Completed
Pull Request — master (#96)
by Maxime
01:37
created

AutoDiscoveredValuesTrait::getDiscoveredClasses()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 4

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 4
rs 10
c 0
b 0
f 0
cc 1
nc 1
nop 0
1
<?php
2
3
/*
4
 * This file is part of the "elao/enum" package.
5
 *
6
 * Copyright (C) Elao
7
 *
8
 * @author Elao <[email protected]>
9
 */
10
11
namespace Elao\Enum;
12
13
use Elao\Enum\Exception\LogicException;
14
15
/**
16
 * Auto-discover enumerated values from public constants.
17
 */
18
trait AutoDiscoveredValuesTrait
19
{
20
    /** @internal */
21
    private static $guessedValues = [];
22
23
    /** @internal */
24
    private static $guessedReadables = [];
25
26
    /**
27
     * @see EnumInterface::values()
28
     *
29
     * @return int[]|string[]
30
     */
31
    public static function values(): array
32
    {
33
        return self::autodiscoveredValues();
34
    }
35
36
    /**
37
     * @see ChoiceEnumTrait::choices()
38
     */
39
    protected static function choices(): array
40
    {
41
        if (!\in_array(ChoiceEnumTrait::class, class_uses(self::class, false), true)) {
42
            throw new LogicException(sprintf(
43
                'Method "%s" is only meant to be used when using the "%s" trait which is not used in "%s"',
44
                __METHOD__,
45
                ChoiceEnumTrait::class,
46
                static::class
47
            ));
48
        }
49
50
        return self::autodiscoveredReadables();
51
    }
52
53
    /**
54
     * @internal
55
     */
56
    private static function autodiscoveredValues(): array
57
    {
58
        $enumType = static::class;
59
        $discoveredClasses = array_reverse(static::getDiscoveredClasses());
60
61
        if (!isset(self::$guessedValues[$enumType])) {
62
            self::$guessedValues[$enumType] = [];
63
            foreach ($discoveredClasses as $discoveredClass) {
64
                $r = new \ReflectionClass($discoveredClass);
65
                $values = $r->getConstants();
66
67
                if (PHP_VERSION_ID >= 70100) {
68
                    $values = array_filter($values, static function (string $k) use ($r) {
69
                        return $r->getReflectionConstant($k)->isPublic();
70
                    }, ARRAY_FILTER_USE_KEY);
71
                }
72
73
                if (is_a($enumType, FlaggedEnum::class, true)) {
74
                    $values = array_filter($values, static function ($v) {
75
                        return \is_int($v) && 0 === ($v & $v - 1) && $v > 0;
76
                    });
77
                } else {
78
                    $values = array_filter($values, static function ($v) {
79
                        return \is_int($v) || \is_string($v);
80
                    });
81
                }
82
83
                self::$guessedValues[$enumType] = array_merge(self::$guessedValues[$enumType], array_values($values));
84
            }
85
86
            self::$guessedValues[$enumType] = array_unique(self::$guessedValues[$enumType]);
87
        }
88
89
        return self::$guessedValues[$enumType];
90
    }
91
92
    /**
93
     * @internal
94
     */
95
    private static function autodiscoveredReadables(): array
96
    {
97
        $enumType = static::class;
98
        $discoveredClasses = array_reverse(static::getDiscoveredClasses());
99
        $values = self::autodiscoveredValues();
100
101
        if (!isset(self::$guessedReadables[$enumType])) {
102
            foreach ($discoveredClasses as $discoveredClass) {
103
                $constants = (new \ReflectionClass($discoveredClass))->getConstants();
104 View Code Duplication
                foreach ($values as $value) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
105
                    if (false !== $constantName = array_search($value, $constants, true)) {
106
                        self::$guessedReadables[$enumType][$value] = ucfirst(strtolower(str_replace('_', ' ', $constantName)));
107
                    }
108
                }
109
            }
110
        }
111
112
        return self::$guessedReadables[$enumType];
113
    }
114
115
    /**
116
     * Override this method in order to discover values from public int/string constants in other classes.
117
     * E.g: `return [static::class, DumbEnum::class];` to discover values from DumbEnum as well.
118
     *
119
     * @return string[]
120
     */
121
    protected static function getDiscoveredClasses(): array
122
    {
123
        return [static::class];
124
    }
125
}
126