Completed
Push — master ( 69c3c3...40bd0a )
by Chris
02:41
created

Enum   A

Complexity

Total Complexity 13

Size/Duplication

Total Lines 66
Duplicated Lines 0 %

Test Coverage

Coverage 100%

Importance

Changes 0
Metric Value
dl 0
loc 66
ccs 19
cts 19
cp 1
rs 10
c 0
b 0
f 0
wmc 13

5 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 1 1
B parseValue() 0 9 5
A toArray() 0 3 1
A getClassConstants() 0 4 1
B parseName() 0 17 5
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 9
    private static function getClassConstants(string $className): array
16
    {
17 9
        return self::$constantCache[$className]
18 9
            ?? 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 4
    final public static function parseValue($searchValue, bool $looseComparison = false): string
29
    {
30 4
        foreach (self::getClassConstants(static::class) as $name => $memberValue) {
31 4
            if ($searchValue === $memberValue || ($looseComparison && $searchValue == $memberValue)) {
32 4
                return $name;
33
            }
34
        }
35
36 2
        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 4
    final public static function parseName(string $searchName, bool $caseInsensitive = false)
47
    {
48 4
        $constants = self::getClassConstants(static::class);
49
50 4
        if (isset($constants[$searchName])) {
51 1
            return $constants[$searchName];
52
        }
53
54 3
        if ($caseInsensitive) {
55 1
            foreach ($constants as $memberName => $value) {
56 1
                if (\strcasecmp($searchName, $memberName) === 0) {
57 1
                    return $value;
58
                }
59
            }
60
        }
61
62 2
        throw new \InvalidArgumentException('Unknown enumeration member: ' . $searchName);
63
    }
64
65 1
    final public static function toArray(): array
66
    {
67 1
        return self::getClassConstants(static::class);
68
    }
69
70
    final protected function __construct() { }
71
}
72