-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathAbstractEnum.php
More file actions
87 lines (78 loc) · 1.99 KB
/
AbstractEnum.php
File metadata and controls
87 lines (78 loc) · 1.99 KB
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
80
81
82
83
84
85
86
87
<?php
namespace CommerceGuys\Enum;
/**
* Base class for enumerations.
*/
abstract class AbstractEnum
{
/**
* Static cache of available values, shared with all subclasses.
*
* @var array
*/
protected static $values = [];
private function __construct()
{
}
/**
* Gets all available values.
*
* @return array The available values, keyed by constant.
*/
public static function getAll()
{
$class = get_called_class();
if (!isset(static::$values[$class])) {
$reflection = new \ReflectionClass($class);
static::$values[$class] = $reflection->getConstants();
}
return static::$values[$class];
}
/**
* Gets the key of the provided value.
*
* @param string $value The value.
*
* @return bool The key if found, false otherwise.
*/
public static function getKey($value)
{
return array_search($value, static::getAll(), true);
}
/**
* Checks whether the provided value is defined.
*
* @param string $value The value.
*
* @return bool True if the value is defined, false otherwise.
*/
public static function exists($value)
{
return in_array($value, static::getAll(), true);
}
/**
* Asserts that the provided value is defined.
*
* @param string $value The value.
*
* @throws \InvalidArgumentException
*/
public static function assertExists($value)
{
if (static::exists($value) === false) {
$class = substr(strrchr(get_called_class(), '\\'), 1);
throw new \InvalidArgumentException(sprintf('"%s" is not a valid %s value.', $value, $class));
}
}
/**
* Asserts that all provided valus are defined.
*
* @param array $values The values.
*/
public static function assertAllExist(array $values)
{
foreach ($values as $value) {
static::assertExists($value);
}
}
}