sokil/php-state

State machine

0.5.3 2020-02-13 13:08 UTC

This package is auto-updated.

Last update: 2024-10-18 01:52:57 UTC


README

Implementation of finite state machine on PHP.

Latest Stable Version Total Downloads Build Status Coverage Status

Installation

You can install library through Composer:

{
    "require": {
        "sokil/php-state": "dev-master"
    }
}

Basic Usage

<?php

// create state machine builder
$machineBuilder = new MachineBuilder();

// configure states
$machineBuilder
    ->addState(function(StateBuilder $builder) {
        $builder->setName('new');
    })
    ->addState(function(StateBuilder $builder) {
        $builder
            ->setName('in_progress')
            ->setMetadata([
                'label' => 'In progress'
            ]);
    })
    ->addState(function(StateBuilder $builder) {
        $builder->setName('done');
    });
    
// set initial state
$machineBuilder->setInitialState('new');

// configure transitions between states
$machineBuilder
    ->addTransition(function(TransitionBuilder $builder) {
        $builder
            ->setName('set_in_progress')
            ->setInitialStateName('new')
            ->setResultingStateName('in_progress')
            ->setAcceptCondition(function() {
                // conditions when accepted to transit from "new" state to "in_progress"
                return true;
            });
    })
    ->addTransition(function(TransitionBuilder $builder) {
        $builder
            ->setName('set_done')
            ->setInitialStateName('in_progress')
            ->setResultingStateName('done');
    });
    
// create machine
$machine = $machineBuilder->getMachine();

// process transition
$state = $machine->process('set_in_progress')->getCurrentState();

Configuration

Machine may be configured directly in code, as in sample above. But also it may be configured by using configuration in files of different formats. Currenly supported are YAML, JSON and php array files. Exaples of configs may be viewed here.

In common case structure of config is:

stateName1:
  initial: true
  transitions:
    transition1Name:
      resultingState: stateName2
    to_rejected:
      resultingState: stateName3

stateName2:
  transitions:
  ...
<?php

// YAML
$configuration = new YamlConfiguration('config.yaml');

// PHP Array
$configuration = new ArrayConfiguration('config.php');
// or
$configuration = new ArrayConfiguration([...state configuration...]);

// JSON
$configuration = new JsonConfiguration('config.json');

// Configure
$machineBuilder = new MachineBuilder();
$machine = $machineBuilder->configure($configuration)->getMachine();

By default, YamlConfiguration uses pecl extension, but if there is no possibility to install this extension on server, you can use Symfony's YAML component.

<?php
$configuration = new YamlConfiguration('config.yaml', ['pecl' => false]);

This also require you to add dependency on symfony/yaml to your composer.json.