-
Notifications
You must be signed in to change notification settings - Fork 0
/
SplEnum.php
73 lines (62 loc) · 1.83 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
<?php
if (!class_exists('SplEnum')) {
/**
* A polyfill for the 'SplEnum' class.
*
* @author Osama Aldemeery <[email protected]>
*/
abstract class SplEnum
{
/**
* @constant(__default) The default value of the enum.
*/
protected const __default = null;
/**
* The current value of the enum.
*
* @var mixed
*/
protected $value;
/**
* splEnum constructor.
*
* @param mixed $value The initial value of the enum.
*
* @throws UnexpectedValueException
*/
public function __construct($value = null)
{
$ref = new \ReflectionClass($this);
if (!in_array($value, $ref->getConstants())) {
throw new \UnexpectedValueException("Value '$value' is not part of the enum " . get_called_class());
}
$this->value = $value;
}
/**
* Get a list of all the constants in the enum
*
* @param bool $include_default Whether to include the default value in the list or no.
*
* @return array The list of constants defined in the enum.
*/
public static function getConstList($include_default = false)
{
$reflected = new \ReflectionClass(new static(null));
$constants = $reflected->getConstants();
if (!$include_default) {
unset($constants['__default']);
return $constants;
}
return $constants;
}
/**
* The string representation of the enum.
*
* @return string The current value of the enum.
*/
final public function __toString()
{
return strval($this->value);
}
}
}