1 | <?php |
||
13 | abstract class AbstractEnum |
||
14 | { |
||
15 | protected $value; |
||
16 | |||
17 | 12 | protected function __construct($value) |
|
18 | { |
||
19 | 12 | if (!$this->isValid($value)) { |
|
20 | 4 | $message = 'Value [%s] is not matching any valid value of class "%s". Valid values are [%s].'; |
|
21 | |||
22 | 4 | throw new InvalidArgumentException(sprintf( |
|
23 | 4 | $message, |
|
24 | 4 | $value, |
|
25 | 4 | $this->getClassName(), |
|
26 | 4 | self::getValidOptionsAsString() |
|
27 | )); |
||
28 | } |
||
29 | |||
30 | 8 | $this->value = $value; |
|
31 | 8 | } |
|
32 | |||
33 | /** |
||
34 | * @return static |
||
35 | */ |
||
36 | 11 | public static function get($value): self |
|
37 | { |
||
38 | 11 | return new static($value); |
|
39 | } |
||
40 | |||
41 | 2 | public static function __callStatic(string $methodName, array $arguments): self |
|
42 | { |
||
43 | 2 | foreach (self::getConstants() as $option => $value) { |
|
44 | 2 | $expectedMethodName = lcfirst(Inflector::classify(strtolower($option))); |
|
45 | 2 | if ($expectedMethodName === $methodName) { |
|
46 | 1 | return new static($value); |
|
47 | } |
||
48 | } |
||
49 | |||
50 | 1 | throw new BadMethodCallException(sprintf('%s::%s() does not exist', static::class, $methodName)); |
|
51 | } |
||
52 | |||
53 | /** |
||
54 | * @return mixed |
||
55 | */ |
||
56 | 6 | public function getValue() |
|
57 | { |
||
58 | 6 | return $this->value; |
|
59 | } |
||
60 | |||
61 | 4 | public function equals(self $other): bool |
|
65 | |||
66 | 3 | public function __toString(): string |
|
67 | { |
||
68 | 3 | return (string) $this->value; |
|
69 | } |
||
70 | |||
71 | 12 | protected function isValid($value): bool |
|
75 | |||
76 | 13 | public static function getValidOptions(): array |
|
77 | { |
||
78 | 13 | return array_values(self::getConstants()); |
|
79 | } |
||
80 | |||
81 | 4 | protected function getClassName(): string |
|
85 | |||
86 | 14 | private static function getConstants(): array |
|
90 | |||
91 | 4 | private static function getValidOptionsAsString(): string |
|
100 | } |
||
101 |