Completed
Pull Request — master (#35)
by Maxime
01:38
created

AutoDiscoveredValuesTrait   A

Complexity

Total Complexity 5

Size/Duplication

Total Lines 36
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 0

Importance

Changes 0
Metric Value
wmc 5
lcom 1
cbo 0
dl 0
loc 36
rs 10
c 0
b 0
f 0

1 Method

Rating   Name   Duplication   Size   Complexity  
B values() 0 25 5
1
<?php
2
3
/*
4
 * This file is part of the "elao/enum" package.
5
 *
6
 * Copyright (C) 2016 Elao
7
 *
8
 * @author Elao <[email protected]>
9
 */
10
11
namespace Elao\Enum;
12
13
trait AutoDiscoveredValuesTrait
14
{
15
    /** @var array */
16
    private static $guessedValues = [];
17
18
    /**
19
     * @see EnumInterface::values()
20
     *
21
     * @return int[]|string[]
22
     */
23
    public static function values(): array
24
    {
25
        $enumType = static::class;
26
27
        if (!isset(self::$guessedValues[$enumType])) {
28
            $r = new \ReflectionClass($enumType);
29
            $values = $r->getConstants();
30
31
            if (PHP_VERSION_ID >= 70100) {
32
                $values = array_filter($values, function ($k) use ($r) {
33
                    return $r->getReflectionConstant($k)->isPublic();
34
                }, ARRAY_FILTER_USE_KEY);
35
            }
36
37
            if (is_a($enumType, FlaggedEnum::class, true)) {
38
                $values = array_filter($values, function ($v) {
39
                    return 0 === ($v & $v - 1) && $v > 0;
40
                });
41
            }
42
43
            self::$guessedValues[$enumType] = array_values($values);
44
        }
45
46
        return self::$guessedValues[$enumType];
47
    }
48
}
49