|
1
|
|
|
<?php |
|
2
|
|
|
|
|
3
|
|
|
declare (strict_types = 1); |
|
4
|
|
|
|
|
5
|
|
|
namespace Noodle\State; |
|
6
|
|
|
|
|
7
|
|
|
/** |
|
8
|
|
|
* FlyweightState will reuse states it has previously created with the same name |
|
9
|
|
|
* rather than create new ones. This results in some memory and performance savings |
|
10
|
|
|
* in applications that would otherwise have many repeated "new State('...')", and |
|
11
|
|
|
* it allows for easier comparison of two States, if necessary. |
|
12
|
|
|
* |
|
13
|
|
|
* @see https://en.wikipedia.org/wiki/Flyweight_pattern |
|
14
|
|
|
*/ |
|
15
|
|
|
final class FlyweightState implements CreatesWildcard, CreatesWithName, State |
|
16
|
|
|
{ |
|
17
|
|
|
/** |
|
18
|
|
|
* The name of the state |
|
19
|
|
|
* |
|
20
|
|
|
* @var string |
|
21
|
|
|
*/ |
|
22
|
|
|
private $name; |
|
23
|
|
|
|
|
24
|
|
|
/** |
|
25
|
|
|
* Instances of states created by the FlyweightState factory method |
|
26
|
|
|
* |
|
27
|
|
|
* @var State[] |
|
28
|
|
|
*/ |
|
29
|
|
|
private static $instances = []; |
|
30
|
|
|
|
|
31
|
|
|
/** |
|
32
|
|
|
* The "wildcard" state, indicating "any" state when doing transition events. |
|
33
|
|
|
* |
|
34
|
|
|
* @var State |
|
35
|
|
|
*/ |
|
36
|
|
|
private static $wildcard; |
|
37
|
|
|
|
|
38
|
|
|
/** |
|
39
|
|
|
* Constructor |
|
40
|
|
|
* |
|
41
|
|
|
* @param string $name |
|
42
|
|
|
*/ |
|
43
|
7 |
|
private function __construct(string $name) |
|
44
|
|
|
{ |
|
45
|
7 |
|
$this->name = $name; |
|
46
|
7 |
|
} |
|
47
|
|
|
|
|
48
|
|
|
/** |
|
49
|
|
|
* {@inheritdoc} |
|
50
|
|
|
*/ |
|
51
|
19 |
|
public function getName() : string |
|
52
|
|
|
{ |
|
53
|
19 |
|
return $this->name; |
|
54
|
|
|
} |
|
55
|
|
|
|
|
56
|
|
|
/** |
|
57
|
|
|
* Creates and returns a state with the given name, or, if such a state |
|
58
|
|
|
* has already been created, returns it from the instance cache. |
|
59
|
|
|
* |
|
60
|
|
|
* @param string $name |
|
61
|
|
|
* |
|
62
|
|
|
* @return State |
|
63
|
|
|
*/ |
|
64
|
23 |
|
public static function named(string $name) : State |
|
65
|
|
|
{ |
|
66
|
23 |
|
if (!isset(self::$instances[$name])) { |
|
67
|
6 |
|
self::$instances[$name] = new self($name); |
|
68
|
|
|
} |
|
69
|
|
|
|
|
70
|
23 |
|
return self::$instances[$name]; |
|
71
|
|
|
} |
|
72
|
|
|
|
|
73
|
|
|
/** |
|
74
|
|
|
* Creates and returns a state with a long, random, name in hex to be |
|
75
|
|
|
* designated the "any" / "wildcard" state, or, if such a state has |
|
76
|
|
|
* already been created, returns it. |
|
77
|
|
|
* |
|
78
|
|
|
* @return State |
|
79
|
|
|
*/ |
|
80
|
9 |
|
public static function any() : State |
|
81
|
|
|
{ |
|
82
|
9 |
|
if (!isset(self::$wildcard)) { |
|
83
|
1 |
|
self::$wildcard = new self(bin2hex(random_bytes(20))); |
|
84
|
|
|
} |
|
85
|
|
|
|
|
86
|
9 |
|
return self::$wildcard; |
|
87
|
|
|
} |
|
88
|
|
|
} |
|
89
|
|
|
|