-
-
Notifications
You must be signed in to change notification settings - Fork 1
/
Info.php
101 lines (87 loc) · 2.21 KB
/
Info.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
<?php
declare(strict_types=1);
namespace Bakame\Aide\Enum;
use ReflectionEnum;
use UnitEnum;
use function array_column;
use function array_search;
use function count;
trait Info
{
public static function isBacked(): bool
{
return (new ReflectionEnum(static::class))->isBacked(); /* @phpstan-ignore-line */
}
public static function isPure(): bool
{
return !static::isBacked();
}
public static function size(): int
{
return count(static::cases());
}
/**
* List the Enum backed name.
*
* @return list<string>
*/
public static function names(): array
{
return array_column(static::cases(), 'name');
}
/**
* List the Enum values if they exist.
* Returns an empty array for non-backed Enumeration.
*
* @return list<string|int>
*/
public static function values(): array
{
return array_column(static::cases(), 'value');
}
/**
* Returns the enumeration name associated to the value if it exists.
* Otherwise, null is returned.
*/
public static function nameOf(string|int $value): ?string
{
/** @var string|false $res */
$res = array_search(
$value,
array_column(static::cases(), 'value', 'name'),
true
);
return match ($res) {
false => null,
default => $res,
};
}
/**
* Returns the list of cases not including the enum instance passed to the method call.
*
* @return array<UnitEnum>
*/
public static function except(UnitEnum ...$values): array
{
return array_values(
array_filter(
static::cases(),
fn (UnitEnum $enum) => !in_array($enum, $values, true)
)
);
}
/**
* Returns the list of cases including only the enum listed in the method call if they exist.
*
* @return array<UnitEnum>
*/
public static function only(UnitEnum ...$values): array
{
return array_values(
array_filter(
static::cases(),
fn (UnitEnum $enum) => in_array($enum, $values, true)
)
);
}
}