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

Enum   A

Complexity

Total Complexity 13

Size/Duplication

Total Lines 67
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 0

Test Coverage

Coverage 0%

Importance

Changes 0
Metric Value
dl 0
loc 67
ccs 0
cts 33
cp 0
rs 10
c 0
b 0
f 0
wmc 13
lcom 1
cbo 0

5 Methods

Rating   Name   Duplication   Size   Complexity  
A getClassConstants() 0 5 1
B parseValue() 0 10 5
B parseName() 0 18 5
A toArray() 0 4 1
A __construct() 0 1 1
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