Issues (72)

src/Concerns/Hydrates.php (1 issue)

Labels
Severity
1
<?php
2
3
declare(strict_types=1);
4
5
namespace Cerbero\Enum\Concerns;
6
7
use Cerbero\Enum\CasesCollection;
8
use ValueError;
9
10
/**
11
 * The trait to hydrate an enum.
12
 */
13
trait Hydrates
14
{
15
    /**
16
     * Retrieve the case hydrated from the given name or fail.
17
     * This method can be called by pure enums only.
18
     *
19
     * @throws ValueError
20
     */
21 4
    public static function from(int|string $name): static
22
    {
23 4
        return self::fromName($name);
24
    }
25
26
    /**
27
     * Retrieve the case hydrated from the given name or fail.
28
     *
29
     * @throws ValueError
30
     */
31 16
    public static function fromName(int|string $name): static
32
    {
33 16
        if ($case = self::tryFromName($name)) {
34 11
            return $case;
35
        }
36
37 5
        throw new ValueError(sprintf('"%s" is not a valid name for enum "%s"', $name, self::class));
38
    }
39
40
    /**
41
     * Retrieve the case hydrated from the given name or NULL.
42
     */
43 28
    public static function tryFromName(int|string $name): ?static
0 ignored issues
show
A parse error occurred: Syntax error, unexpected T_STATIC on line 43 at column 59
Loading history...
44
    {
45 28
        foreach (self::cases() as $case) {
46 28
            if ($case->name === $name) {
47 20
                return $case;
48
            }
49
        }
50
51 8
        return null;
52
    }
53
54
    /**
55
     * Retrieve the case hydrated from the given name or NULL.
56
     * This method can be called by pure enums only.
57
     */
58 4
    public static function tryFrom(int|string $name): ?static
59
    {
60 4
        return self::tryFromName($name);
61
    }
62
63
    /**
64
     * Retrieve all the cases hydrated from the given meta or fail.
65
     *
66
     * @return CasesCollection<self>
67
     * @throws ValueError
68
     */
69 8
    public static function fromMeta(string $meta, mixed $value = true): CasesCollection
70
    {
71 8
        if ($cases = self::tryFromMeta($meta, $value)) {
72 6
            return $cases;
73
        }
74
75 2
        throw new ValueError(sprintf('Invalid value for the meta "%s" for enum "%s"', $meta, self::class));
76
    }
77
78
    /**
79
     * Retrieve all the cases hydrated from the given meta or NULL.
80
     *
81
     * @return ?CasesCollection<self>
82
     */
83 14
    public static function tryFromMeta(string $meta, mixed $value = true): ?CasesCollection
84
    {
85 14
        $cases = [];
86
87 14
        foreach (self::cases() as $case) {
88 14
            $metaValue = $case->resolveMeta($meta);
89
90 14
            if ((is_callable($value) && $value($metaValue) === true) || $metaValue === $value) {
91 10
                $cases[] = $case;
92
            }
93
        }
94
95 14
        return $cases ? new CasesCollection($cases) : null;
96
    }
97
}
98