1 | <?php |
||
15 | abstract class ExplicitEnum implements Enum, \Serializable |
||
16 | { |
||
17 | /** |
||
18 | * @var mixed |
||
19 | */ |
||
20 | private $value = ''; |
||
21 | |||
22 | /** |
||
23 | * @var Enum[] |
||
24 | */ |
||
25 | private static $instances = []; |
||
26 | |||
27 | /** |
||
28 | * @param mixed $value |
||
29 | */ |
||
30 | final private function __construct($value) |
||
31 | { |
||
32 | $this->value = $value; |
||
33 | } |
||
34 | |||
35 | /** |
||
36 | * @param mixed $value |
||
37 | * |
||
38 | * @return Enum |
||
39 | */ |
||
40 | final public static function byValue($value) |
||
41 | { |
||
42 | $key = get_called_class().'|'.$value; |
||
43 | |||
44 | // limitation of count object instances |
||
45 | if (!isset(self::$instances[$key])) { |
||
46 | if (!static::isValid($value)) { |
||
47 | throw OutOfEnumException::create($value, get_called_class()); |
||
48 | } |
||
49 | |||
50 | self::$instances[$key] = new static($value); |
||
51 | } |
||
52 | |||
53 | return self::$instances[$key]; |
||
54 | } |
||
55 | |||
56 | /** |
||
57 | * @return mixed |
||
58 | */ |
||
59 | final public function value() |
||
63 | |||
64 | /** |
||
65 | * Available values. |
||
66 | * |
||
67 | * @return Enum[] |
||
68 | */ |
||
69 | final public static function values() |
||
78 | |||
79 | /** |
||
80 | * @param Enum $enum |
||
81 | * |
||
82 | * @return bool |
||
83 | */ |
||
84 | final public function equals(Enum $enum) |
||
85 | { |
||
86 | return $this === $enum || ($this->value() === $enum->value() && get_called_class() == get_class($enum)); |
||
87 | } |
||
88 | |||
89 | /** |
||
90 | * Is value supported. |
||
91 | * |
||
92 | * @param mixed $value |
||
93 | * |
||
94 | * @return bool |
||
95 | */ |
||
96 | final public static function isValid($value) |
||
100 | |||
101 | /** |
||
102 | * Return readable value. |
||
103 | * |
||
104 | * @return string |
||
105 | */ |
||
106 | public function __toString() |
||
110 | |||
111 | final public function __clone() |
||
115 | |||
116 | /** |
||
117 | * @return mixed |
||
118 | */ |
||
119 | public function serialize() |
||
123 | |||
124 | /** |
||
125 | * @param mixed $data |
||
126 | */ |
||
127 | public function unserialize($data) |
||
131 | } |
||
132 |