Skip to content

datomatic/laravel-enum-state-machine

Repository files navigation

Enum Helper-DarkEnum Helper-Light

Laravel enum state machine

Latest Version on Packagist Pest Tests number GitHub Tests Action Status GitHub Code Style Action Status Total Downloads

This package it's simple state transitions control for enums in Laravel, this is not an implementation of state machine pattern. Allowing you to prevent unlogically transition and also controlling the initial state of the enum fields on your models.

Installation

Laravel 10+ and PHP 8.2+ are required.

You can install the package via composer:

composer require datomatic/laravel-enum-state-machine

You can publish and run the migrations with:

php artisan vendor:publish --tag="enum-state-machine-migrations"
php artisan migrate

You can publish the config file with:

php artisan vendor:publish --tag="enum-state-machine-config"

This is the contents of the published config file:

return [
/*
    |--------------------------------------------------------------------------
    | Soft Mode Configuration
    |--------------------------------------------------------------------------
    |
    | The 'soft_mode' configuration allows for handling errors without
    | interrupting the application's execution. When this option is enabled,
    | no exceptions are thrown during state transitions and logged instead.
    | This helps prevent unexpected crashes, ensuring
    | greater application resilience, especially in scenarios where a failure
    | in the state machine should not disrupt the main program flow.
    | You can configure this modality for each model casting
    |
    */
    'soft_mode' => env('LARAVEL_ENUM_STATE_MACHINE_SOFT_MODE', false),
];

Usage

Laravel enum state machine it's a simple state transitions control for enums in Laravel, this is not an implementation of state machine pattern.

In the default mode, if the transition is not allowed, an exception StatusTransitionDenied will be thrown. In the soft mode, if the transition is not allowed, an error message will be logged.

Setting the model

You need to define the casts in your model and the transition control function. The first param on the casting is the enum class and the optional second param is the soft mode modality (if no second param is passed, the default mode configured in config file is used). You can cast multiple fields if needed. The transition method name is composed by the enum field name (camelCase) + Transitions and serve to define whether a transition is allowed or not.

class TestModel extends Model
{
    //Laravel 10
    protected $casts = [
        'status' => AsEnumStateMachine::class.':'.StatusEnum::class,  // ',true' for soft mode
    ];
    
    //Laravel 11
    protected function casts(): array
    {
        return [
            'field_name' => AsEnumStateMachine::of(FieldEnum::class, false),
        ];
    }

    /** 
     * This method name is composed by the enum field name (camelCase) + Transitions 
     */
    public function statusTransitions(?StatusEnum $from, ?StatusEnum $to): bool
    {
        return match ($from) {
            null => true, // initial state permitted to all states
            StatusEnum::PUBLIC => match ($to) {
                StatusEnum::PRIVATE => true,
                StatusEnum::PROTECTED => true,
                null => false,
                default => false
            },
            StatusEnum::PROTECTED => match ($to) {
                StatusEnum::PRIVATE => true,
                StatusEnum::PUBLIC => false,
                default => false
            },
            StatusEnum::PRIVATE => false, //final state
            default => true
        };
    }

Use the model

$model = new TestModel;
$model->status = StatusEnum::PUBLIC; // OK
$model->save();

$model = TestModel::find(1);
$model->status; // StatusEnum::PUBLIC
$model->status = StatusEnum::PRIVATE; // OK
$model->status = StatusEnum::PUBLIC; // thrown `StatusTransitionDenied`

Testing

composer test

Changelog

Please see CHANGELOG for more information on what has changed recently.

Security Vulnerabilities

Please review our security policy on how to report security vulnerabilities.

Credits

License

The MIT License (MIT). Please see License File for more information.

About

A simple state machine for enums in Laravel

Resources

License

Stars

Watchers

Forks

Sponsor this project

Packages

No packages published

Languages