1 | <?php |
||
9 | abstract class Enum |
||
10 | { |
||
11 | /** |
||
12 | * The enum value. |
||
13 | * |
||
14 | * @var mixed |
||
15 | */ |
||
16 | protected $value; |
||
17 | |||
18 | /** |
||
19 | * The enum constants. |
||
20 | * |
||
21 | * @var array |
||
22 | */ |
||
23 | protected static $constants = []; |
||
24 | |||
25 | /** |
||
26 | * Create a new enum instance. |
||
27 | * |
||
28 | * @param mixed $value |
||
29 | */ |
||
30 | 18 | public function __construct($value) |
|
31 | { |
||
32 | 18 | if (!static::constants()->containsStrict($value)) { |
|
33 | 3 | throw new UnexpectedValueException(sprintf( |
|
34 | 3 | 'Value `%s` is not part of the enum %s', |
|
35 | 1 | $value, |
|
36 | 3 | static::class |
|
37 | 1 | )); |
|
38 | } |
||
39 | |||
40 | 18 | $this->value = $value; |
|
41 | 18 | } |
|
42 | |||
43 | /** |
||
44 | * @return string |
||
45 | */ |
||
46 | 3 | public function __toString() |
|
50 | |||
51 | /** |
||
52 | * Get the enum key. |
||
53 | * |
||
54 | * @return mixed |
||
55 | */ |
||
56 | 3 | public function getKey() |
|
60 | |||
61 | /** |
||
62 | * Get the enum value. |
||
63 | * |
||
64 | * @return mixed |
||
65 | */ |
||
66 | 3 | public function getValue() |
|
70 | |||
71 | /** |
||
72 | * Get the enum keys. |
||
73 | * |
||
74 | * @return array |
||
75 | */ |
||
76 | 3 | public static function keys() |
|
82 | |||
83 | /** |
||
84 | * Get the enum values. |
||
85 | * |
||
86 | * @return array |
||
87 | */ |
||
88 | 3 | public static function values() |
|
96 | |||
97 | /** |
||
98 | * Get the enum constants. |
||
99 | * |
||
100 | * @return \Illuminate\Support\Collection |
||
101 | */ |
||
102 | 27 | public static function constants() |
|
103 | { |
||
104 | 27 | if (!isset(static::$constants[static::class])) { |
|
105 | 3 | static::$constants[static::class] = collect( |
|
106 | 3 | (new ReflectionClass(static::class))->getConstants() |
|
107 | 1 | ); |
|
108 | 1 | } |
|
109 | |||
110 | 27 | return static::$constants[static::class]; |
|
111 | } |
||
112 | |||
113 | /** |
||
114 | * Returns a new enum instance when called statically. |
||
115 | * |
||
116 | * @param string $name |
||
117 | * @param array $arguments |
||
118 | * |
||
119 | * @return static |
||
120 | */ |
||
121 | 6 | public static function __callStatic($name, array $arguments) |
|
133 | } |
||
134 |