Enum::getConstants()   A
last analyzed

Complexity

Conditions 4
Paths 6

Size

Total Lines 18
Code Lines 10

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 4
eloc 10
c 1
b 0
f 0
nc 6
nop 0
dl 0
loc 18
rs 9.9332
1
<?php
2
3
declare(strict_types=1);
4
5
namespace Bugloos\QueryFilterBundle\Enum\Contract;
6
7
use InvalidArgumentException;
8
use ReflectionException;
9
use RuntimeException;
10
11
/**
12
 * Class Enum was developed by my dear friend Mojtaba Gheytasi <https://github.com/mojtaba-gheytasi>.
13
 *
14
 * @author Mojtaba Gheytasi <[email protected]>
15
 */
16
abstract class Enum
17
{
18
    private static ?array $constCacheArray = null;
19
20
    public static function all(): array
21
    {
22
        return array_values(self::getConstants());
23
    }
24
25
    public static function getKeys(): array
26
    {
27
        return array_keys(self::getConstants());
28
    }
29
30
    public static function getKey($value): string
31
    {
32
        $constants = self::getConstants();
33
34
        if (!\in_array($value, $constants, true)) {
35
            self::createInvalidArgumentException('key');
36
        }
37
38
        return array_search($value, $constants, true);
39
    }
40
41
    private static function getConstants(): array
42
    {
43
        if (null === self::$constCacheArray) {
44
            self::$constCacheArray = [];
45
        }
46
47
        $calledClass = static::class;
48
49
        if (!\array_key_exists($calledClass, self::$constCacheArray)) {
50
            try {
51
                $reflect = new \ReflectionClass($calledClass);
52
            } catch (ReflectionException $e) {
53
                throw new RuntimeException();
54
            }
55
            self::$constCacheArray[$calledClass] = $reflect->getConstants();
56
        }
57
58
        return self::$constCacheArray[$calledClass];
59
    }
60
61
    /**
62
     * @param string $target
63
     */
64
    public static function createInvalidArgumentException(
65
        string $target
66
    ): void {
67
        throw new InvalidArgumentException(
68
            sprintf('Invalid argument, %s not exists in %s', $target, static::class)
69
        );
70
    }
71
}
72