1. Go to this page and download the library: Download wlhrtr/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/ */
use Wlhrtr\StateMachine\StateMachines\StateMachine;
class StatusStateMachine extends StateMachine
{
public function recordHistory(): bool
{
return false;
}
public function transitions(): array
{
return [
//
];
}
public function defaultState(): ?string
{
return null;
}
}
public function transitions(): array
{
return [
'pending' => ['approved', 'declined'],
'approved' => ['processed'],
];
}
public function transitions(): array
{
return [
'*' => ['approved', 'declined'], // From any to 'approved' or 'declined'
'approved' => '*', // From 'approved' to any
'*' => '*', // From any to any
];
}
public function defaultState(): ?string
{
return 'pending'; // it can be null too
}
public function recordHistory(): bool
{
return true;
}
use Wlhrtr\StateMachine\Traits\HasStateMachines;
use App\StateMachines\StatusStateMachine;
class SalesOrder extends Model
{
Use HasStateMachines;
public $stateMachines = [
'status' => StatusStateMachine::class
];
}
use Illuminate\Support\Facades\Validator as ValidatorFacade;
class StatusStateMachine extends StateMachine
{
public function validatorForTransition($from, $to, $model): ?Validator
{
if ($from === 'pending' && $to === 'approved') {
return ValidatorFacade::make([
'total' => $model->total,
], [
'total' => 'gt:0',
]);
}
return parent::validatorForTransition($from, $to, $model);
}
}
class StatusStateMachine extends StateMachine
{
public function beforeTransitionHooks(): array
{
return [
'approved' => [
function ($to, $model) {
// Dispatch some job BEFORE "approved changes to $to"
},
function ($to, $model) {
// Send mail BEFORE "approved changes to $to"
},
],
];
}
public function afterTransitionHooks(): array
{
return [
'processed' => [
function ($from, $model) {
// Dispatch some job AFTER "$from transitioned to processed"
},
function ($from, $model) {
// Send mail AFTER "$from transitioned to processed"
},
],
];
}
}