|
1
|
|
|
<?php |
|
2
|
|
|
|
|
3
|
|
|
/** |
|
4
|
|
|
* Part of SplTypes package. |
|
5
|
|
|
* |
|
6
|
|
|
* (c) Adrien Loyant <[email protected]> |
|
7
|
|
|
* |
|
8
|
|
|
* For the full copyright and license information, please view the LICENSE |
|
9
|
|
|
* file that was distributed with this source code. |
|
10
|
|
|
*/ |
|
11
|
|
|
|
|
12
|
|
|
declare(strict_types=1); |
|
13
|
|
|
|
|
14
|
|
|
namespace Ducks\Component\SplTypes; |
|
15
|
|
|
|
|
16
|
|
|
use Ducks\Component\SplTypes\Reflection\SplReflectionEnumBackedCase; |
|
17
|
|
|
|
|
18
|
|
|
trait SplBackedEnumTrait |
|
19
|
|
|
{ |
|
20
|
|
|
use SplUnitEnumTrait; |
|
21
|
|
|
|
|
22
|
|
|
/** |
|
23
|
|
|
* Maps a scalar to an enum instance |
|
24
|
|
|
* |
|
25
|
|
|
* @param int|string $value The scalar value to map to an enum case. |
|
26
|
|
|
* |
|
27
|
|
|
* @return static A case instance of this enumeration. |
|
28
|
|
|
*/ |
|
29
|
|
|
final public static function from($value): self |
|
30
|
|
|
{ |
|
31
|
|
|
$case = static::tryFrom($value); |
|
32
|
|
|
|
|
33
|
|
|
if (null === $case) { |
|
34
|
|
|
throw new \ValueError( |
|
35
|
|
|
sprintf('%s is not a valid backing value for enum "%s"', \json_encode($value), static::class) |
|
36
|
|
|
); |
|
37
|
|
|
} |
|
38
|
|
|
|
|
39
|
|
|
return $case; |
|
40
|
|
|
} |
|
41
|
|
|
|
|
42
|
|
|
/** |
|
43
|
|
|
* Maps a scalar to an enum instance or null |
|
44
|
|
|
* |
|
45
|
|
|
* @param int|string $value e scalar value to map to an enum case. |
|
46
|
|
|
* |
|
47
|
|
|
* @return static|null A case instance of this enumeration, or null if not found. |
|
48
|
|
|
*/ |
|
49
|
|
|
final public static function tryFrom($value): ?self |
|
50
|
|
|
{ |
|
51
|
|
|
foreach (static::cases() as $case) { |
|
52
|
|
|
if ($case->value === $value) { |
|
53
|
|
|
$result = $case; |
|
54
|
|
|
break; |
|
55
|
|
|
} |
|
56
|
|
|
} |
|
57
|
|
|
|
|
58
|
|
|
return $result ?? null; |
|
59
|
|
|
} |
|
60
|
|
|
|
|
61
|
|
|
/** |
|
62
|
|
|
* Return a new instance of enum |
|
63
|
|
|
* |
|
64
|
|
|
* @param string $name |
|
65
|
|
|
* @param array $arguments |
|
66
|
|
|
* |
|
67
|
|
|
* @return static self keywords not an equivalent |
|
68
|
|
|
* |
|
69
|
|
|
* @psalm-suppress UnsafeInstantiation |
|
70
|
|
|
* @phpstan-ignore-next-line |
|
71
|
|
|
*/ |
|
72
|
|
|
#[\ReturnTypeWillChange] |
|
73
|
|
|
public static function __callStatic(string $name, array $arguments) |
|
74
|
|
|
{ |
|
75
|
|
|
try { |
|
76
|
|
|
$unit = new SplReflectionEnumBackedCase(static::class, $name); |
|
77
|
|
|
$object = $unit->getValue(); |
|
78
|
|
|
} catch (\ReflectionException $th) { |
|
79
|
|
|
throw new \Error('Undefined constant ' . static::class . '::' . $name); |
|
80
|
|
|
} |
|
81
|
|
|
|
|
82
|
|
|
/** @var static $object */ |
|
83
|
|
|
return $object; |
|
84
|
|
|
} |
|
85
|
|
|
} |
|
86
|
|
|
|