Skip to content

Instantly share code, notes, and snippets.

@edgrosvenor
Created April 6, 2026 05:39
Show Gist options
  • Select an option

  • Save edgrosvenor/7351cf4283a83504d85a1f915b65dd93 to your computer and use it in GitHub Desktop.

Select an option

Save edgrosvenor/7351cf4283a83504d85a1f915b65dd93 to your computer and use it in GitHub Desktop.
Fat Enums: Using the state machine - transitions and validation
<?php
$status = OrderStatus::Pending;
// Check if transition is valid
$status->canTransitionTo(OrderStatus::Processing); // true
$status->canTransitionTo(OrderStatus::Delivered); // false
// Perform the transition
$newStatus = $status->transitionTo(OrderStatus::Processing);
// Returns OrderStatus::Processing
// Invalid transitions throw
$status->transitionTo(OrderStatus::Delivered);
// InvalidStateTransition: "Cannot transition from Pending to Delivered.
// Valid transitions from Pending: Processing, Cancelled"
// Check from the other direction
OrderStatus::Shipped->canTransitionFrom(OrderStatus::Processing); // true
OrderStatus::Shipped->canTransitionFrom(OrderStatus::Pending); // false
// Final states cannot transition anywhere
OrderStatus::Delivered->canTransitionTo(OrderStatus::Pending); // false
OrderStatus::Delivered->transitionTo(OrderStatus::Pending);
// InvalidStateTransition: "Delivered is a final state and cannot transition"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment