-
-
Notifications
You must be signed in to change notification settings - Fork 0
Console Commands
Laravel Statecraft provides a comprehensive set of Artisan commands to help you manage state machines, generate components, and troubleshoot issues during development.
Generate a new state machine with YAML definition and supporting files:
# Create a basic state machine
php artisan statecraft:make OrderStateMachine --model=Order
# Create with custom directory
php artisan statecraft:make UserWorkflow --model=User --path=workflows
# Create with example guards and actions
php artisan statecraft:make ArticleWorkflow --model=Article --with-examples
Options:
-
--model
: The Eloquent model class name -
--path
: Custom directory for YAML file -
--with-examples
: Generate example guard and action classes -
--force
: Overwrite existing files
Display all available state machines:
php artisan statecraft:list
Output example:
+------------------+------------------+---------------+
| State Machine | Model | States |
+------------------+------------------+---------------+
| OrderStateMachine| App\Models\Order | 6 states |
| UserWorkflow | App\Models\User | 4 states |
+------------------+------------------+---------------+
Validate state machine configuration:
# Validate specific state machine
php artisan statecraft:validate OrderStateMachine
# Validate all state machines
php artisan statecraft:validate --all
# Validate with verbose output
php artisan statecraft:validate OrderStateMachine --verbose
Generate a new guard class:
# Basic guard
php artisan statecraft:make:guard PaymentGuard
# Guard with custom namespace
php artisan statecraft:make:guard Billing/CreditCheckGuard
# Guard with context support
php artisan statecraft:make:guard ValidationGuard --with-context
Generated guard example:
<?php
namespace App\StateMachine\Guards;
use Grazulex\LaravelStatecraft\Contracts\Guard;
use Illuminate\Database\Eloquent\Model;
class PaymentGuard implements Guard
{
public function check(Model $model, string $from, string $to): bool
{
// TODO: Implement your guard logic
return true;
}
}
Generate a new action class:
# Basic action
php artisan statecraft:make:action ProcessPayment
# Action with custom namespace
php artisan statecraft:make:action Notifications/SendEmailAction
# Action with context support
php artisan statecraft:make:action UpdateInventory --with-context
Generated action example:
<?php
namespace App\StateMachine\Actions;
use Grazulex\LaravelStatecraft\Contracts\Action;
use Illuminate\Database\Eloquent\Model;
class ProcessPayment implements Action
{
public function execute(Model $model, string $from, string $to): void
{
// TODO: Implement your action logic
}
}
Generate an event listener for state changes:
# Basic listener
php artisan statecraft:make:listener OrderStateListener
# Model-specific listener
php artisan statecraft:make:listener OrderStateListener --model=Order
Analyze state machine usage and performance:
# Analyze specific state machine
php artisan statecraft:analyze OrderStateMachine
# Analyze all state machines
php artisan statecraft:analyze --all
# Include performance metrics
php artisan statecraft:analyze OrderStateMachine --with-metrics
Output example:
OrderStateMachine Analysis
==========================
States: 6 total
- pending: 45% of orders
- paid: 30% of orders
- shipped: 20% of orders
- delivered: 5% of orders
Transitions (last 30 days):
- pay: 1,234 times (avg: 41/day)
- ship: 987 times (avg: 33/day)
- deliver: 876 times (avg: 29/day)
Performance:
- Average time to payment: 2.5 hours
- Average fulfillment time: 1.2 days
- Completion rate: 95%
Show current state distribution:
# Show status for specific model
php artisan statecraft:status Order
# Show detailed breakdown
php artisan statecraft:status Order --detailed
# Export to CSV
php artisan statecraft:status Order --export=orders_status.csv
Clean up old history records:
# Clean records older than 30 days
php artisan statecraft:cleanup --days=30
# Clean for specific model
php artisan statecraft:cleanup --model=Order --days=90
# Dry run (show what would be deleted)
php artisan statecraft:cleanup --days=30 --dry-run
Clear state machine cache:
# Clear all cache
php artisan statecraft:cache:clear
# Clear specific state machine cache
php artisan statecraft:cache:clear OrderStateMachine
Migrate existing model states to new state machine:
# Migrate with mapping file
php artisan statecraft:migrate-states Order --mapping=state_mapping.json
# Interactive migration
php artisan statecraft:migrate-states Order --interactive
Generate comprehensive reports:
# Daily report
php artisan statecraft:report --period=daily
# Weekly summary
php artisan statecraft:report --period=weekly [email protected]
# Custom date range
php artisan statecraft:report --from=2024-01-01 --to=2024-01-31
# Export to file
php artisan statecraft:report --export=report.pdf
Show performance metrics:
# Basic metrics
php artisan statecraft:metrics
# Detailed metrics with charts
php artisan statecraft:metrics --detailed
# Export metrics
php artisan statecraft:metrics --export=json > metrics.json
Debug state machine issues:
# Debug specific model instance
php artisan statecraft:debug Order 123
# Show transition possibilities
php artisan statecraft:debug Order 123 --transitions
# Verbose debugging
php artisan statecraft:debug Order 123 --verbose
Output example:
Debugging Order #123
====================
Current State: processing
State Machine: OrderStateMachine
Last Transition: pay β processing (2 hours ago)
Available Transitions:
β ship (guards: HasInventory)
β cancel (guard failed: IsWithinCancellationPeriod)
State History:
- pending β paid (3 hours ago) by User #5
- paid β processing (2 hours ago) by System
Guards Status:
β HasInventory: passed
β IsWithinCancellationPeriod: failed (reason: too late)
Test if a transition is possible:
# Test transition
php artisan statecraft:test-transition Order 123 ship
# Test with context
php artisan statecraft:test-transition Order 123 ship --context='{"urgent":true}'
# Show guard details
php artisan statecraft:test-transition Order 123 ship --show-guards
Generate state machine diagrams:
# Generate Mermaid diagram
php artisan statecraft:diagram OrderStateMachine
# Export to file
php artisan statecraft:diagram OrderStateMachine --output=order_workflow.md
# Generate DOT format
php artisan statecraft:diagram OrderStateMachine --format=dot
# Include metadata
php artisan statecraft:diagram OrderStateMachine --with-metadata
Generated Mermaid diagram example:
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 --> [*]
Perform batch transitions:
# Transition all pending orders older than 24 hours
php artisan statecraft:transition:batch Order \
--where="status=pending AND created_at < NOW() - INTERVAL 24 HOUR" \
--transition=auto_cancel
# Dry run
php artisan statecraft:transition:batch Order \
--where="status=processing" \
--transition=ship \
--dry-run
# With progress bar
php artisan statecraft:transition:batch Order \
--where="status=paid" \
--transition=process \
--chunk=100
Run state machine tests:
# Test all state machines
php artisan statecraft:test
# Test specific state machine
php artisan statecraft:test OrderStateMachine
# Run with coverage
php artisan statecraft:test --coverage
Generate test data:
# Create orders in various states
php artisan statecraft:factory Order --count=100 --states=all
# Create specific state distribution
php artisan statecraft:factory Order --count=50 --states=pending:20,paid:15,shipped:10,delivered:5
Publish configuration files:
# Publish config
php artisan statecraft:config:publish
# Publish with force
php artisan statecraft:config:publish --force
Install and configure Laravel Statecraft:
# Full installation
php artisan statecraft:install
# Install with example
php artisan statecraft:install --with-example
# Skip migrations
php artisan statecraft:install --skip-migrations
You can extend Laravel Statecraft with custom commands:
<?php
namespace App\Console\Commands;
use Illuminate\Console\Command;
use Grazulex\LaravelStatecraft\Services\StateMachineService;
class CustomStatecraftCommand extends Command
{
protected $signature = 'statecraft:custom {action}';
protected $description = 'Custom statecraft command';
public function __construct(
private StateMachineService $stateMachineService
) {
parent::__construct();
}
public function handle()
{
$action = $this->argument('action');
match ($action) {
'health-check' => $this->healthCheck(),
'optimize' => $this->optimize(),
default => $this->error("Unknown action: {$action}")
};
}
private function healthCheck()
{
$this->info('Running health check...');
// Check all state machines
$stateMachines = $this->stateMachineService->getAllStateMachines();
foreach ($stateMachines as $stateMachine) {
if ($this->stateMachineService->validate($stateMachine)) {
$this->line("β {$stateMachine->getName()}");
} else {
$this->error("β {$stateMachine->getName()}");
}
}
}
}
Create useful aliases in your shell:
# Add to ~/.bashrc or ~/.zshrc
alias sm:make='php artisan statecraft:make'
alias sm:list='php artisan statecraft:list'
alias sm:validate='php artisan statecraft:validate'
alias sm:debug='php artisan statecraft:debug'
alias sm:status='php artisan statecraft:status'
Most commands support these options:
-
--env
: Specify environment -
--verbose
: Verbose output -
--quiet
: Suppress output -
--force
: Force overwrite -
--dry-run
: Show what would happen
Commands that support different output formats:
-
--format=table
(default) --format=json
--format=csv
--format=xml
-
--model
: Filter by model class -
--state
: Filter by current state -
--user
: Filter by user -
--date
: Filter by date range
Now that you know the console commands:
- Learn Testing Guide - Test your state machines effectively
- Explore Examples Collection - See complete implementations
- Study Configuration Guide - Advanced configuration options
Pro tip: Use php artisan statecraft:list
to see all available commands and their current status in your application.
π― 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