1
|
|
|
<?php namespace BuildR\Utils\Enumeration; |
2
|
|
|
|
3
|
|
|
use \ReflectionClass; |
4
|
|
|
use \Countable; |
5
|
|
|
use BuildR\Foundation\Object\StringConvertibleInterface; |
6
|
|
|
use BuildR\Utils\Enumeration\Exception\EnumerationException; |
7
|
|
|
|
8
|
|
|
class EnumerationBase implements StringConvertibleInterface, Countable { |
|
|
|
|
9
|
|
|
|
10
|
|
|
public $value; |
11
|
|
|
|
12
|
|
|
private static $cache = []; |
13
|
|
|
|
14
|
|
|
public function __construct($value) { |
15
|
|
|
if(!$this->isValid($value)) { |
16
|
|
|
throw EnumerationException::invalidValue($value); |
17
|
|
|
} |
18
|
|
|
|
19
|
|
|
$this->value = $value; |
20
|
|
|
} |
21
|
|
|
|
22
|
|
|
public function isValid($value) { |
23
|
|
|
return (bool) in_array($value, self::toArray()); |
24
|
|
|
} |
25
|
|
|
|
26
|
|
|
public function getValue() { |
27
|
|
|
return $this->value; |
28
|
|
|
} |
29
|
|
|
|
30
|
|
|
public static function toArray() { |
31
|
|
|
$enumClass = get_called_class(); |
32
|
|
|
|
33
|
|
|
if(!array_key_exists($enumClass, self::$cache)) { |
34
|
|
|
$reflector = new ReflectionClass($enumClass); |
35
|
|
|
self::$cache[$enumClass] = $reflector->getConstants(); |
36
|
|
|
} |
37
|
|
|
|
38
|
|
|
return self::$cache[$enumClass]; |
39
|
|
|
} |
40
|
|
|
|
41
|
|
|
public static function getKeys() { |
42
|
|
|
return array_keys(self::toArray()); |
43
|
|
|
} |
44
|
|
|
|
45
|
|
|
public static function isValidKey($key) { |
46
|
|
|
if(!is_string($key)) { |
47
|
|
|
throw EnumerationException::invalidKeyType(gettype($key)); |
48
|
|
|
} |
49
|
|
|
|
50
|
|
|
return array_key_exists($key, self::toArray()); |
51
|
|
|
} |
52
|
|
|
|
53
|
|
|
public static function size() { |
54
|
|
|
return count(self::toArray()); |
55
|
|
|
} |
56
|
|
|
|
57
|
|
|
public static function __callStatic($name, $arguments) { |
|
|
|
|
58
|
|
|
$calledClass = get_called_class(); |
59
|
|
|
$args[] = $name; |
|
|
|
|
60
|
|
|
|
61
|
|
|
if(array_key_exists(EnumerationFieldDefinitionInterface::class, class_implements($calledClass))) { |
62
|
|
|
$fields = static::defineFields()[$name]; |
63
|
|
|
array_unshift($fields, $args[0]); |
64
|
|
|
|
65
|
|
|
$args = $fields; |
66
|
|
|
} |
67
|
|
|
|
68
|
|
|
$reflector = new ReflectionClass($calledClass); |
69
|
|
|
return $reflector->newInstanceArgs($args); |
70
|
|
|
} |
71
|
|
|
// ========================================== |
72
|
|
|
// StringConvertibleInterface implementation |
73
|
|
|
|
74
|
|
|
// ========================================== |
75
|
|
|
|
76
|
|
|
/** |
77
|
|
|
* {@inheritdoc} |
78
|
|
|
*/ |
79
|
|
|
public function __toString() { |
80
|
|
|
return $this->value; |
81
|
|
|
} |
82
|
|
|
|
83
|
|
|
/** |
84
|
|
|
* {@inheritdoc} |
85
|
|
|
*/ |
86
|
|
|
public function toString() { |
87
|
|
|
return $this->value; |
88
|
|
|
} |
89
|
|
|
|
90
|
|
|
} |
91
|
|
|
|