PHP code example of llbbl / enum-state-machine

1. Go to this page and download the library: Download llbbl/enum-state-machine 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/ */

    

llbbl / enum-state-machine example snippets


use EnumStateMachine\Attributes\Transition;
use EnumStateMachine\Attributes\StateMachineConfig;

#[StateMachineConfig(dispatchEvents: true)]
#[Transition(to: self::Cancelled, guard: NotYetShippedGuard::class)] // wildcard: any state → Cancelled
enum OrderState: string
{
    case Pending = 'pending';

    #[Transition(to: self::Processing, after: ChargeCreditCardHook::class)]
    case Paid = 'paid';

    #[Transition(
        to: self::Shipped,
        guard: HasValidAddressGuard::class,
        before: ReserveInventoryHook::class,
        after: SendTrackingEmailHook::class,
    )]
    case Processing = 'processing';

    case Shipped = 'shipped';
    case Cancelled = 'cancelled';
}

use EnumStateMachine\StateMachine;
use EnumStateMachine\Exceptions\InvalidTransitionException;

// Construct from your model's enum-typed state (`$order->state` is typed
// `OrderState`) for full PHPStan narrowing of `transitionTo()` / `getCurrentState()`.
$machine = new StateMachine($order->state);

if ($machine->can(OrderState::Shipped, context: $order)) {
    // show the "Ship" button
}

try {
    $order->state = $machine->transitionTo(OrderState::Shipped, context: $order);
} catch (InvalidTransitionException $e) {
    // no such transition, or a guard rejected it
}
bash
just php setup      # Homebrew C libs + builds the pinned PHP against openssl@3
just install        # composer install