|
1
|
|
|
<?php |
|
2
|
|
|
|
|
3
|
|
|
declare(strict_types=1); |
|
4
|
|
|
|
|
5
|
|
|
namespace LM\Common\Enum; |
|
6
|
|
|
|
|
7
|
|
|
use InvalidArgumentException; |
|
8
|
|
|
use ReflectionClass; |
|
9
|
|
|
|
|
10
|
|
|
/** |
|
11
|
|
|
* This is a class that enums can inherit for convenience. |
|
12
|
|
|
* |
|
13
|
|
|
* Any implementation of this class only needs to define constants, and does |
|
14
|
|
|
* not need to define a constructor or any other method. |
|
15
|
|
|
* |
|
16
|
|
|
* @example Scalar.php An implementation. |
|
17
|
|
|
* @deprecated |
|
18
|
|
|
* @todo Don't use enums at all. |
|
19
|
|
|
*/ |
|
20
|
|
|
abstract class AbstractEnum implements IEnum |
|
21
|
|
|
{ |
|
22
|
|
|
/** @var string */ |
|
23
|
|
|
private $value; |
|
24
|
|
|
|
|
25
|
|
|
/** |
|
26
|
|
|
* @return string[] An array of constants defined by the enum. |
|
27
|
|
|
* |
|
28
|
|
|
* @todo Shouldn't static methods be avoided? |
|
29
|
|
|
*/ |
|
30
|
|
|
public static function getConstants() |
|
31
|
|
|
{ |
|
32
|
|
|
$reflectionClass = new ReflectionClass(static::class); |
|
33
|
|
|
|
|
34
|
|
|
return $reflectionClass->getConstants(); |
|
35
|
|
|
} |
|
36
|
|
|
|
|
37
|
|
|
/** |
|
38
|
|
|
* This constructor saves subclasses of this class the burden of defining |
|
39
|
|
|
* a constructor. |
|
40
|
|
|
* @param string $value The value to initialise the enum with. It is checked |
|
41
|
|
|
* for correctness. (It needs to be among the constants.) |
|
42
|
|
|
*/ |
|
43
|
|
|
public function __construct(string $value) |
|
44
|
|
|
{ |
|
45
|
|
|
if (!in_array($value, static::getConstants(), true)) { |
|
46
|
|
|
throw new InvalidArgumentException(); |
|
47
|
|
|
} |
|
48
|
|
|
$this->value = $value; |
|
49
|
|
|
} |
|
50
|
|
|
|
|
51
|
|
|
public function getValue(): string |
|
52
|
|
|
{ |
|
53
|
|
|
return $this->value; |
|
54
|
|
|
} |
|
55
|
|
|
|
|
56
|
|
|
public function is(IEnum $enum): bool |
|
57
|
|
|
{ |
|
58
|
|
|
if (get_class($enum) !== get_class($this)) { |
|
59
|
|
|
return false; |
|
60
|
|
|
} |
|
61
|
|
|
if ($this->value !== $enum->getValue()) { |
|
62
|
|
|
return false; |
|
63
|
|
|
} |
|
64
|
|
|
|
|
65
|
|
|
return true; |
|
66
|
|
|
} |
|
67
|
|
|
|
|
68
|
|
|
public function serialize() |
|
69
|
|
|
{ |
|
70
|
|
|
return serialize($this->value); |
|
71
|
|
|
} |
|
72
|
|
|
|
|
73
|
|
|
public function unserialize($serialized) |
|
74
|
|
|
{ |
|
75
|
|
|
$this->value = unserialize($serialized); |
|
76
|
|
|
} |
|
77
|
|
|
} |
|
78
|
|
|
|