-
-
Notifications
You must be signed in to change notification settings - Fork 66
Expand file tree
/
Copy pathStateMachine.php
More file actions
50 lines (39 loc) · 1012 Bytes
/
StateMachine.php
File metadata and controls
50 lines (39 loc) · 1012 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
<?php
declare(strict_types=1);
namespace Tests\Fixtures;
use Exception;
class StateMachine
{
private $states = [];
private $transitions = [];
private $currentState;
public function addState($state)
{
$this->states[] = $state;
}
public function addTransition($action, $fromState, $toState)
{
$this->transitions[$action] = [
'from' => $fromState,
'to' => $toState,
];
}
public function initialize()
{
if (count($this->states) > 0) {
$this->currentState = $this->states[0];
}
}
public function getCurrentState()
{
return $this->currentState;
}
public function apply($action)
{
if (isset($this->transitions[$action]) && $this->transitions[$action]['from'] === $this->currentState) {
$this->currentState = $this->transitions[$action]['to'];
} else {
throw new Exception('Transition not found.');
}
}
}