-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathEnum.php
More file actions
96 lines (75 loc) · 2.19 KB
/
Enum.php
File metadata and controls
96 lines (75 loc) · 2.19 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
88
89
90
91
92
93
94
95
96
<?php
declare(strict_types=1);
namespace Src\Shared\Domain\ValueObjects;
use Src\Shared\Domain\Exceptions\InvalidValueObjectException;
abstract class Enum
{
protected static $cache = [];
protected $value;
public function __construct($value)
{
$this->ensureIsBetweenAcceptedValues($value);
$this->value = $value;
}
public static function __callStatic(string $name, $args)
{
return new static(self::values()[$name]);
}
public static function values(): array
{
$class = static::class;
if (!isset(self::$cache[$class])) {
$reflected = new \ReflectionClass($class);
self::$cache[$class] = self::reindex(self::keysFormatter(), $reflected->getConstants());
}
return self::$cache[$class];
}
public static function randomValue()
{
return self::values()[array_rand(self::values())];
}
public static function random()
{
return new static(self::randomValue());
}
private static function keysFormatter(): callable
{
return static function ($unused, $key): string {
return self::toCamelCase(strtolower($key));
};
}
private static function toCamelCase(string $text): string
{
return lcfirst(str_replace('_', '', ucwords($text, '_')));
}
public function value()
{
return $this->value;
}
public function equals(Enum $other): bool
{
return $other == $this;
}
public function __toString(): string
{
return (string) $this->value();
}
private function ensureIsBetweenAcceptedValues($value): void
{
if (!\in_array($value, static::values(), true)) {
$this->throwExceptionForInvalidValue($value);
}
}
protected function throwExceptionForInvalidValue($value): void
{
throw new InvalidValueObjectException(sprintf('<%s>Invalid value: <%s>', static::class, $value));
}
private static function reindex(callable $fn, iterable $coll): array
{
$result = [];
foreach ($coll as $key => $value) {
$result[$fn($value, $key)] = $value;
}
return $result;
}
}