Created
April 6, 2026 05:39
-
-
Save edgrosvenor/7351cf4283a83504d85a1f915b65dd93 to your computer and use it in GitHub Desktop.
Fat Enums: Using the state machine - transitions and validation
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| <?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