1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
/** |
4
|
|
|
* Part of SplTypes package. |
5
|
|
|
* |
6
|
|
|
* (c) Adrien Loyant <[email protected]> |
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 Ducks\Component\SplTypes; |
15
|
|
|
|
16
|
|
|
/** |
17
|
|
|
* SplEnum gives the ability to emulate and create enumeration objects natively in PHP. |
18
|
|
|
* |
19
|
|
|
* @template T |
20
|
|
|
* @extends SplType<T> |
21
|
|
|
* |
22
|
|
|
* @psalm-api |
23
|
|
|
* |
24
|
|
|
* @psalm-suppress MissingDependency |
25
|
|
|
* @psalm-suppress UndefinedClass |
26
|
|
|
*/ |
27
|
|
|
abstract class SplEnum extends SplType implements SplEnumerable |
28
|
|
|
{ |
29
|
|
|
use SplEnumTrait; |
30
|
|
|
/** @use SplEnumAccessorsTrait<T> */ |
31
|
|
|
use SplEnumAccessorsTrait; |
32
|
|
|
|
33
|
|
|
/** |
34
|
|
|
* {@inheritdoc} |
35
|
|
|
* |
36
|
|
|
* @param mixed $initial_value |
37
|
|
|
* @param bool $strict |
38
|
|
|
* |
39
|
|
|
* @phpstan-param T|null $initial_value |
40
|
|
|
* @phpstan-param bool $strict |
41
|
|
|
* |
42
|
|
|
* @throws \UnexpectedValueException if incompatible type is given. |
43
|
|
|
* |
44
|
|
|
* @SuppressWarnings(PHPMD.CamelCaseParameterName) |
45
|
|
|
* @SuppressWarnings(PHPMD.CamelCaseVariableName) |
46
|
|
|
*/ |
47
|
10 |
|
public function __construct($initial_value = self::__default, bool $strict = true) |
48
|
|
|
{ |
49
|
|
|
/** @var T $initial_value */ |
50
|
10 |
|
$initial_value ??= static::__default; |
51
|
|
|
|
52
|
10 |
|
if (!\in_array($initial_value, $this->getConstList(), $strict)) { |
53
|
1 |
|
throw new \UnexpectedValueException('Cannot instantiate, Value not a const in enum ' . __CLASS__); |
54
|
|
|
} |
55
|
|
|
|
56
|
9 |
|
parent::__construct($initial_value); |
57
|
|
|
} |
58
|
|
|
|
59
|
|
|
/** |
60
|
|
|
* Returns all consts (possible values) as an array. |
61
|
|
|
* |
62
|
|
|
* @param bool $include_default Whether to include __default property. |
63
|
|
|
* |
64
|
|
|
* @return mixed[] |
65
|
|
|
* |
66
|
|
|
* @SuppressWarnings(PHPMD.CamelCaseParameterName) |
67
|
|
|
* @SuppressWarnings(PHPMD.CamelCaseVariableName) |
68
|
|
|
*/ |
69
|
10 |
|
final public function getConstList(bool $include_default = false) |
70
|
|
|
{ |
71
|
10 |
|
$class = new \ReflectionClass($this); |
72
|
10 |
|
$constants = $class->getConstants(); |
73
|
10 |
|
if (!$include_default) { |
74
|
10 |
|
unset($constants['__default']); |
75
|
|
|
} |
76
|
|
|
|
77
|
10 |
|
return $constants; |
78
|
|
|
} |
79
|
|
|
} |
80
|
|
|
|