Test Failed
Push — 7.x ( bea7e1...2b11c5 )
by Adrien
08:51
created

SplBackedEnumTrait   A

Complexity

Total Complexity 7

Size/Duplication

Total Lines 66
Duplicated Lines 0 %

Importance

Changes 1
Bugs 0 Features 1
Metric Value
eloc 19
c 1
b 0
f 1
dl 0
loc 66
rs 10
wmc 7

3 Methods

Rating   Name   Duplication   Size   Complexity  
A from() 0 11 2
A __callStatic() 0 12 2
A tryFrom() 0 10 3
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
declare(strict_types=1);
13
14
namespace Ducks\Component\SplTypes;
15
16
use Ducks\Component\SplTypes\Reflection\SplReflectionEnumBackedCase;
17
18
trait SplBackedEnumTrait
19
{
20
    use SplUnitEnumTrait;
21
22
    /**
23
     * Maps a scalar to an enum instance
24
     *
25
     * @param int|string $value The scalar value to map to an enum case.
26
     *
27
     * @return static A case instance of this enumeration.
28
     */
29
    final public static function from($value): self
30
    {
31
        $case = static::tryFrom($value);
32
33
        if (null === $case) {
34
            throw new \ValueError(
35
                sprintf('%s is not a valid backing value for enum "%s"', \json_encode($value), static::class)
36
            );
37
        }
38
39
        return $case;
40
    }
41
42
    /**
43
     * Maps a scalar to an enum instance or null
44
     *
45
     * @param int|string $value e scalar value to map to an enum case.
46
     *
47
     * @return static|null A case instance of this enumeration, or null if not found.
48
     */
49
    final public static function tryFrom($value): ?self
50
    {
51
        foreach (static::cases() as $case) {
52
            if ($case->value === $value) {
53
                $result = $case;
54
                break;
55
            }
56
        }
57
58
        return $result ?? null;
59
    }
60
61
    /**
62
     * Return a new instance of enum
63
     *
64
     * @param string $name
65
     * @param array $arguments
66
     *
67
     * @return static self keywords not an equivalent
68
     *
69
     * @psalm-suppress UnsafeInstantiation
70
     * @phpstan-ignore-next-line
71
     */
72
    #[\ReturnTypeWillChange]
73
    public static function __callStatic(string $name, array $arguments)
74
    {
75
        try {
76
            $unit = new SplReflectionEnumBackedCase(static::class, $name);
77
            $object = $unit->getValue();
78
        } catch (\ReflectionException $th) {
79
            throw new \Error('Undefined constant ' . static::class . '::' . $name);
80
        }
81
82
        /** @var static $object */
83
        return $object;
84
    }
85
}
86