Passed
Push — master ( 8634b9...ba407f )
by Chris
14:07
created

Enum::parseValue()   B

Complexity

Conditions 5
Paths 3

Size

Total Lines 10
Code Lines 5

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 30

Importance

Changes 0
Metric Value
cc 5
eloc 5
nc 3
nop 2
dl 0
loc 10
ccs 0
cts 9
cp 0
crap 30
rs 8.8571
c 0
b 0
f 0
1
<?php declare(strict_types=1);
2
3
namespace DaveRandom\LibLifxLan;
4
5
abstract class Enum
6
{
7
    private static $constantCache = [];
8
9
    /**
10
     * Get a map of member names to values for the specified class name
11
     *
12
     * @param string $className
13
     * @return array
14
     */
15
    private static function getClassConstants(string $className): array
16
    {
17
        return self::$constantCache[$className]
18
            ?? self::$constantCache[$className] = (new \ReflectionClass($className))->getConstants();
19
    }
20
21
    /**
22
     * Get the name of the first member with the specified value
23
     *
24
     * @param mixed $searchValue
25
     * @param bool $looseComparison
26
     * @return string
27
     */
28
    final public static function parseValue($searchValue, bool $looseComparison = false): string
29
    {
30
        foreach (self::getClassConstants(static::class) as $name => $memberValue) {
31
            if ($searchValue === $memberValue || ($looseComparison && $searchValue == $memberValue)) {
32
                return $name;
33
            }
34
        }
35
36
        throw new \InvalidArgumentException('Unknown enumeration value: ' . $searchValue);
37
    }
38
39
    /**
40
     * Get the value of the member with the specified name
41
     *
42
     * @param string $searchName
43
     * @param bool $caseInsensitive
44
     * @return mixed
45
     */
46
    final public static function parseName(string $searchName, bool $caseInsensitive = false)
47
    {
48
        $constants = self::getClassConstants(static::class);
49
50
        if (isset($constants[$searchName])) {
51
            return $constants[$searchName];
52
        }
53
54
        if ($caseInsensitive) {
55
            foreach ($constants as $memberName => $value) {
56
                if (\strcasecmp($searchName, $memberName) === 0) {
57
                    return $value;
58
                }
59
            }
60
        }
61
62
        throw new \InvalidArgumentException('Unknown enumeration member: ' . $searchName);
63
    }
64
65
    final public static function toArray(): array
66
    {
67
        return self::getClassConstants(static::class);
68
    }
69
70
    final protected function __construct() { }
71
}
72