1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
/** |
4
|
|
|
* This file is part of RussianPost SDK package. |
5
|
|
|
* |
6
|
|
|
* © Appwilio (http://appwilio.com), greabock (https://github.com/greabock), JhaoDa (https://github.com/jhaoda) |
7
|
|
|
* |
8
|
|
|
* For the full copyright and license information, please view the LICENSE |
9
|
|
|
* file that was distributed with this source code. |
10
|
|
|
*/ |
11
|
|
|
|
12
|
|
|
declare(strict_types=1); |
13
|
|
|
|
14
|
|
|
namespace Appwilio\RussianPostSDK\Core; |
15
|
|
|
|
16
|
|
|
abstract class Enum implements \JsonSerializable |
17
|
|
|
{ |
18
|
|
|
protected static $cache = []; |
19
|
|
|
|
20
|
|
|
protected $value; |
21
|
|
|
|
22
|
16 |
|
public function __construct($value) |
23
|
|
|
{ |
24
|
16 |
|
if ($value instanceof static) { |
25
|
1 |
|
$value = $value->getValue(); |
26
|
|
|
} |
27
|
|
|
|
28
|
16 |
|
if (! \in_array($value, static::toArray(), true)) { |
29
|
|
|
throw new \UnexpectedValueException("Value '$value' is not part of the enum ".static::class); |
30
|
|
|
} |
31
|
|
|
|
32
|
16 |
|
$this->value = $value; |
33
|
16 |
|
} |
34
|
|
|
|
35
|
16 |
|
public static function toArray(): array |
36
|
|
|
{ |
37
|
16 |
|
$class = static::class; |
38
|
|
|
|
39
|
16 |
|
if (! isset(static::$cache[$class])) { |
40
|
4 |
|
static::$cache[$class] = (new \ReflectionClass($class))->getConstants(); |
41
|
|
|
} |
42
|
|
|
|
43
|
16 |
|
return static::$cache[$class]; |
44
|
|
|
} |
45
|
|
|
|
46
|
16 |
|
public static function __callStatic($name, $arguments) |
47
|
|
|
{ |
48
|
16 |
|
$options = static::toArray(); |
49
|
|
|
|
50
|
16 |
|
if (isset($options[$name]) || \array_key_exists($name, $options)) { |
51
|
16 |
|
return new static($options[$name]); |
52
|
|
|
} |
53
|
|
|
|
54
|
|
|
throw new \BadMethodCallException("No static method or enum constant '$name' in class ".static::class); |
55
|
|
|
} |
56
|
|
|
|
57
|
1 |
|
public function jsonSerialize() |
58
|
|
|
{ |
59
|
1 |
|
return $this->getValue(); |
60
|
|
|
} |
61
|
|
|
|
62
|
2 |
|
final public function equals(Enum $other): bool |
63
|
|
|
{ |
64
|
2 |
|
return $this === $other || (\get_class($other) === static::class && $this->value === $other->value); |
65
|
|
|
} |
66
|
|
|
|
67
|
16 |
|
final public function getValue() |
68
|
|
|
{ |
69
|
16 |
|
return $this->value; |
70
|
|
|
} |
71
|
|
|
|
72
|
|
|
final private function __clone() |
73
|
|
|
{ |
74
|
|
|
throw new \LogicException('Enums are not cloneable'); |
75
|
|
|
} |
76
|
|
|
|
77
|
|
|
final public function __sleep() |
78
|
|
|
{ |
79
|
|
|
throw new \LogicException('Enums are not serializable'); |
80
|
|
|
} |
81
|
|
|
|
82
|
|
|
final public function __wakeup() |
83
|
|
|
{ |
84
|
|
|
throw new \LogicException('Enums are not serializable'); |
85
|
|
|
} |
86
|
|
|
} |
87
|
|
|
|