Skip to content

Commit

Permalink
Changed key for afterTransitionHooks callbacks
Browse files Browse the repository at this point in the history
- Updated tests
  • Loading branch information
asantibanez committed Mar 21, 2021
1 parent f2a70b5 commit 33d837a
Show file tree
Hide file tree
Showing 3 changed files with 15 additions and 14 deletions.
15 changes: 8 additions & 7 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -404,10 +404,11 @@ We can also add custom hooks/callbacks that will be executed before/after a tran
To do so, we must override the `beforeTransitionHooks()` and `afterTransitionHooks()` methods in our state machine
accordingly.

Both transition hooks methods must return a keyed array with the state and an array of callbacks/closures
Both transition hooks methods must return a keyed array with the state as key, and an array of callbacks/closures
to be executed.

> NOTE: The keys for the array must be the `$from` states.
> NOTE: The keys for beforeTransitionHooks() must be the `$from` states.
> NOTE: The keys for afterTransitionHooks() must be the `$to` states.
Example

Expand All @@ -431,12 +432,12 @@ class StatusStateMachine extends StateMachine
public function afterTransitionHooks(): array
{
return [
'approved' => [
function ($to, $model) {
// Dispatch some job AFTER "approved changes to $to"
'processed' => [
function ($from, $model) {
// Dispatch some job AFTER "$from transitioned to processed"
},
function ($to, $model) {
// Send mail AFTER "approved changes to $to"
function ($from, $model) {
// Send mail AFTER "$from transitioned to processed"
},
],
];
Expand Down
6 changes: 3 additions & 3 deletions src/StateMachines/StateMachine.php
Original file line number Diff line number Diff line change
Expand Up @@ -129,11 +129,11 @@ public function transitionTo($from, $to, $customProperties = [], $responsible =
$this->model->recordState($field, $from, $to, $customProperties, $responsible, $changedAttributes);
}

$afterTransitionHooks = $this->afterTransitionHooks()[$from] ?? [];
$afterTransitionHooks = $this->afterTransitionHooks()[$to] ?? [];

collect($afterTransitionHooks)
->each(function ($callable) use ($to) {
$callable($to, $this->model);
->each(function ($callable) use ($from) {
$callable($from, $this->model);
});

$this->cancelAllPendingTransitions();
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -30,16 +30,16 @@ public function defaultState(): ?string
public function afterTransitionHooks(): array
{
return [
'pending' => [
function($to, $model) {
'approved' => [
function($from, $model) {
$model->total = 200;
$model->save();
},
function($to, $model) {
function($from, $model) {
$model->notes = 'after';
$model->save();
},
function ($to, $model) {
function ($from, $model) {
AfterTransitionJob::dispatch();
},
]
Expand Down

0 comments on commit 33d837a

Please sign in to comment.