1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
declare(strict_types=1); |
4
|
|
|
|
5
|
|
|
namespace Dflydev\FiniteStateMachine\Guard; |
6
|
|
|
|
7
|
|
|
use Dflydev\FiniteStateMachine\Contracts\GuardCallback; |
8
|
|
|
use Dflydev\FiniteStateMachine\State\State; |
9
|
|
|
use Dflydev\FiniteStateMachine\Transition\Transition; |
10
|
|
|
|
11
|
|
|
class Guard |
12
|
|
|
{ |
13
|
|
|
private string $name; |
14
|
|
|
private array $transitionNames; |
15
|
|
|
private array $fromStateNames; |
16
|
|
|
private array $toStateNames; |
17
|
|
|
private GuardCallback $callback; |
18
|
|
|
|
19
|
21 |
|
public function __construct( |
20
|
|
|
string $name, |
21
|
|
|
array $transitionNames, |
22
|
|
|
array $fromStateNames, |
23
|
|
|
array $toStateNames, |
24
|
|
|
GuardCallback $callback |
25
|
|
|
) { |
26
|
21 |
|
$this->name = $name; |
27
|
21 |
|
$this->transitionNames = $transitionNames; |
28
|
21 |
|
$this->fromStateNames = $fromStateNames; |
29
|
21 |
|
$this->toStateNames = $toStateNames; |
30
|
21 |
|
$this->callback = $callback; |
31
|
21 |
|
} |
32
|
|
|
|
33
|
21 |
|
public function name(): string |
34
|
|
|
{ |
35
|
21 |
|
return $this->name; |
36
|
|
|
} |
37
|
|
|
|
38
|
13 |
|
public function cannot(object $object, Transition $transition, State $fromState, State $toState): bool |
39
|
|
|
{ |
40
|
13 |
|
$matches = []; |
41
|
|
|
|
42
|
13 |
|
if (count($this->transitionNames) > 0) { |
43
|
13 |
|
$matches[] = in_array($transition->name(), $this->transitionNames); |
44
|
|
|
} |
45
|
|
|
|
46
|
13 |
|
if (count($this->fromStateNames) > 0) { |
47
|
13 |
|
$matches[] = in_array($fromState->name(), $this->fromStateNames); |
48
|
|
|
} |
49
|
|
|
|
50
|
13 |
|
if (count($this->toStateNames) > 0) { |
51
|
|
|
$matches[] = in_array($toState->name(), $this->toStateNames); |
52
|
|
|
} |
53
|
|
|
|
54
|
13 |
|
if (count($matches) === 0) { |
55
|
|
|
return false; |
56
|
|
|
} |
57
|
|
|
|
58
|
13 |
|
if (in_array(false, $matches)) { |
59
|
11 |
|
return false; |
60
|
|
|
} |
61
|
|
|
|
62
|
2 |
|
return ! $this->callback->__invoke($object, $transition, $fromState, $toState); |
63
|
|
|
} |
64
|
|
|
} |
65
|
|
|
|