Passed
Push — master ( 84bf0f...c60b29 )
by Marc
43s queued 16s
created

Enum::byName()   A

Complexity

Conditions 3
Paths 3

Size

Total Lines 17
Code Lines 9

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 10
CRAP Score 3

Importance

Changes 0
Metric Value
cc 3
eloc 9
nc 3
nop 1
dl 0
loc 17
ccs 10
cts 10
cp 1
crap 3
rs 9.9666
c 0
b 0
f 0
1
<?php
2
3
declare(strict_types=1);
4
5
namespace MabeEnum;
6
7
use ReflectionClass;
8
use InvalidArgumentException;
9
use LogicException;
10
11
/**
12
 * Abstract base enumeration class.
13
 *
14
 * @copyright 2019 Marc Bennewitz
15
 * @license http://github.com/marc-mabe/php-enum/blob/master/LICENSE.txt New BSD License
16
 * @link http://github.com/marc-mabe/php-enum for the canonical source repository
17
 */
18
abstract class Enum
19
{
20
    /**
21
     * The selected enumerator value
22
     *
23
     * @var null|bool|int|float|string|array
24
     */
25
    private $value;
0 ignored issues
show
Coding Style introduced by
Expected 1 blank line before member var; 0 found
Loading history...
26
27
    /**
28
     * The ordinal number of the enumerator
29
     *
30
     * @var null|int
31
     */
32
    private $ordinal;
33
34
    /**
35
     * A map of enumerator names and values by enumeration class
36
     *
37
     * @var array ["$class" => ["$name" => $value, ...], ...]
38
     */
39
    private static $constants = [];
40
41
    /**
42
     * A List of available enumerator names by enumeration class
43
     *
44
     * @var array ["$class" => ["$name0", ...], ...]
45
     */
46
    private static $names = [];
47
48
    /**
49
     * Already instantiated enumerators
50
     *
51
     * @var array ["$class" => ["$name" => $instance, ...], ...]
52
     */
53
    private static $instances = [];
54
55
    /**
56
     * Constructor
57
     *
58
     * @param null|bool|int|float|string|array $value   The value of the enumerator
59
     * @param int|null                         $ordinal The ordinal number of the enumerator
60
     */
61 45
    final private function __construct($value, $ordinal = null)
62
    {
63 45
        $this->value   = $value;
64 45
        $this->ordinal = $ordinal;
65 45
    }
66
67
    /**
68
     * Get the name of the enumerator
69
     *
70
     * @return string
71
     * @see getName()
72
     */
73 1
    public function __toString(): string
74
    {
75 1
        return $this->getName();
76
    }
77
78
    /**
79
     * @throws LogicException Enums are not cloneable
0 ignored issues
show
introduced by
@throws tag comment must end with a full stop
Loading history...
80
     *                        because instances are implemented as singletons
81
     */
0 ignored issues
show
introduced by
Missing @return tag in function comment
Loading history...
82 1
    final private function __clone()
83
    {
84 1
        throw new LogicException('Enums are not cloneable');
85
    }
86
87
    /**
88
     * @throws LogicException Enums are not serializable
0 ignored issues
show
introduced by
@throws tag comment must end with a full stop
Loading history...
89
     *                        because instances are implemented as singletons
90
     */
0 ignored issues
show
introduced by
Missing @return tag in function comment
Loading history...
91 1
    final public function __sleep()
92
    {
93 1
        throw new LogicException('Enums are not serializable');
94
    }
95
96
    /**
97
     * @throws LogicException Enums are not serializable
0 ignored issues
show
introduced by
@throws tag comment must end with a full stop
Loading history...
98
     *                        because instances are implemented as singletons
99
     */
0 ignored issues
show
introduced by
Missing @return tag in function comment
Loading history...
100 1
    final public function __wakeup()
101
    {
102 1
        throw new LogicException('Enums are not serializable');
103
    }
104
105
    /**
106
     * Get the value of the enumerator
107
     *
108
     * @return null|bool|int|float|string|array
109
     */
110 32
    final public function getValue()
111
    {
112 32
        return $this->value;
113
    }
114
115
    /**
116
     * Get the name of the enumerator
117
     *
118
     * @return string
119
     */
120 8
    final public function getName()
121
    {
122 8
        return self::$names[static::class][$this->ordinal ?? $this->getOrdinal()];
123
    }
124
125
    /**
126
     * Get the ordinal number of the enumerator
127
     *
128
     * @return int
129
     */
130 108
    final public function getOrdinal()
131
    {
132 108
        if ($this->ordinal === null) {
133 22
            $ordinal   = 0;
134 22
            $value     = $this->value;
135 22
            $constants = self::$constants[static::class] ?? static::getConstants();
136 22
            foreach ($constants as $constValue) {
137 22
                if ($value === $constValue) {
138 22
                    break;
139
                }
140 17
                ++$ordinal;
141
            }
142
143 22
            $this->ordinal = $ordinal;
144
        }
145
146 108
        return $this->ordinal;
147
    }
148
149
    /**
150
     * Compare this enumerator against another and check if it's the same.
151
     *
152
     * @param static|null|bool|int|float|string|array $enumerator An enumerator object or value
153
     * @return bool
154
     */
155 2
    final public function is($enumerator)
156
    {
157 2
        return $this === $enumerator || $this->value === $enumerator
158
159
            // The following additional conditions are required only because of the issue of serializable singletons
160 2
            || ($enumerator instanceof static
161 2
                && \get_class($enumerator) === static::class
162 2
                && $enumerator->value === $this->value
163
            );
164
    }
165
166
    /**
167
     * Get an enumerator instance of the given enumerator value or instance
168
     *
169
     * @param static|null|bool|int|float|string|array $enumerator An enumerator object or value
170
     * @return static
171
     * @throws InvalidArgumentException On an unknown or invalid value
0 ignored issues
show
introduced by
@throws tag comment must end with a full stop
Loading history...
172
     * @throws LogicException           On ambiguous constant values
0 ignored issues
show
introduced by
@throws tag comment must end with a full stop
Loading history...
173
     */
174 119
    final public static function get($enumerator)
175
    {
176 119
        if ($enumerator instanceof static && \get_class($enumerator) === static::class) {
177 35
            return $enumerator;
178
        }
179
180 94
        return static::byValue($enumerator);
181
    }
182
183
    /**
184
     * Get an enumerator instance by the given value
185
     *
186
     * @param null|bool|int|float|string|array $value Enumerator value
187
     * @return static
188
     * @throws InvalidArgumentException On an unknown or invalid value
0 ignored issues
show
introduced by
@throws tag comment must end with a full stop
Loading history...
189
     * @throws LogicException           On ambiguous constant values
0 ignored issues
show
introduced by
@throws tag comment must end with a full stop
Loading history...
190
     */
191 94
    final public static function byValue($value)
192
    {
193 94
        $constants = self::$constants[static::class] ?? static::getConstants();
194
195 92
        $name = \array_search($value, $constants, true);
196 92
        if ($name === false) {
197 12
            throw new InvalidArgumentException(sprintf(
198 12
                'Unknown value %s for enumeration %s',
199 12
                \is_scalar($value)
200 7
                    ? \var_export($value, true)
201 12
                    : 'of type ' . (\is_object($value) ? \get_class($value) : \gettype($value)),
202 12
                static::class
203
            ));
204
        }
205
206 83
        return self::$instances[static::class][$name]
207 83
            ?? self::$instances[static::class][$name] = new static($constants[$name]);
0 ignored issues
show
Coding Style introduced by
Expected 1 space before "??"; newline found
Loading history...
208
    }
209
210
    /**
211
     * Get an enumerator instance by the given name
212
     *
213
     * @param string $name The name of the enumerator
214
     * @return static
215
     * @throws InvalidArgumentException On an invalid or unknown name
0 ignored issues
show
introduced by
@throws tag comment must end with a full stop
Loading history...
216
     * @throws LogicException           On ambiguous values
0 ignored issues
show
introduced by
@throws tag comment must end with a full stop
Loading history...
217
     */
218 59
    final public static function byName(string $name)
219
    {
220 59
        if (isset(self::$instances[static::class][$name])) {
221 44
            return self::$instances[static::class][$name];
222
        }
223
224 19
        $const = static::class . "::{$name}";
0 ignored issues
show
Coding Style Best Practice introduced by
As per coding-style, please use concatenation or sprintf for the variable $name instead of interpolation.

It is generally a best practice as it is often more readable to use concatenation instead of interpolation for variables inside strings.

// Instead of
$x = "foo $bar $baz";

// Better use either
$x = "foo " . $bar . " " . $baz;
$x = sprintf("foo %s %s", $bar, $baz);
Loading history...
225 19
        if (!\defined($const)) {
226 1
            throw new InvalidArgumentException("{$const} not defined");
0 ignored issues
show
Coding Style Best Practice introduced by
As per coding-style, please use concatenation or sprintf for the variable $const instead of interpolation.

It is generally a best practice as it is often more readable to use concatenation instead of interpolation for variables inside strings.

// Instead of
$x = "foo $bar $baz";

// Better use either
$x = "foo " . $bar . " " . $baz;
$x = sprintf("foo %s %s", $bar, $baz);
Loading history...
227
        }
228
229 18
        assert(
230 18
            self::noAmbiguousValues(static::getConstants()),
231 17
            'Ambiguous enumerator values detected for ' . static::class
232
        );
233
234 17
        return self::$instances[static::class][$name] = new static(\constant($const));
235
    }
236
237
    /**
238
     * Get an enumeration instance by the given ordinal number
239
     *
240
     * @param int $ordinal The ordinal number of the enumerator
241
     * @return static
242
     * @throws InvalidArgumentException On an invalid ordinal number
0 ignored issues
show
introduced by
@throws tag comment must end with a full stop
Loading history...
243
     * @throws LogicException           On ambiguous values
0 ignored issues
show
introduced by
@throws tag comment must end with a full stop
Loading history...
244
     */
245 39
    final public static function byOrdinal(int $ordinal)
246
    {
247 39
        $constants = self::$constants[static::class] ?? static::getConstants();
248
249 39
        if (!isset(self::$names[static::class][$ordinal])) {
250 1
            throw new InvalidArgumentException(\sprintf(
251 1
                'Invalid ordinal number %s, must between 0 and %s',
252 1
                $ordinal,
253 1
                \count(self::$names[static::class]) - 1
254
            ));
255
        }
256
257 38
        $name = self::$names[static::class][$ordinal];
258 38
        return self::$instances[static::class][$name]
259 38
            ?? self::$instances[static::class][$name] = new static($constants[$name], $ordinal);
0 ignored issues
show
Coding Style introduced by
Expected 1 space before "??"; newline found
Loading history...
260
    }
261
262
    /**
263
     * Get a list of enumerator instances ordered by ordinal number
264
     *
265
     * @return static[]
266
     */
267 17
    final public static function getEnumerators()
268
    {
269 17
        if (!isset(self::$names[static::class])) {
270 1
            static::getConstants();
271
        }
272 17
        return \array_map([static::class, 'byName'], self::$names[static::class]);
273
    }
274
275
    /**
276
     * Get a list of enumerator values ordered by ordinal number
277
     *
278
     * @return mixed[]
279
     */
280 7
    final public static function getValues()
281
    {
282 7
        return \array_values(self::$constants[static::class] ?? static::getConstants());
283
    }
284
285
    /**
286
     * Get a list of enumerator names ordered by ordinal number
287
     *
288
     * @return string[]
289
     */
290 3
    final public static function getNames()
291
    {
292 3
        if (!isset(self::$names[static::class])) {
293 1
            static::getConstants();
294
        }
295 3
        return self::$names[static::class];
296
    }
297
    
298
    /**
299
     * Get a list of enumerator ordinal numbers
300
     *
301
     * @return int[]
302
     */
303 1
    final public static function getOrdinals()
304
    {
305 1
        $count = \count(self::$constants[static::class] ?? static::getConstants());
306 1
        return $count ? \range(0, $count - 1) : [];
307
    }
308
309
    /**
310
     * Get all available constants of the called class
311
     *
312
     * @return array
313
     * @throws LogicException On ambiguous constant values
0 ignored issues
show
introduced by
@throws tag comment must end with a full stop
Loading history...
314
     */
315 151
    final public static function getConstants()
316
    {
317 151
        if (isset(self::$constants[static::class])) {
318 115
            return self::$constants[static::class];
319
        }
320
321 51
        $reflection = new ReflectionClass(static::class);
322 51
        $constants  = [];
323
324
        do {
325 51
            $scopeConstants = [];
326
            // Enumerators must be defined as public class constants
327 51
            foreach ($reflection->getReflectionConstants() as $reflConstant) {
328 50
                if ($reflConstant->isPublic()) {
329 50
                    $scopeConstants[ $reflConstant->getName() ] = $reflConstant->getValue();
330
                }
331
            }
332
333 51
            $constants = $scopeConstants + $constants;
334 51
        } while (($reflection = $reflection->getParentClass()) && $reflection->name !== __CLASS__);
335
336 51
        assert(
337 51
            self::noAmbiguousValues($constants),
338 51
            'Ambiguous enumerator values detected for ' . static::class
339
        );
340
341 48
        self::$names[static::class] = \array_keys($constants);
342 48
        return self::$constants[static::class] = $constants;
343
    }
344
345
    /**
346
     * Test that the given constants does not contain ambiguous values
347
     * @param array $constants
0 ignored issues
show
Documentation introduced by
Missing parameter comment
Loading history...
348
     * @return bool
349
     */
350 53
    private static function noAmbiguousValues($constants)
0 ignored issues
show
introduced by
Type hint "array" missing for $constants
Loading history...
351
    {
352 53
        foreach ($constants as $value) {
353 52
            $names = \array_keys($constants, $value, true);
354 52
            if (\count($names) > 1) {
355 5
                return false;
356
            }
357
        }
358
359 48
        return true;
360
    }
361
362
    /**
363
     * Test if the given enumerator is part of this enumeration
364
     * 
365
     * @param static|null|bool|int|float|string|array $enumerator
0 ignored issues
show
Documentation introduced by
Missing parameter comment
Loading history...
366
     * @return bool
367
     */
368 1
    final public static function has($enumerator)
369
    {
370 1
        return ($enumerator instanceof static && \get_class($enumerator) === static::class)
371 1
            || static::hasValue($enumerator);
372
    }
373
374
    /**
375
     * Test if the given enumerator value is part of this enumeration
376
     *
377
     * @param null|bool|int|float|string|array $value
0 ignored issues
show
Documentation introduced by
Missing parameter comment
Loading history...
378
     * @return bool
379
     */
380 2
    final public static function hasValue($value)
381
    {
382 2
        return \in_array($value, self::$constants[static::class] ?? static::getConstants(), true);
383
    }
384
385
    /**
386
     * Test if the given enumerator name is part of this enumeration
387
     *
388
     * @param string $name
0 ignored issues
show
Documentation introduced by
Missing parameter comment
Loading history...
389
     * @return bool
390
     */
391 1
    final public static function hasName(string $name)
392
    {
393 1
        return \defined("static::{$name}");
0 ignored issues
show
Coding Style Best Practice introduced by
As per coding-style, please use concatenation or sprintf for the variable $name instead of interpolation.

It is generally a best practice as it is often more readable to use concatenation instead of interpolation for variables inside strings.

// Instead of
$x = "foo $bar $baz";

// Better use either
$x = "foo " . $bar . " " . $baz;
$x = sprintf("foo %s %s", $bar, $baz);
Loading history...
394
    }
395
396
    /**
397
     * Get an enumerator instance by the given name.
398
     *
399
     * This will be called automatically on calling a method
400
     * with the same name of a defined enumerator.
401
     *
402
     * @param string $method The name of the enumerator (called as method)
403
     * @param array  $args   There should be no arguments
404
     * @return static
405
     * @throws InvalidArgumentException On an invalid or unknown name
0 ignored issues
show
introduced by
@throws tag comment must end with a full stop
Loading history...
406
     * @throws LogicException           On ambiguous constant values
0 ignored issues
show
introduced by
@throws tag comment must end with a full stop
Loading history...
407
     */
408 39
    final public static function __callStatic(string $method, array $args)
409
    {
410 39
        return static::byName($method);
411
    }
412
}
413