PHP code example of bradliu / heshen

1. Go to this page and download the library: Download bradliu/heshen 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/ */

    

bradliu / heshen example snippets



use Runner\Heshen\Contracts\StatefulInterface;

class Document implements StatefulInterface
{
    protected $state = 'a';

    public function getState(): string
    {
        return $this->state;
    }

    public function setState(string $state): void
    {
        echo "\nsetting\n";
        $this->state = $state;
    }
}




use Runner\Heshen\Blueprint;
use Runner\Heshen\State;
use Runner\Heshen\Contracts\StatefulInterface;

class Graph extends Blueprint {
    protected function configure(): void
    {
        $this->addState('a', State::TYPE_INITIAL);
        $this->addState('b', State::TYPE_NORMAL);
        $this->addState('c', State::TYPE_NORMAL);
        $this->addState('d', State::TYPE_FINAL);

        $this->addTransition('one', 'a', 'b');
        $this->addTransition('two', 'b', 'c', function (StatefulInterface $stateful, array $parameters) {
            return ($parameters['number'] ?? 0) > 5;
        });
    }

    protected function preOne(StatefulInterface $stateful, array $parameters = [])
    {
        echo "before apply transition 'one'\n";
    }
    
    protected function postOne(StatefulInterface $stateful, array $parameters = [])
    {
        echo "after apply transition 'one'\n";
    }
}



use Runner\Heshen\Machine;

$machine = new Machine(new Document, new Graph);

var_dump($machine->can('one')); // output: bool(true)
var_dump($machine->can('two')); // output: bool(false)

$machine->apply('one');
/*
 * output:
 * before apply transition 'one'
 * after apply transition 'one'
 */

var_dump($machine->can('two', ['number' => 1])); // output: bool(false)
var_dump($machine->can('two', ['number' => 6])); // output: bool(true)




use Runner\Heshen\Factory;

$factory = new Factory([
    Document::class => Graph::class,
]);

$document = new Document;

$machine = $factory->make($document);

var_dump($machine->can('one')); // output: bool(true)