PHP code example of potfur / statemachine

1. Go to this page and download the library: Download potfur/statemachine library. Choose the download type require.

2. Extract the ZIP file and open the index.php.

3. Add this code to the index.php.
    
        
<?php
require_once('vendor/autoload.php');

/* Start to develop here. Best regards https://php-download.com/ */

    

potfur / statemachine example snippets


$commandResults = [
    true, // from new to pending
    false, // from pending to error (onStateWasSet)
    true, // from error to pending (onStateWasSet)
    true, // from pending to done (onStateWasSet)
];

$command = function () use (&$commandResults) {
    if (!count($commandResults)) {
        throw new \InvalidArgumentException('Out of results');
    }

    return array_shift($commandResults);
};

$schema = [
    'name' => 'testSchema',
    'initialState' => 'new',
    'states' => [
        [
            'name' => 'new',
            'events' => [
                [
                    'name' => 'goPending',
                    'targetState' => 'pending',
                    'errorState' => 'error',
                    'command' => $command,
                ]
            ],
        ],
        [
            'name' => 'pending',
            'events' => [
                [
                    'name' => StateMachine::ON_STATE_WAS_SET,
                    'targetState' => 'done',
                    'errorState' => 'error',
                    'command' => $command
                ]
            ],
        ],
        [
            'name' => 'error',
            'events' => [
                [
                    'name' => StateMachine::ON_STATE_WAS_SET,
                    'targetState' => 'pending',
                    'errorState' => 'error',
                    'command' => $command
                ]
            ],
        ],
        [
            'name' => 'done',
            'events' => [],
        ]
    ]
];

$process = (new ArrayFactory($schema))->getProcess();

$payload = PayloadEnvelope::wrap('context');

$machine = new StateMachine($process);
$history = $machine->triggerEvent('goPending', $payload);