PHP code example of moirei / laravel-state

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

    

moirei / laravel-state example snippets


use MOIREI\State\State;

/**
 * @property State $status
 */
class Order extends Model{
    protected function status(): Attribute{
        return State::make([
            State::on('created', 'paid'),
            State::on('paid', ['created', 'completed'])
            State::on('completed', 'archived')
        ]);
    }
}

dump($order->status->value); // `created`

$order->status->transitionTo('paid');

dump($order->status->value); // `paid`

use MOIREI\State\Traits\CastsEnumAttributesState;
use MOIREI\State\Traits\HasEnumState;
use MOIREI\State\State;

...

enum OrderStatus: string{
    use HasEnumState;

    case PENDING = 'pending';
    case PAID = 'paid';
    case CLOSED = 'closed';

    public static function states(){
        return [
            State::on(self::PENDING, [self::PAID, self::CLOSED]),
            State::on(self::PAID, self::CLOSED),
        ];
    }
}

...

/**
 * @property OrderStatus $status
 */
class Order extends Model{
    use CastsEnumAttributesState; // only if using casts

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

    // or

    protected function status(): Attribute{
        return OrderStatus::useAttribute();
    }
}

...

// accepts enum value but fails if invalid
if($order->status->is('pending')){
    $order->status->transitionTo(OrderStatus::PAID);
}

// should throw
if($order->status->is('closed')){
    $order->status->transitionTo(...);
}

use MOIREI\State\State;

...

final class OrderStatus extends State{
    const PENDING = 'pending';
    const PAID = 'paid';
    const CLOSED = 'closed';

    public static function states(){
        return [
            State::on(static::PENDING, [static::PAID, static::CLOSED]),
            State::on(static::PAID, static::CLOSED),
        ];
    }
}

...

/**
 * @property OrderStatus $status
 */
class Order extends Model{

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

    // or

    protected function status(): Attribute{
        return OrderStatus::useAttribute();
    }
}

...

// same as with enum above
if($order->status->is('pending')){
    $order->status->transitionTo('paid');
}