-
-
Notifications
You must be signed in to change notification settings - Fork 2
/
SplBackedEnumTrait.php
110 lines (98 loc) · 2.74 KB
/
SplBackedEnumTrait.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
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
<?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;
use Ducks\Component\SplTypes\Reflection\SplReflectionEnumBackedCase;
/**
* Simplify SplBackedEnum integration
*
* @template T
*
* @property-read mixed $value
*
* @phpstan-require-implements SplBackedEnum
*/
trait SplBackedEnumTrait
{
use SplUnitEnumTrait;
/**
* Maps a scalar to an enum instance.
*
* @param int|string $value The scalar value to map to an enum case.
*
* @return static A case instance of this enumeration.
*
* @throws \ValueError if $value is not a valid backing value for enum
*/
final public static function from($value): self
{
$case = static::tryFrom($value);
if (null === $case) {
throw new \ValueError(
sprintf('%s is not a valid backing value for enum "%s"', \json_encode($value), static::class)
);
}
return $case;
}
/**
* Maps a scalar to an enum instance or null.
*
* @param int|string|mixed $value e scalar value to map to an enum case.
*
* @return static|null A case instance of this enumeration, or null if not found.
*
* @psalm-suppress UnusedVariable
*/
final public static function tryFrom($value): ?self
{
foreach (static::cases() as $case) {
/**
* @var SplEnumBacked $case
*
* @phpstan-var SplEnumBacked<T> $case
*/
if ($case->value === $value) {
$result = $case;
break;
}
}
/** @var static|null $result */
return $result ?? null;
}
/**
* Return a new instance of enum.
*
* @param string $name
* @param mixed[] $arguments
*
* @return static self keywords not an equivalent
*
* @throws \Error if $name is not a valid constant enum
*
* @phpstan-param string $name
* @phpstan-param list<mixed> $arguments
* @phpstan-return static
* @phpstan-ignore-next-line
*
* @psalm-suppress UnsafeInstantiation
*/
#[\ReturnTypeWillChange]
public static function __callStatic(string $name, array $arguments)
{
try {
$unit = new SplReflectionEnumBackedCase(static::class, $name);
$object = $unit->getValue();
} catch (\ReflectionException $th) {
throw new \Error('Undefined constant ' . static::class . '::' . $name);
}
/** @var static $object */
return $object;
}
}