SplEnum::__construct()   A
last analyzed

Complexity

Conditions 2
Paths 2

Size

Total Lines 10
Code Lines 4

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 5
CRAP Score 2

Importance

Changes 1
Bugs 0 Features 1
Metric Value
cc 2
eloc 4
c 1
b 0
f 1
nc 2
nop 2
dl 0
loc 10
ccs 5
cts 5
cp 1
crap 2
rs 10
1
<?php
2
3
/**
4
 * Part of SplTypes package.
5
 *
6
 * (c) Adrien Loyant <[email protected]>
7
 *
8
 * For the full copyright and license information, please view the LICENSE
9
 * file that was distributed with this source code.
10
 */
11
12
declare(strict_types=1);
13
14
namespace Ducks\Component\SplTypes;
15
16
/**
17
 * SplEnum gives the ability to emulate and create enumeration objects natively in PHP.
18
 *
19
 * @template T
20
 * @extends SplType<T>
21
 *
22
 * @psalm-api
23
 *
24
 * @psalm-suppress MissingDependency
25
 * @psalm-suppress UndefinedClass
26
 */
27
abstract class SplEnum extends SplType implements SplEnumerable
28
{
29
    use SplEnumTrait;
30
    /** @use SplEnumAccessorsTrait<T> */
31
    use SplEnumAccessorsTrait;
32
33
    /**
34
     * {@inheritdoc}
35
     *
36
     * @param mixed $initial_value
37
     * @param bool $strict
38
     *
39
     * @phpstan-param T|null $initial_value
40
     * @phpstan-param bool $strict
41
     *
42
     * @throws \UnexpectedValueException if incompatible type is given.
43
     *
44
     * @SuppressWarnings(PHPMD.CamelCaseParameterName)
45
     * @SuppressWarnings(PHPMD.CamelCaseVariableName)
46
     */
47 10
    public function __construct($initial_value = self::__default, bool $strict = true)
48
    {
49
        /** @var T $initial_value */
50 10
        $initial_value ??= static::__default;
51
52 10
        if (!\in_array($initial_value, $this->getConstList(), $strict)) {
53 1
            throw new \UnexpectedValueException('Cannot instantiate, Value not a const in enum ' . __CLASS__);
54
        }
55
56 9
        parent::__construct($initial_value);
57
    }
58
59
    /**
60
     * Returns all consts (possible values) as an array.
61
     *
62
     * @param bool $include_default Whether to include __default property.
63
     *
64
     * @return mixed[]
65
     *
66
     * @SuppressWarnings(PHPMD.CamelCaseParameterName)
67
     * @SuppressWarnings(PHPMD.CamelCaseVariableName)
68
     */
69 10
    final public function getConstList(bool $include_default = false)
70
    {
71 10
        $class = new \ReflectionClass($this);
72 10
        $constants = $class->getConstants();
73 10
        if (!$include_default) {
74 10
            unset($constants['__default']);
75
        }
76
77 10
        return $constants;
78
    }
79
}
80