Passed
Push — master ( 43d236...683d13 )
by Pol
12:42 queued 10:44
created

Enum::value()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 3
Code Lines 1

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 2
CRAP Score 1

Importance

Changes 0
Metric Value
cc 1
eloc 1
nc 1
nop 1
dl 0
loc 3
ccs 2
cts 2
cp 1
crap 1
rs 10
c 0
b 0
f 0
1
<?php
2
3
/**
4
 * For the full copyright and license information, please view
5
 * the LICENSE file that was distributed with this source code.
6
 */
7
8
declare(strict_types=1);
9
10
namespace loophp\phposinfo\Enum;
11
12
use Exception;
13
use Generator;
14
use ReflectionClass;
15
use ReflectionException;
16
17
use function constant;
18
19
abstract class Enum
20
{
21
    /**
22
     * @return Generator<int|string>
23
     */
24 4
    final public static function getIterator(): Generator
25
    {
26 4
        $reflection = null;
0 ignored issues
show
Unused Code introduced by
The assignment to $reflection is dead and can be removed.
Loading history...
27
28
        try {
29 4
            $reflection = new ReflectionClass(static::class);
30
        } catch (ReflectionException $e) {
31
            // Do something.
32
        }
33
34 4
        if (null !== $reflection) {
35 4
            yield from $reflection->getConstants();
36
        }
37 2
    }
38
39 4
    final public static function has(string $key): bool
40
    {
41 4
        foreach (static::getIterator() as $keyConst => $valueConst) {
42 4
            if ($key !== $keyConst) {
43 4
                continue;
44
            }
45
46 4
            return true;
47
        }
48
49 2
        return false;
50
    }
51
52
    /**
53
     * @param int|string $value
54
     */
55 4
    final public static function isValid($value): bool
56
    {
57 4
        foreach (static::getIterator() as $valueConst) {
58 4
            if ($value !== $valueConst) {
59 4
                continue;
60
            }
61
62 4
            return true;
63
        }
64
65 1
        return false;
66
    }
67
68
    /**
69
     * @param int|string $value
70
     *
71
     * @throws Exception
72
     */
73 3
    final public static function key($value): string
74
    {
75 3
        foreach (static::getIterator() as $keyConst => $valueConst) {
76 3
            if ($value === $valueConst) {
77 3
                return $keyConst;
78
            }
79
        }
80
81 1
        throw new Exception('No such key.');
82
    }
83
84
    /**
85
     * @return int|string
86
     */
87 4
    final public static function value(string $value)
88
    {
89 4
        return constant('static::' . $value);
90
    }
91
}
92