Finite

A PHP Finite State Machine

Finite is a state machine library that gives you ability to manage the state of a PHP object through a graph of states and transitions.

Overview

Define your workflow / state graph

<?php

$document     = new MyDocument;
$stateMachine = new Finite\StateMachine\StateMachine;
$loader       = new Finite\Loader\ArrayLoader([
    'class'  => 'MyDocument',
    'states' => [
        'draft'    => ['type' => 'initial', 'properties' => []],
        'proposed' => ['type' => 'normal',  'properties' => []],
        'accepted' => ['type' => 'final',   'properties' => []],
        'refused'  => ['type' => 'final',   'properties' => []],
    ],
    'transitions' => [
        'propose' => ['from' => ['draft'],    'to' => 'proposed'],
        'accept'  => ['from' => ['proposed'], 'to' => 'accepted'],
        'refuse'  => ['from' => ['proposed'], 'to' => 'refused'],
    ]
]);

$loader->load($stateMachine);
$stateMachine->setObject($document);
$stateMachine->initialize();

Define your object

<?php

class MyDocument implements Finite\StatefulInterface
{
    private $state;
    public function getFiniteState()
    {
        return $this->state;
    }
    public function setFiniteState($state)
    {
        $this->state = $state;
    }
}

Work with states & transitions

<?php

echo $stateMachine->getCurrentState();
// => "draft"

var_dump($stateMachine->can('accept'));
// => bool(false)

var_dump($stateMachine->can('propose'));
// => bool(true)

$stateMachine->apply('propose');
echo $stateMachine->getCurrentState();
// => "proposed"

Contribute

Contributions are welcome !

Finite follows PSR-2 code, and accept pull-requests on the GitHub repository.

If you’re a beginner, you will find some guidelines about code contributions at Symfony.