PHPackages                             cosma/simple-state-machine - PHPackages - PHPackages  [Skip to content](#main-content)[PHPackages](/)[Directory](/)[Categories](/categories)[Trending](/trending)[Leaderboard](/leaderboard)[Changelog](/changelog)[Analyze](/analyze)[Collections](/collections)[Log in](/login)[Sign up](/register)

1. [Directory](/)
2. /
3. [Utility &amp; Helpers](/categories/utility)
4. /
5. cosma/simple-state-machine

ActiveLibrary[Utility &amp; Helpers](/categories/utility)

cosma/simple-state-machine
==========================

Simple State Machine

v1.0.3(11y ago)325MITPHPPHP &gt;=5.3

Since Jul 19Pushed 10y ago1 watchersCompare

[ Source](https://github.com/cosma/simple-state-machine)[ Packagist](https://packagist.org/packages/cosma/simple-state-machine)[ RSS](/packages/cosma-simple-state-machine/feed)WikiDiscussions master Synced 1mo ago

READMEChangelogDependencies (2)Versions (5)Used By (0)

SimpleStateMachine - A very simple State Machine
================================================

[](#simplestatemachine----a-very-simple-state-machine)

[![Circle CI](https://camo.githubusercontent.com/c0eaebc24d6ab1d9195884ff51969a45e7ff7efa5c60ccc875cd33036034aa11/68747470733a2f2f636972636c6563692e636f6d2f67682f636f736d612f73696d706c652d73746174652d6d616368696e652e7376673f7374796c653d737667)](https://circleci.com/gh/cosma/simple-state-machine)[![SensioLabsInsight](https://camo.githubusercontent.com/27181ae2f3615b90e8d46e4abe61c6c6e9e865ef1c4860de6964b420751c29f0/68747470733a2f2f696e73696768742e73656e73696f6c6162732e636f6d2f70726f6a656374732f63363364313238622d333134382d343134392d383161382d6563623033646465333535642f6d696e692e706e67)](https://insight.sensiolabs.com/projects/c63d128b-3148-4149-81a8-ecb03dde355d)

- A Simple State Machine without timeouts.
- States can modify a Data object which will be injected in the initial State.
- The State Machine graph can be visualised in a UML diagram generated in different formats.

Table of Contents
-----------------

[](#table-of-contents)

- [Installation](#installation)
- [Usage](#usage)
- [Reference](#reference)
    - [Defining Data Object](#defining-data-object)
    - [Defining States](#defining-states)
    - [Define Conditions](#define-conditions)
    - [Graph Diagram](#graph-diagram)
    - [Export Formats](#export-formats)
    - [DOT Language](#dot-language)
- [Tests](#tests)
- [License](#license)

Installation
------------

[](#installation)

Simple State Machine is installable via [Composer](https://getcomposer.org/)as [cosma/simple-state-machine](https://packagist.org/packages/cosma/simple-state-machine).

```
{
    "require": {
        "cosma/simple-state-machine": "1.0.*"
    }
}
```

Usage
-----

[](#usage)

Let's follow the example of a simple price calculator state machine.

```
namespace \MyProject;

/**
*   Simple State Machine
*/
$priceStateMachine = \Cosma\SimpleStateMachine\StateMachine('Price Calculator State Machine');

/**
*   Your Data object which can be modify by the State Machines
*   Has to implement the interface \Cosma\SimpleStateMachine\InterfaceData
*/
$price = new \YourProject\Price();

/**
*   Start State of the State Machine
*   Has to extends the abstract \Cosma\SimpleStateMachine\AbstractState
*/
$initialPriceState = \YourProject\PriceStateMachine\States\InitialPrice($price);

/**
*   Simple State Machine cannot run without setting the start State
*/
$priceStateMachine->setState($initialPriceState);

/**
*   Running the State Machine
*   During this process the Data object will be modified depending on teh configuration of the Machine
*/
$priceStateMachine->run();

/**
*   Retrieve the Data object at the end of the process
*/
$finalPrice = $priceStateMachine->getState()->getData();

/**
*   Generate the Diagram of the State Machine.
*   Choose the format
*/
$graphic = new Graphic('svg');
$diagramSVG = $priceStateMachine->draw($graphic);
echo $diagramSVG;
```

Reference
---------

[](#reference)

### Defining Data Object

[](#defining-data-object)

The Data object can be modify by the State Machines transitions and State.

The Data class must implement the interface \\Cosma\\SimpleStateMachine\\InterfaceData.

InterfaceData is a empty interface but is used to force Type hinting.

```
namespace \MyProject\PriceStateMachine;

class Price implements \Cosma\SimpleStateMachine\InterfaceData
{
    /**
    *   @var float
    */
    private $value;

    public function __constructor()
    {
        $this->value = $this->getPriceFromDB();
    }

    /**
    *    getters, setters and other functions
    */
    ...
}
```

### Defining States

[](#defining-states)

All states must extend the class \\Cosma\\SimpleStateMachine\\AbstractState

```
namespace \MyProject\PriceStateMachine\States;

class AddVATState extends \Cosma\SimpleStateMachine\AbstractState
{
    /**
    *   Set the label for this State used in State Machine diagram
    */
    public function getLabel()
    {
        return 'Add VAT Tax';
    }

    /**
    *   Modify the Data object
    */
    protected function process()
    {
        $price = $this->getData();
        $price->setValue($price->getValue() * 1.19);
        ...
    }

    /**
    *   Configure the Transitions from this State to another States or itself in case of a loop
    *   You may set in what Condition that Transition takes place
    *   The order to check upon the validity of conditions and forward to next State is from up to down
    */
    protected function configureAvailableTransitions()
    {
        $this->addTransition(
                            '\YourProject\PriceStateMachine\States\AddDiscount',
                            '\YourProject\PriceStateMachine\Conditions\IfGreaterThan1000'
        );

        $this->addTransition('NewStateClass', 'ConditionClass');

        $this->addTransition('\YourProject\PriceStateMachine\States\AddDiscount');
        ...
    }
}
```

### Defining Conditions

[](#defining-conditions)

A Transition between states is possible directly when there is no condition or, if there is a condition, only when that condition is true.

All Conditions must extend \\Cosma\\SimpleStateMachine\\AbstractCondition class

```
namespace namespace \MyProject\PriceStateMachine\Conditions;

class SomeWildCondition extends \Cosma\SimpleStateMachine\AbstractCondition
{
    /**
    *   @return string
    */
    public function getLabel()
    {
        return "Some Wild Condition";
    }

    /**
    *   @return bool
    */
    public function isTrue()
    {
        $data = $this->getData();
        return $this->checkSomething($data);
    }
    ...
}
```

### Graph Diagram

[](#graph-diagram)

You can easily visualise the State Machine Diagram

```
namespace \MyProject;

/**
*   Generate the Diagram of the State Machine.
*   Choose the format
*/
$graphic = new Graphic('svg');
$diagramSVG = $priceStateMachine->draw($graphic);

echo $diagramSVG;
```

### Export Formats

[](#export-formats)

The output is delivered in various formats.

The most used export formats are:

- [PNG](https://raw.githubusercontent.com/cosma/simple-state-machine/master/tests/Example/Draw/Formats/PNG.png)
- [PDF](https://raw.githubusercontent.com/cosma/simple-state-machine/master/tests/Example/Draw/Formats/PDF.pdf)
- [SVG](https://raw.githubusercontent.com/cosma/simple-state-machine/master/tests/Example/Draw/Formats/SVG.xml)
- [DOT](https://raw.githubusercontent.com/cosma/simple-state-machine/master/tests/Example/Draw/Formats/DOT.dot)
- [EPS](https://raw.githubusercontent.com/cosma/simple-state-machine/master/tests/Example/Draw/Formats/EPS.eps)
- [TIFF](https://raw.githubusercontent.com/cosma/simple-state-machine/master/tests/Example/Draw/Formats/TIFF.tiff)
- [JPG](https://raw.githubusercontent.com/cosma/simple-state-machine/master/tests/Example/Draw/Formats/JPG.jpg) (low quality)
- [GIF](https://raw.githubusercontent.com/cosma/simple-state-machine/master/tests/Example/Draw/Formats/GIF.gif) (low quality)
- [BMP](https://raw.githubusercontent.com/cosma/simple-state-machine/master/tests/Example/Draw/Formats/BMP.bmp) (low quality)

All supported formats are the DOT output formats: bmp, canon, cgimage, cmap, cmapx, cmapx\_np, dot, eps, exr, fig, gif, gv, icns, ico, imap, imap\_np, ismap, jp2, jpe, jpeg, jpg, pct, pdf, pic, pict, plain, plain-ext, png, pov, ps, ps2, psd, sgi, svg, svgz, tga, tif, tiff, tk, vml, vmlz, x11, xdot, xdot1.2, xdot1.4, xlib

### DOT Language

[](#dot-language)

Stands for graph description language and you can read more [here](http://en.wikipedia.org/wiki/DOT_(graph_description_language))

To take fully advantage of style attributes you need to know DOT language.

When defining a Condition or a State, you can easily modify the protected $styleAttributes property and overwrite the default style for a State or a Condition.

By this you can manipulate the color, font and shape of States and Conditions

```
namespace \MyProject\PriceStateMachine\States;

class MyState extends \Cosma\SimpleStateMachine\AbstractState
{
    ...
    /**
    *   An array of DOT attributes to overwrite the default style of a State/Condition
    */
    protected $styleAttributes = array(
        'fillcolor' => '#A8CE9F',
        'style' => 'filled',
        'fontcolor' => '#000000',
        'fontsize' => 12,
        'penwidth' => 1,
    );
    ...
}
```

DOT Useful Links:

1. Drawing graphs with DOT - [download a pdf](http://www.graphviz.org/Documentation/dotguide.pdf)
2. Node Shapes - [shapes of a node](http://www.graphviz.org/doc/info/shapes.html)

Tests
-----

[](#tests)

```
vendor/phpunit/phpunit/phpunit --coverage-text  --coverage-html=tests/coverage tests
```

License
-------

[](#license)

Released under the MIT License, see LICENSE.

###  Health Score

27

—

LowBetter than 49% of packages

Maintenance20

Infrequent updates — may be unmaintained

Popularity10

Limited adoption so far

Community7

Small or concentrated contributor base

Maturity61

Established project with proven stability

 Bus Factor1

Top contributor holds 100% of commits — single point of failure

How is this calculated?**Maintenance (25%)** — Last commit recency, latest release date, and issue-to-star ratio. Uses a 2-year decay window.

**Popularity (30%)** — Total and monthly downloads, GitHub stars, and forks. Logarithmic scaling prevents top-heavy scores.

**Community (15%)** — Contributors, dependents, forks, watchers, and maintainers. Measures real ecosystem engagement.

**Maturity (30%)** — Project age, version count, PHP version support, and release stability.

###  Release Activity

Cadence

Every ~89 days

Total

3

Last Release

4142d ago

### Community

Maintainers

![](https://www.gravatar.com/avatar/a1695d8d888c44c734f8a2d8151eadc456fa1605179acab2ba14d090d4b27e9a?d=identicon)[cosma](/maintainers/cosma)

---

Top Contributors

[![cosma](https://avatars.githubusercontent.com/u/1668991?v=4)](https://github.com/cosma "cosma (111 commits)")

---

Tags

state-machinenon persistentgraph generation

###  Code Quality

TestsPHPUnit

### Embed Badge

![Health badge](/badges/cosma-simple-state-machine/health.svg)

```
[![Health](https://phpackages.com/badges/cosma-simple-state-machine/health.svg)](https://phpackages.com/packages/cosma-simple-state-machine)
```

###  Alternatives

[metabor/statemachine

Statemachine in PHP 5.3

103150.7k2](/packages/metabor-statemachine)[ringierimu/state-workflow

Laravel State Workflow provide tools for defining and managing workflows and activities with ease.

3251.1k](/packages/ringierimu-state-workflow)[mouadziani/xstate

State machine library to play with any complex behavior of your PHP objects

866.7k](/packages/mouadziani-xstate)[shrink0r/workflux

Finite state machine for php.

375.6k1](/packages/shrink0r-workflux)[tarfin-labs/event-machine

Event-driven state machines for Laravel with event sourcing, type-safe context, and full audit trail.

188.5k](/packages/tarfin-labs-event-machine)[phpmentors/stagehand-fsm

A finite state machine

361.1k](/packages/phpmentors-stagehand-fsm)

PHPackages © 2026

[Directory](/)[Categories](/categories)[Trending](/trending)[Changelog](/changelog)[Analyze](/analyze)
