Skip to content

Console Commands

Jean-Marc Strauven edited this page Aug 6, 2025 · 2 revisions

🎨 Console Commands

Laravel Statecraft provides a comprehensive set of Artisan commands to help you manage state machines, generate components, and troubleshoot issues during development.

πŸ“‹ Available Commands

Core Commands

statecraft:make

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

statecraft:list

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      |
+------------------+------------------+---------------+

statecraft:validate

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

πŸ—οΈ Generation Commands

statecraft:make:guard

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;
    }
}

statecraft:make:action

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
    }
}

statecraft:make:listener

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

πŸ” Analysis Commands

statecraft:analyze

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%

statecraft:status

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

🧹 Maintenance Commands

statecraft:cleanup

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

statecraft:cache:clear

Clear state machine cache:

# Clear all cache
php artisan statecraft:cache:clear

# Clear specific state machine cache
php artisan statecraft:cache:clear OrderStateMachine

statecraft:migrate-states

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

πŸ“Š Reporting Commands

statecraft:report

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

statecraft:metrics

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 Commands

statecraft:debug

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)

statecraft:test-transition

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

πŸ“ˆ Visualization Commands

statecraft:diagram

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 --> [*]
Loading

πŸ”„ Batch Commands

statecraft:transition:batch

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

πŸ§ͺ Testing Commands

statecraft:test

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

statecraft:factory

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

βš™οΈ Configuration Commands

statecraft:config:publish

Publish configuration files:

# Publish config
php artisan statecraft:config:publish

# Publish with force
php artisan statecraft:config:publish --force

statecraft:install

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

πŸ” Custom Commands

Creating Custom Commands

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()}");
            }
        }
    }
}

πŸ“ Command Aliases

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'

πŸ”§ Command Options Reference

Global Options

Most commands support these options:

  • --env: Specify environment
  • --verbose: Verbose output
  • --quiet: Suppress output
  • --force: Force overwrite
  • --dry-run: Show what would happen

Output Formats

Commands that support different output formats:

  • --format=table (default)
  • --format=json
  • --format=csv
  • --format=xml

Filtering Options

  • --model: Filter by model class
  • --state: Filter by current state
  • --user: Filter by user
  • --date: Filter by date range

πŸš€ What's Next?

Now that you know the console commands:

  1. Learn Testing Guide - Test your state machines effectively
  2. Explore Examples Collection - See complete implementations
  3. 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.

Clone this wiki locally