-
-
Notifications
You must be signed in to change notification settings - Fork 0
Console Commands
Master the powerful CLI tools for managing Laravel Statecraft state machines.
Laravel Statecraft provides comprehensive console commands for:
- Managing state machines - Create, list, and inspect definitions
- Validation - Ensure YAML files are correct
- Export - Generate diagrams and documentation
- Code generation - Create guards, actions, and examples
- Maintenance - Cleanup and optimization
# List all available commands
php artisan list statecraft
# Get help for any command
php artisan help statecraft:make
Generate a new state machine YAML file with optional PHP classes:
# Basic state machine
php artisan statecraft:make OrderStateMachine
# With model specification
php artisan statecraft:make OrderStateMachine --model=Order
# With full namespace
php artisan statecraft:make OrderStateMachine --model="App\\Models\\Order"
# Generate in custom directory
php artisan statecraft:make OrderStateMachine --path=workflows
# Generate with example guards and actions
php artisan statecraft:make OrderStateMachine --with-examples
# Interactive mode
php artisan statecraft:make OrderStateMachine --interactive
Generated Files:
state-machines/
βββ OrderStateMachine.yaml
app/
βββ Guards/
β βββ CanSubmitGuard.php
β βββ IsManagerGuard.php
βββ Actions/
βββ NotifyReviewerAction.php
βββ SendConfirmationEmailAction.php
Example Generated YAML:
name: OrderStateMachine
model: App\Models\Order
initial_state: pending
states:
- name: pending
description: Order awaiting processing
- name: approved
description: Order approved
- name: rejected
description: Order rejected
transitions:
- name: approve
from: pending
to: approved
guard: CanApproveGuard
action: SendApprovalNotificationAction
- name: reject
from: pending
to: rejected
guard: CanRejectGuard
action: SendRejectionNotificationAction
Display all state machine definitions with summary information:
# List all state machines
php artisan statecraft:list
# List with detailed information
php artisan statecraft:list --verbose
# List from custom directory
php artisan statecraft:list --path=custom/workflows
# Filter by model
php artisan statecraft:list --model=Order
# Sort by different criteria
php artisan statecraft:list --sort=name
php artisan statecraft:list --sort=states
php artisan statecraft:list --sort=transitions
Output:
+------------------+------------------+--------+-------------+---------+-------+
| Name | Model | States | Transitions | Initial | Field |
+------------------+------------------+--------+-------------+---------+-------+
| OrderStateMachine| App\Models\Order | 5 | 6 | pending | status|
| ArticleWorkflow | App\Models\Article| 4 | 5 | draft | state |
| UserRegistration | App\Models\User | 3 | 3 | pending | status|
+------------------+------------------+--------+-------------+---------+-------+
Total: 3 state machines found
Display detailed information about a specific state machine:
# Show state machine details
php artisan statecraft:show OrderStateMachine
# Show raw YAML content
php artisan statecraft:show OrderStateMachine --raw
# Show with guard/action details
php artisan statecraft:show OrderStateMachine --verbose
# Show from custom directory
php artisan statecraft:show OrderStateMachine --path=workflows
Detailed Output:
State Machine: OrderStateMachine
=====================================
Configuration:
File: state-machines/OrderStateMachine.yaml
Model: App\Models\Order
Initial State: pending
State Field: status
States (5):
β pending (initial)
β paid
β processing
β shipped
β delivered
Transitions (6):
pay: pending β paid
Guard: PaymentGuard β
Action: ProcessPaymentAction β
process: paid β processing
Guards: InventoryGuard, AddressGuard β
Action: StartProcessingAction β
ship: processing β shipped
Guard: ShippingGuard β
Actions: CreateShipmentAction, SendTrackingEmailAction β
deliver: shipped β delivered
Action: MarkAsDeliveredAction β
cancel: [pending, paid, processing] β cancelled
Action: CancelOrderAction β
Statistics:
Total States: 5
Total Transitions: 6
Guarded Transitions: 4 (67%)
Transitions with Actions: 6 (100%)
Average Transitions per State: 1.2
Validate YAML files and class dependencies:
# Validate all state machines
php artisan statecraft:validate --all
# Validate specific state machine
php artisan statecraft:validate OrderStateMachine
# Validate with detailed output
php artisan statecraft:validate --all --verbose
# Validate only YAML syntax
php artisan statecraft:validate --all --yaml-only
# Validate only class dependencies
php artisan statecraft:validate --all --classes-only
# Custom validation path
php artisan statecraft:validate --all --path=workflows
# Exit with error code on failure (CI/CD)
php artisan statecraft:validate --all --strict
Validation Output:
Validating Laravel Statecraft Definitions
=========================================
β OrderStateMachine.yaml
β YAML syntax valid
β Required fields present
β States defined correctly
β Transitions valid
β Guards exist: PaymentGuard, InventoryGuard
β Actions exist: ProcessPaymentAction, StartProcessingAction
β ArticleWorkflow.yaml
β YAML syntax valid
β Required fields present
β States defined correctly
β Transition validation failed
- Invalid state reference: 'published' not defined in states
β Guard not found: NonExistentGuard
β Actions exist: PublishArticleAction
Summary:
Total files: 2
Valid: 1
Invalid: 1
Warnings: 0
Export state machines to various formats for documentation and visualization:
# Export to Mermaid diagram
php artisan statecraft:export OrderStateMachine --format=mermaid
# Export to JSON
php artisan statecraft:export OrderStateMachine --format=json
# Export to Markdown documentation
php artisan statecraft:export OrderStateMachine --format=markdown
# Export to file
php artisan statecraft:export OrderStateMachine --format=mermaid --output=docs/order-workflow.md
# Export all state machines
php artisan statecraft:export --all --format=mermaid --output=docs/workflows/
# Custom styling for Mermaid
php artisan statecraft:export OrderStateMachine --format=mermaid --style=github
stateDiagram-v2
[*] --> pending
pending --> paid: pay
paid --> processing: process
processing --> shipped: ship
shipped --> delivered: deliver
pending --> cancelled: cancel
paid --> cancelled: cancel
processing --> cancelled: cancel
delivered --> [*]
cancelled --> [*]
{
"name": "OrderStateMachine",
"model": "App\\Models\\Order",
"initial_state": "pending",
"states": [
{
"name": "pending",
"description": "Order awaiting payment"
},
{
"name": "paid",
"description": "Payment confirmed"
}
],
"transitions": [
{
"name": "pay",
"from": "pending",
"to": "paid",
"guard": "PaymentGuard",
"action": "ProcessPaymentAction"
}
]
}
# OrderStateMachine
**Model:** App\Models\Order
**Initial State:** pending
**State Field:** status
## States
- **pending** - Order awaiting payment
- **paid** - Payment confirmed
- **processing** - Order being prepared
- **shipped** - Order dispatched
- **delivered** - Order received
## Transitions
### pay: pending β paid
- **Guard:** PaymentGuard
- **Action:** ProcessPaymentAction
### process: paid β processing
- **Guards:** InventoryGuard, AddressGuard
- **Action:** StartProcessingAction
Generate guard and action classes from YAML definitions:
# Generate all classes for a state machine
php artisan statecraft:generate OrderStateMachine
# Generate only guards
php artisan statecraft:generate OrderStateMachine --guards-only
# Generate only actions
php artisan statecraft:generate OrderStateMachine --actions-only
# Generate with custom namespace
php artisan statecraft:generate OrderStateMachine --guards-namespace="App\\OrderGuards"
# Generate with stubs
php artisan statecraft:generate OrderStateMachine --use-stubs
# Force overwrite existing files
php artisan statecraft:generate OrderStateMachine --force
# Generate for all state machines
php artisan statecraft:generate --all
Generated Guard Example:
<?php
namespace App\Guards;
use Grazulex\LaravelStatecraft\Contracts\Guard;
use Illuminate\Database\Eloquent\Model;
class PaymentGuard implements Guard
{
public function passes(Model $model, array $context = []): bool
{
// TODO: Implement payment validation logic
return true;
}
}
Perform maintenance operations on state machines and history:
# Cleanup old history records
php artisan statecraft:cleanup --history --days=365
# Cleanup for specific model
php artisan statecraft:cleanup --history --model="App\\Models\\Order" --days=90
# Dry run to see what would be cleaned
php artisan statecraft:cleanup --history --days=365 --dry-run
# Clear state machine cache
php artisan statecraft:cleanup --cache
# Optimize state machine definitions
php artisan statecraft:cleanup --optimize
# Full cleanup
php artisan statecraft:cleanup --all
Manage state machine definition caching:
# Cache all state machine definitions
php artisan statecraft:cache
# Clear state machine cache
php artisan statecraft:cache:clear
# Show cache statistics
php artisan statecraft:cache:stats
# Warm cache for specific state machine
php artisan statecraft:cache OrderStateMachine
Debug and troubleshoot state machine issues:
# Debug specific model instance
php artisan statecraft:debug --model="App\\Models\\Order" --id=123
# Show available transitions for model
php artisan statecraft:debug --model="App\\Models\\Order" --id=123 --transitions
# Debug guard resolution
php artisan statecraft:debug --guard=PaymentGuard --model="App\\Models\\Order" --id=123
# Debug action resolution
php artisan statecraft:debug --action=ProcessPaymentAction
# Show state machine configuration
php artisan statecraft:debug OrderStateMachine --config
# Trace state machine resolution
php artisan statecraft:debug OrderStateMachine --trace
Debug Output:
Debugging Order #123
===================
Current State: pending
State Machine: OrderStateMachine
Available Transitions:
β pay (PaymentGuard passes)
β process (Guard not satisfied)
β cancel (No guard required)
Guard Analysis:
PaymentGuard:
β Total > 0: $100.00
β Customer has payment method
β Payment service available
ProcessingGuard:
β Order not paid yet
History (last 5):
2024-01-01 10:00:00 | null β pending (created)
# Validate all state machines
php artisan statecraft:validate --all
# Export all to documentation
php artisan statecraft:export --all --format=markdown --output=docs/
# Generate classes for all state machines
php artisan statecraft:generate --all
# List statistics for all
php artisan statecraft:stats --all
# Validation for CI/CD (exits with error code on failure)
php artisan statecraft:validate --all --strict --quiet
# Generate documentation in CI
php artisan statecraft:export --all --format=markdown --output=docs/state-machines/
# Check for missing classes
php artisan statecraft:validate --all --classes-only --strict
Configure commands in config/statecraft.php
:
'commands' => [
'default_path' => base_path('state-machines'),
'export_path' => base_path('docs/state-machines'),
'generate_namespace' => 'App',
'validation' => [
'strict_mode' => false,
'check_classes' => true,
'validate_yaml' => true,
],
'export' => [
'mermaid_theme' => 'default',
'include_descriptions' => true,
'include_metadata' => false,
],
]
Create aliases for frequently used commands:
# In your .bashrc or .zshrc
alias sc-list="php artisan statecraft:list"
alias sc-show="php artisan statecraft:show"
alias sc-validate="php artisan statecraft:validate --all"
alias sc-export="php artisan statecraft:export"
# 1. Create new state machine
php artisan statecraft:make UserOnboarding --model=User --interactive
# 2. Validate the YAML
php artisan statecraft:validate UserOnboarding
# 3. Generate PHP classes
php artisan statecraft:generate UserOnboarding
# 4. Show the structure
php artisan statecraft:show UserOnboarding --verbose
# 5. Export documentation
php artisan statecraft:export UserOnboarding --format=markdown --output=docs/
# Pre-deployment validation
php artisan statecraft:validate --all --strict
# Cache state machines for performance
php artisan statecraft:cache
# Generate missing classes
php artisan statecraft:generate --all --guards-only
# Export updated documentation
php artisan statecraft:export --all --format=mermaid --output=public/docs/
# Weekly cleanup
php artisan statecraft:cleanup --history --days=90
# Monthly optimization
php artisan statecraft:cleanup --optimize --cache
# Validate after updates
php artisan statecraft:validate --all --verbose
- Validate frequently - Run validation before deployments
- Use aliases - Create shortcuts for common commands
- Automate exports - Generate documentation automatically
- Monitor cleanup - Regular maintenance prevents bloat
- Debug systematically - Use debug commands for troubleshooting
# GitHub Actions example
- name: Validate State Machines
run: php artisan statecraft:validate --all --strict
- name: Generate Documentation
run: php artisan statecraft:export --all --format=markdown --output=docs/
- name: Cache State Machines
run: php artisan statecraft:cache
Now that you understand the CLI tools, explore:
- βοΈ Configuration Guide - Configure command behavior
- π§ͺ Testing Guide - Use commands in testing
- π State History - Manage history with commands
- π‘ Examples Collection - Command usage examples
- π¦ Order Workflow - Real-world command usage
- π User Workflow - Advanced CLI patterns
- π― Events System - Debug events with CLI
- π‘οΈ Guards & Actions - Generate and validate classes
Ready to explore advanced workflow patterns? Check out π User Workflow Guide!
π― Laravel Statecraft - Advanced State Machine Implementation for Laravel
Navigate: π Home | π¦ Installation | π Basic Guide | π YAML Config | π‘ Examples
Resources: π‘οΈ Guards & Actions | π― Events | π State History | π§ͺ Testing | π¨ Commands
π Community Resources:
Made with β€οΈ for the Laravel community β’ Contribute β’ License