Skip to content

Commit

Permalink
custom return value
Browse files Browse the repository at this point in the history
  • Loading branch information
jarektkaczyk committed Oct 28, 2024
1 parent 408556b commit b3627bf
Show file tree
Hide file tree
Showing 2 changed files with 16 additions and 4 deletions.
10 changes: 6 additions & 4 deletions src/Fsm.php
Original file line number Diff line number Diff line change
Expand Up @@ -75,9 +75,9 @@ public function getCurrentState() : string
*
* @param string|Transition $action
* @param mixed $payload
* @return string
* @return mixed
*/
public function process(string|Transition $action, $payload = null) : string
public function process(string|Transition $action, $payload = null) : mixed
{
$action = is_string($action) ? $action : $action->action;

Expand All @@ -90,11 +90,13 @@ public function process(string|Transition $action, $payload = null) : string
$transition = $this->transitions[$this->state][$action];

if (is_callable($transition)) {
$transition($this->stateful_object, $payload);
$returnValue = $transition($this->stateful_object, $payload);
} else {
$this->stateful_object->setState($transition->to_state);
}

return $this->state = $transition->to_state;
$this->state = $transition->to_state;

return $returnValue ?? $this->state;
}
}
10 changes: 10 additions & 0 deletions tests/FsmTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -43,6 +43,14 @@ public function it_transitions_machine_between_object_states()
$this->assertEquals('idle', $this->fsm->getCurrentState());
}

/** @test */
public function it_returns_custom_transition_value()
{
$this->assertEquals('off', $this->fsm->getCurrentState());
$this->assertEquals(['custom' => 'return'], $this->fsm->process(CustomTransition::make('off', 'custom_start', 'idle')));
$this->assertEquals('idle', $this->fsm->getCurrentState());
}

/** @test */
public function it_puts_machine_object_in_proper_state()
{
Expand Down Expand Up @@ -101,5 +109,7 @@ public function __invoke($stateful_object, $payload)
{
$stateful_object->prop = $payload['prop'];
$stateful_object->setState($this->to_state);

return ['custom' => 'return'];
}
}

0 comments on commit b3627bf

Please sign in to comment.