PHP code example of yohang / finite

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

    

yohang / finite example snippets


enum DocumentState: string implements State
{
    case DRAFT = 'draft';
    case PUBLISHED = 'published';
    case REPORTED = 'reported';
    case DISABLED = 'disabled';

    public static function getTransitions(): array
    {
        return [
            new Transition('publish', [self::DRAFT], self::PUBLISHED),
            new Transition('clear', [self::REPORTED, self::DISABLED], self::PUBLISHED),
            new Transition('report', [self::PUBLISHED], self::REPORTED),
            new Transition('disable', [self::REPORTED, self::PUBLISHED], self::DISABLED),
        ];
    }
}


class Document
{
    private DocumentState $state = DocumentState::DRAFT;

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

    public function setState(DocumentState $state): void
    {
        $this->state = $state;
    }
}

use Finite\StateMachine;

$document = new Document;

$sm = new StateMachine;

// Can we process a transition ?
$sm->can($document, 'publish');

// Apply a transition
$sm->apply($document, 'publish'); 


enum DocumentState: string implements State
{
    // ...

    public function isDeletable(): bool
    {
        return in_array($this, [self::DRAFT, self::DISABLED]);
    }

    public function isPrintable(): bool
    {
        return in_array($this, [self::PUBLISHED, self::REPORTED]);
    }
}

var_dump($document->getState()->isDeletable());
var_dump($document->getState()->isPrintable());