systream/state-machine

1.1.2 2016-06-20 19:17 UTC

This package is not auto-updated.

Last update: 2024-04-27 17:20:26 UTC


README

Installation

You can install this package via packagist.org with composer.

composer require systream/state-machine

composer.json:

"require": {
    "systream/state-machine": "1.*"
}

Usage examples

Setup

You need to add transitions to state machine.

$stateMachine = new StateMachine(new \Systream\EventDispatcher());

$inStock = new StateMachine\State('In stock');
$ordered = new StateMachine\State('Ordered');
$shippingInProcess = new StateMachine\State('Shipping in process');
$deliveredToClient = new StateMachine\State('Order is at client');

$stateMachine->addTransition(
	new GenericTransition('Order'), $inStock, $ordered
);

$stateMachine->addTransition(
	new GenericTransition('Cancel order'), $ordered, $inStock
);

$stateMachine->addTransition(
	new GenericTransition('Shipping'), $ordered, $shippingInProcess
);

$stateMachine->addTransition(
	new GenericTransition('Handover to client'), $shippingInProcess, $deliveredToClient
);

Custom transitions

You have to implement the \Systream\StateMachine\TransitionInterface interface to create custom transition

Process Transition

StateObject

To use state machine you need an object which has state. process method expect \Systream\StateMachine\State\StateObjectInterface interface.

So you need to implement it, or just use \Systream\StateMachine\State\StateObjectTrait.

Can

Testing, whether it can change the status to the target state

$product = new DummyStateObject();
$product->setState($inStock);
$stateMachine->can($product, $ordered); // will return true
$stateMachine->can($product, $deliveredToClient); // will return false

Process

Set project state to In Stock and process it to Ordered.

$product = new DummyStateObject();
$product->setState($inStock);
$stateMachine->process($product, $ordered);

Set state without transition will trow an \Systream\StateMachine\Exception\CantSetStatusException exception.

$product = new DummyStateObject();
$product->setState($inStock);
$stateMachine->process($product, $deliveredToClient);

Get available states

$states = $stateMachine->getStates();

It will return array of \Systream\StateMachine\State\StateInterface objects

Get next states

This method will return of the next possible states of an state object:

$product = new DummyStateObject();
$states = $stateMachine->getNextStates($product);

It will return array of \Systream\StateMachine\State\StateInterface objects

Visualization

With this library you are able to generate an image with the states and transitions. To get this work you need to install graphviz.

$doFileGenerator = new StateMachine\DotFileGenerator();
$image = $doFileGenerator->getImage($stateMachine);
file_put_contents('my_flow_chart.png', $image);

example-flow

Test

Build Status