1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
declare(strict_types = 1); |
4
|
|
|
|
5
|
|
|
/* |
6
|
|
|
* This file is part of the StateMachine package |
7
|
|
|
* |
8
|
|
|
* (c) Michal Wachowski <[email protected]> |
9
|
|
|
* |
10
|
|
|
* For the full copyright and license information, please view the LICENSE |
11
|
|
|
* file that was distributed with this source code. |
12
|
|
|
*/ |
13
|
|
|
|
14
|
|
|
namespace StateMachine\Payload; |
15
|
|
|
|
16
|
|
|
/** |
17
|
|
|
* Payload envelope, used to transport subject trough state machine process |
18
|
|
|
* |
19
|
|
|
* @package StateMachine |
20
|
|
|
*/ |
21
|
|
|
final class PayloadEnvelope implements Payload |
22
|
|
|
{ |
23
|
|
|
/** |
24
|
|
|
* Flag if context changed |
25
|
|
|
* |
26
|
|
|
* @var bool |
27
|
|
|
*/ |
28
|
|
|
private $hasChanged = false; |
29
|
|
|
|
30
|
|
|
/** |
31
|
|
|
* Current contexts state |
32
|
|
|
* |
33
|
|
|
* @var string |
34
|
|
|
*/ |
35
|
|
|
private $state; |
36
|
|
|
|
37
|
|
|
/** |
38
|
|
|
* Current runs history |
39
|
|
|
* |
40
|
|
|
* @var array |
41
|
|
|
*/ |
42
|
|
|
private $history = []; |
43
|
|
|
|
44
|
|
|
/** |
45
|
|
|
* Actual context instance |
46
|
|
|
* |
47
|
|
|
* @var mixed |
48
|
|
|
*/ |
49
|
|
|
private $subject; |
50
|
|
|
|
51
|
16 |
|
private function __construct($subject) |
52
|
|
|
{ |
53
|
16 |
|
$this->subject = $subject; |
54
|
16 |
|
} |
55
|
|
|
|
56
|
|
|
/** |
57
|
|
|
* @param mixed $subject |
58
|
|
|
* |
59
|
|
|
* @return PayloadEnvelope |
60
|
|
|
*/ |
61
|
16 |
|
public static function wrap($subject): PayloadEnvelope |
62
|
|
|
{ |
63
|
16 |
|
return new static($subject); |
64
|
|
|
} |
65
|
|
|
|
66
|
|
|
/** |
67
|
|
|
* Return true if state has changed (even if it was changed back to itself) |
68
|
|
|
* |
69
|
|
|
* @return bool |
70
|
|
|
*/ |
71
|
1 |
|
public function hasChanged(): bool |
72
|
|
|
{ |
73
|
1 |
|
return $this->hasChanged; |
74
|
|
|
} |
75
|
|
|
|
76
|
|
|
/** |
77
|
|
|
* Return current subject state |
78
|
|
|
* |
79
|
|
|
* @return null|string |
80
|
|
|
*/ |
81
|
6 |
|
public function state() |
82
|
|
|
{ |
83
|
6 |
|
return $this->state; |
84
|
|
|
} |
85
|
|
|
|
86
|
|
|
/** |
87
|
|
|
* Set new state to subject |
88
|
|
|
* |
89
|
|
|
* @param string $name state name |
90
|
|
|
*/ |
91
|
8 |
|
public function changeState($name) |
92
|
|
|
{ |
93
|
8 |
|
$this->state = $name; |
94
|
8 |
|
$this->history[] = $name; |
95
|
8 |
|
$this->hasChanged = true; |
96
|
8 |
|
} |
97
|
|
|
|
98
|
|
|
/** |
99
|
|
|
* Return array with all states that were set in this run |
100
|
|
|
* |
101
|
|
|
* @return array |
102
|
|
|
*/ |
103
|
5 |
|
public function history(): array |
104
|
|
|
{ |
105
|
5 |
|
return $this->history; |
106
|
|
|
} |
107
|
|
|
|
108
|
|
|
/** |
109
|
|
|
* Return subject |
110
|
|
|
* |
111
|
|
|
* @return mixed |
112
|
|
|
*/ |
113
|
1 |
|
public function subject() |
114
|
|
|
{ |
115
|
1 |
|
return $this->subject; |
116
|
|
|
} |
117
|
|
|
} |
118
|
|
|
|