PHP code example of maestrodimateo / laravel-workflow

1. Go to this page and download the library: Download maestrodimateo/laravel-workflow library. Choose the download type require.

2. Extract the ZIP file and open the index.php.

3. Add this code to the index.php.
    
        
<?php
require_once('vendor/autoload.php');

/* Start to develop here. Best regards https://php-download.com/ */

    

maestrodimateo / laravel-workflow example snippets


use Maestrodimateo\Workflow\Traits\Workflowable;

class Invoice extends Model
{
    use HasUuids, Workflowable;
}

use Maestrodimateo\Workflow\Facades\Workflow;

// Current status
$basket = Workflow::for($invoice)->currentStatus();
$basket->name;   // "Draft"
$basket->status; // "DRAFT"

// Available next steps
$options = Workflow::for($invoice)->nextBaskets();

// Transition
Workflow::for($invoice)->transition($nextBasket->id, 'Approved by manager');

workflow($invoice)->currentStatus();
workflow($invoice)->transition($basketId);

$wf = Workflow::for($model);

// Circuits accessible to a role
Workflow::circuitsForRole('manager');
Workflow::circuitsForRoles(['admin', 'manager']);

// Baskets accessible to a role
Workflow::basketsForRole('validator');
Workflow::basketsForRole('validator', $circuitId);
Workflow::basketsForRoles(['admin', 'operator'], $circuitId);

Circuit::forRole('admin')->get();
Basket::forRoles(['admin', 'manager'])->get();

$basket->hasRole('validator');  // true/false
$circuit->hasRole('admin');     // true/false

$invoice->baskets;        // All baskets (past and current)
$invoice->histories;      // Transition history
$invoice->workflowLock;   // Active lock (or null)

// Current status
$invoice->currentStatus();              // Across all circuits
$invoice->currentStatus($circuit);      // In a specific circuit

// Inspect the basket
$basket = $invoice->currentStatus();
$basket->status;   // "REVIEW"
$basket->name;     // "Under Review"
$basket->color;    // "#2563eb"
$basket->roles;    // ["manager", "validator"]
$basket->next;     // Collection<Basket> — possible next steps
$basket->previous; // Collection<Basket> — where it came from

// Models in a specific basket
Invoice::fromBasket($reviewBasket)->get();

// Unlocked models
Invoice::unlocked()->get();

// Models locked by a specific user
Invoice::lockedBy(auth()->id())->get();

// Combine scopes
Invoice::fromBasket($reviewBasket)->unlocked()->get();

$invoice = Invoice::create(['number' => 'INV-001']);

$invoice->currentStatus()->status; // "DRAFT"
$invoice->baskets->count();        // 1 (or more if multiple circuits)

Workflow::for($invoice)->in($approvalCircuit)->currentStatus();
Workflow::for($invoice)->in($complianceCircuit)->transition($basketId);
Workflow::for($invoice)->in('circuit-uuid')->history();

$statuses = Workflow::for($invoice)->allStatuses();
// [
//     'circuit-a-id' => ['circuit' => Circuit, 'basket' => Basket],
//     'circuit-b-id' => ['circuit' => Circuit, 'basket' => Basket],
// ]

// Lock (default: 30 minutes)
Workflow::for($invoice)->lock();
Workflow::for($invoice)->lock(60);  // 1 hour

// Check
Workflow::for($invoice)->isLocked();
Workflow::for($invoice)->isLockedByMe();
Workflow::for($invoice)->lockedBy();        // "user-uuid"
Workflow::for($invoice)->lockExpiration();  // Carbon

// Transition — automatically checks the lock
Workflow::for($invoice)->transition($basketId);
// OK if you hold the lock (released after transition)
// ModelLockedException if locked by someone else

// Release
Workflow::for($invoice)->unlock();
Workflow::for($invoice)->unlock(force: true);  // admin

use Maestrodimateo\Workflow\Exceptions\ModelLockedException;

try {
    Workflow::for($invoice)->transition($basketId);
} catch (ModelLockedException $e) {
    // "This resource is locked by [user] until [14:30]."
}

use Maestrodimateo\Workflow\Contracts\TransitionAction;

class GeneratePdfAction implements TransitionAction
{
    public static function key(): string   { return 'generate_pdf'; }
    public static function label(): string { return 'Generate PDF'; }

    public function execute(Model $model, Basket $from, Basket $to, array $config = []): void
    {
        // Your logic here
    }
}

Workflow::registerAction(GeneratePdfAction::class);

use Maestrodimateo\Workflow\Contracts\AfterCommitAction;
use Maestrodimateo\Workflow\Contracts\TransitionAction;

class NotifySlackAction implements TransitionAction, AfterCommitAction
{
    public static function key(): string   { return 'notify_slack'; }
    public static function label(): string { return 'Notify Slack'; }

