Passed
Push — 7.x ( 9aeb39...d57385 )
by Adrien
10:00
created

SplEnumTrait::cases()   A

Complexity

Conditions 3
Paths 2

Size

Total Lines 12
Code Lines 6

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 3
eloc 6
c 1
b 0
f 0
nc 2
nop 0
dl 0
loc 12
rs 10
1
<?php
2
3
/**
4
 * Part of SplTypes package.
5
 *
6
 * (c) Adrien Loyant <[email protected]>
7
 *
8
 * For the full copyright and license information, please view the LICENSE
9
 * file that was distributed with this source code.
10
 */
11
12
namespace Ducks\Component\SplTypes;
13
14
/**
15
 * Trait used for enum emulation
16
 *
17
 * @psalm-api
18
 */
19
trait SplEnumTrait
20
{
21
    /**
22
     * Generates a list of cases on an enum
23
     *
24
     * @return array An array of all defined cases of this enumeration, in order of declaration.
25
     */
26
    public static function cases(): array
27
    {
28
        static $cases = null;
29
30
        if (!isset($cases)) {
31
            $enum = new \ReflectionEnum(static::class);
0 ignored issues
show
Bug introduced by
The type ReflectionEnum was not found. Maybe you did not declare it correctly or list all dependencies?

The issue could also be caused by a filter entry in the build configuration. If the path has been excluded in your configuration, e.g. excluded_paths: ["lib/*"], you can move it to the dependency path list as follows:

filter:
    dependency_paths: ["lib/*"]

For further information see https://scrutinizer-ci.com/docs/tools/php/php-scrutinizer/#list-dependency-paths

Loading history...
32
            foreach ($enum->getCases() as $case) {
33
                $cases[] = $case->getValue();
34
            }
35
        }
36
37
        return $cases ?? [];
38
    }
39
40
    /**
41
     * Maps a scalar to an enum instance
42
     *
43
     * @param int|string $value The scalar value to map to an enum case.
44
     *
45
     * @return SplEnum A case instance of this enumeration.
46
     */
47
    final public static function from($value): self
48
    {
49
        $case = static::tryFrom($value);
50
51
        if (null === $case) {
52
            throw new \ValueError(
53
                sprintf('%s is not a valid backing value for enum "%s"', \json_encode($value), static::class)
54
            );
55
        }
56
57
        return $case;
58
    }
59
60
    /**
61
     * Maps a scalar to an enum instance or null
62
     *
63
     * @param int|string $value e scalar value to map to an enum case.
64
     *
65
     * @return SplEnum|null A case instance of this enumeration, or null if not found.
66
     */
67
    final public static function tryFrom($value): ?self
68
    {
69
        foreach (static::cases() as $case) {
70
            if ($case->value === $value) {
71
                $result = $case;
72
                break;
73
            }
74
        }
75
76
        return $result ?? null;
77
    }
78
}
79