-
-
Notifications
You must be signed in to change notification settings - Fork 1
/
Factory.php
41 lines (32 loc) · 872 Bytes
/
Factory.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
<?php
declare(strict_types=1);
namespace Bakame\Aide\Enum;
use ValueError;
trait Factory
{
public static function tryFrom(string $value): ?static
{
return static::tryFromName($value);
}
public static function from(string $value): static
{
return static::fromName($value);
}
public static function tryFromName(string $name): ?static
{
foreach (static::cases() as $case) {
if ($case->name === $name) {
return $case;
}
}
return null;
}
public static function fromName(string $name): static
{
$instance = static::tryFromName($name);
return match (null) {
$instance => throw new ValueError('"'.$name.'" is not a valid name for "'.static::class.'" enumeration.'),
default => $instance,
};
}
}