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