PHP code example of tamkeen-tech / laravel-enum-state-machine

1. Go to this page and download the library: Download tamkeen-tech/laravel-enum-state-machine 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/ */

    

tamkeen-tech / laravel-enum-state-machine example snippets


use TamkeenTech\LaravelEnumStateMachine\Traits\HasStateMachines;

class Bill extends Model
{
    use HasStateMachines;

    protected $fillable = [
        'status',
    ];

    protected $casts = [
        'status' => BillStatus::class,
    ];

    protected $recordStateHistory = true;

    protected $stateMachines = [
        'status'
    ];
}

use TamkeenTech\LaravelEnumStateMachine\Traits\StateMachine;

enum BillStatus: string
{
    use StateMachine;

    case PENDING = 'PENDING';
    case PAID = 'PAID';
    case EXPIRED = 'EXPIRED';
    case REFUNDED = 'REFUNDED';

    public function transitions(): array
    {
        return match ($this) {
            self::PENDING => [self::PAID, self::EXPIRED],
            self::PAID => [self::REFUNDED]
        };
    }

    public function initialState(): array
    {
        return [self::PENDING];
    }
}

  // throw InitailStateIsNotAllowedException with message "Only allowed initial states: PENDING"
  Bill::create([
    'status' => BillStatus::PAID
  ]);
  

  $bill = Bill::create([
    'status' => BillStatus::PENDING
  ]);

  // throw StateTransitionNotAllowedException with message "Only allowed transition states: PAID, EXPIRED"
  $bill->update([
    'status' => BillStatus::REFUNDED
  ]);
  

$bill = Bill::find(1);
$bill->stateHistory;

$billStatus = BillStatus::PENDING;

if ($billStatus->canTransitTo(BillStatus::PAID)) {
    // Do something
}

$billStatus = BillStatus::PENDING;

if ($billStatus->inInitialState()) {
    // Do something
}

$billStatus = BillStatus::PENDING;

if ($billStatus->is(BillStatus::PENDING)) {
    // Do something
}
bash
php artisan enum:flow-diagram "App\Enums\BillStatus"
bash
php artisan enum:flow-diagram "App\Enums\BillStatus" --output=/custom/path