Skip to content

Console Commands

Jean-Marc Strauven edited this page Jul 31, 2025 · 2 revisions

πŸ› οΈ Console Commands

Master the powerful CLI tools for managing Laravel Statecraft state machines.

πŸ“– Overview

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

πŸ“‹ Available Commands

Core Management Commands

# List all available commands
php artisan list statecraft

# Get help for any command
php artisan help statecraft:make

πŸ—οΈ Creation Commands

statecraft:make - Create State Machine

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

πŸ“Š Inspection Commands

statecraft:list - List State Machines

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

statecraft:show - Show State Machine Details

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

βœ… Validation Commands

statecraft:validate - Validate State Machines

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 Commands

statecraft:export - Export to Different Formats

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

Mermaid Diagram Output

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

JSON Export

{
  "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"
    }
  ]
}

Markdown Documentation

# 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

πŸ”„ Code Generation Commands

statecraft:generate - Generate PHP Classes

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

🧹 Maintenance Commands

statecraft:cleanup - Cleanup Operations

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

statecraft:cache - Cache Management

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

πŸ” Debugging Commands

statecraft:debug - Debug State Machines

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)

⚑ Batch Operations

Working with Multiple State Machines

# 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

CI/CD Integration

# 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

πŸ”§ Configuration and Customization

Command Configuration

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,
    ],
]

Custom Command Aliases

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"

πŸ“Š Command Examples

Development Workflow

# 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/

Production Deployment

# 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/

Maintenance Tasks

# 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

πŸš€ Best Practices

Command Usage

  1. Validate frequently - Run validation before deployments
  2. Use aliases - Create shortcuts for common commands
  3. Automate exports - Generate documentation automatically
  4. Monitor cleanup - Regular maintenance prevents bloat
  5. Debug systematically - Use debug commands for troubleshooting

Integration with Build Tools

# 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

πŸš€ Next Steps

Now that you understand the CLI tools, explore:

Core Features

Practical Applications

Advanced Topics

Ready to explore advanced workflow patterns? Check out πŸ”„ User Workflow Guide!

Clone this wiki locally