-
-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathSplUnitEnumTrait.php
90 lines (79 loc) · 2.14 KB
/
SplUnitEnumTrait.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
<?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\SplReflectionEnum;
use Ducks\Component\SplTypes\Reflection\SplReflectionEnumUnitCase;
/**
* Simplify SplUnitEnum integration
*
* @property-read string $name
*
* @phpstan-require-implements SplUnitEnum
*/
trait SplUnitEnumTrait
{
use SplEnumSingletonTrait;
/**
* case-sensitive name of the case itself.
*
* @var string
*/
protected string $name;
/**
* Generates a list of cases on an enum
*
* @return static[] An array of all defined cases of this enumeration, in order of declaration.
*
* @psalm-suppress MixedInferredReturnType
*
* @see SplUnitEnum::cases()
*/
public static function cases(): array
{
static $cases = null;
if (null === $cases) {
$enum = new SplReflectionEnum(static::class);
foreach ($enum->getCases() as $case) {
$cases[] = $case->getValue();
}
}
return $cases ?? [];
}
/**
* 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 SplReflectionEnumUnitCase(static::class, $name);
$object = $unit->getValue();
} catch (\ReflectionException $th) {
throw new \Error('Undefined constant ' . static::class . '::' . $name);
}
/** @var static $object */
return $object;
}
}