mini\Hooks\StateMachine class

Documentation

A state machine which validates that states only transition to legal target states.

Provides hooks for entering, exiting, entered, and exited states, allowing fine-grained control over state transitions. Prevents invalid transitions and re-entrant state changes.

Example Usage

$machine = new StateMachine([
    [Phase::Bootstrap, Phase::Request],  // Bootstrap can only go to Request
    [Phase::Request],                    // Request is terminal
]);

$machine->onEnteringState(Phase::Request, function($old, $new) {
    echo "Entering request phase";
});

$machine->trigger(Phase::Request);  // Transitions and fires hooks

Inheritance

Extends: mini\Hooks\Dispatcher

Implements: Stringable

Properties (9)

protected readonly array $transitions

Valid state transitions for the state machine.

protected UnitEnum|string|int $state

The current state

protected UnitEnum|string|int|null $transitioningTo

State being transitioned to (null if not transitioning)

protected array $listeners

Subscribers to all state changes

protected array $enteringListeners

Subscribers for entering a particular state

protected array $exitingListeners

Subscribers for exiting a particular state

protected array $enteredListeners

Subscribers for completed entering a particular state

protected array $exitedListeners

Subscribers for completed exiting a particular state

protected array $exitCurrentListeners

Subscribers to get notified ONCE when the current state exits

Methods (27)

Configure the states and valid transitions

Return the current state

String representation of current state

Transition to a new state

Register a listener that fires once when the current state exits

Subscribe to when a particular state is about to be entered

Subscribe to when a particular state has been entered

Subscribe to when a particular state is about to be exited

Subscribe to when a particular state has been exited

Subscribe to get notified about all state transitions

Unsubscribe from all state transition events

Assert we're not currently transitioning

Assert that the provided states exist in the state machine

Assert that the provided state is a valid target from current state

Normalize state arguments (handles arrays, recursion)

Convert state to scalar value for array keys

Get a description of the event dispatcher

Get the filename where this event dispatcher was created

Get the line number where this event dispatcher was created

Configure event loop integration

Invoke all listeners in an array

Handle an exception from a listener

Filter array to remove specific values

Schedule a function to run when runEvents() is called

Run all scheduled events

Remove values from multiple arrays by reference

Invoke a listener with exception handling

Source

src/Hooks/StateMachine.php:33-390