-
-
Notifications
You must be signed in to change notification settings - Fork 1
/
Hasser.php
72 lines (60 loc) · 1.74 KB
/
Hasser.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
<?php
declare(strict_types=1);
namespace Bakame\Aide\Enum;
use ReflectionEnum;
use function is_int;
use function is_string;
trait Hasser
{
public static function has(int|string $value): bool
{
$type = (new ReflectionEnum(static::class))->getBackingType()?->getName();
return match (true) {
('int' === $type && is_int($value) || 'string' === $type && is_string($value)) => null !== static::tryFrom($value), /* @phpstan-ignore-line */
is_int($value) => false,
default => static::hasName($value),
};
}
/**
* Tells whether the name is used as a case name.
*
* Returns true on success, false otherwise.
*/
public static function hasName(string $name): bool
{
foreach (static::cases() as $enum) {
if ($enum->name === $name) {
return true;
}
}
return false;
}
/**
* Tells whether the value is part of the enumeration.
*
* Returns true on success, false otherwise.
*/
public static function hasValue(int|string $value): bool
{
foreach (static::cases() as $enum) {
if ($enum?->value === $value) { /* @phpstan-ignore-line */
return true;
}
}
return false;
}
/**
* Tells whether the value/name pair is part of the enumeration.
*
* Returns true on success, false otherwise.
*/
public static function hasCase(string $name, int|string $value): bool
{
foreach (static::cases() as $enum) {
if ($enum?->name === $name && $enum?->value === $value) { /* @phpstan-ignore-line */
return true;
}
}
return false;
}
}