    public function execute(Model $model, Basket $from, Basket $to, array $config = []): void
    {
        Http::post($config['webhook_url'], ['model' => $model->getKey(), 'to' => $to->status]);
    }
}

use Maestrodimateo\Workflow\Contracts\QueueableAction;
use Maestrodimateo\Workflow\Contracts\TransitionAction;

class NotifySlackAction implements TransitionAction, QueueableAction
{
    public static function key(): string       { return 'notify_slack'; }
    public static function label(): string     { return 'Notify Slack'; }
    public static function queue(): ?string    { return 'notifications'; }
    public static function connection(): ?string { return null; }

    public function execute(Model $model, Basket $from, Basket $to, array $config = []): void
    {
        Http::post($config['webhook_url'], ['model' => $model->getKey(), 'to' => $to->status]);
    }
}

use Maestrodimateo\Workflow\Contracts\TransitionCondition;

class BudgetApprovedCondition implements TransitionCondition
{
    public static function key(): string   { return 'budget_approved'; }
    public static function label(): string { return 'Budget approved'; }

    public function passes(Model $model, array $config = []): bool
    {
        return $model->budget?->is_approved === true;
    }

    public function reason(array $config = []): string
    {
        return 'The budget must be approved first.';
    }

    // Optional: limit this condition to specific models
    public static function models(): array
    {
        return [\App\Models\Invoice::class];
    }
}

'conditions' => [
    App\Workflow\Conditions\BudgetApprovedCondition::class,
],

// Check which transitions are available
foreach (Workflow::for($invoice)->availableTransitions() as $t) {
    $t['basket'];     // Target basket
    $t['label'];      // Transition label
    $t['open'];       // true/false
    $t['blockedBy'];  // ["The budget must be approved first."]
}

// Handle rejection
try {
    Workflow::for($invoice)->transition($basketId);
} catch (\Maestrodimateo\Workflow\Exceptions\TransitionConditionException $e) {
    $e->reasons;  // ["The budget must be approved first."]
}

$history = Workflow::for($invoice)->history();

foreach ($history as $entry) {
    $entry->previous_status;  // "DRAFT"
    $entry->next_status;      // "REVIEW"
    $entry->duration_seconds; // 3600
    $entry->duration_human;   // "1h"
    $entry->done_by;          // User ID
    $entry->comment;          // "Sent for review"
}

// Total time
Workflow::for($invoice)->totalDuration();             // seconds

// Time in a specific step
Workflow::for($invoice)->durationInStatus('REVIEW');  // seconds

// config/workflow.php
'message_variables' => [
    'reference' => fn ($model) => $model->reference,
    'amount'    => fn ($model) => number_format($model->amount, 2, '.', ','),
],

// EventServiceProvider
protected $listen = [
    \Maestrodimateo\Workflow\Events\TransitionEvent::class => [
        \App\Listeners\NotifySlack::class,
    ],
];

public function handle(TransitionEvent $event): void
{
    $event->currentBasket; // Source basket
    $event->nextBasket;    // Target basket
    $event->model;         // The transitioned model
    $event->comment;       // Transition comment
}

use Maestrodimateo\Workflow\Facades\Workflow;

Workflow::importFromJson(database_path('seeders/workflow-invoices.json'));

// config/workflow.php
return [
    // Routes & middleware
    'routes' => [
        'prefix'           => 'workflow',
        'middleware'        => ['api', 'auth'],
        'admin_middleware'  => ['web', 'auth'],
    ],

    // Authorization gate (define in a ServiceProvider)
    // Gate::define('manage-workflow', fn ($user) => $user->isAdmin());
    'authorization' => [
        'gate' => 'manage-workflow',
    ],

    // User attribute stored in history
    'auth_identifier' => 'id',

    // Custom variables for message templates
    'message_variables' => [],

    // Custom actions & conditions
    'actions'    => [],
    'conditions' => [],

    // Queue settings for async actions
    'actions_queue' => [
        'queue'      => env('WORKFLOW_ACTIONS_QUEUE'),
        'connection' => env('WORKFLOW_ACTIONS_QUEUE_CONNECTION'),
        'tries'      => 3,
        'backoff'    => [10, 30, 60],
        'timeout'    => 30,
    ],

    // Lock duration
    'lock' => [
        'duration_minutes' => 30,
    ],

    // SSRF protection for webhooks
    'webhook' => [
        'allowed_schemes'      => ['https'],
        'allowed_hosts'        => [],
        'block_private_ranges' => true,
        'timeout'              => 5,
    ],
];
bash
php artisan vendor:publish --tag=workflow-config
php artisan vendor:publish --tag=workflow-migrations
php artisan migrate
bash
php artisan vendor:publish --tag=workflow-views
bash
php artisan make:workflow-action GeneratePdfAction