AbstractEnum   A
last analyzed

Complexity

Total Complexity 7

Size/Duplication

Total Lines 67
Duplicated Lines 0 %

Coupling/Cohesion

Components 0
Dependencies 0

Importance

Changes 0
Metric Value
wmc 7
lcom 0
cbo 0
dl 0
loc 67
rs 10
c 0
b 0
f 0

4 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 4 1
A __toString() 0 4 1
A __callStatic() 0 9 2
A all() 0 12 3
1
<?php
2
namespace SubjectivePHP\Spl\Types;
3
4
/**
5
 * Defines the base AbstractEnum class.
6
 */
7
abstract class AbstractEnum
8
{
9
    /**
10
     * String value of enum.
11
     *
12
     * @var string
13
     */
14
    private $value;
15
16
    /**
17
     * Construct a new AbstractEnum object.
18
     *
19
     * @param string $value The string value of the enum.
20
     */
21
    final private function __construct(string $value)
22
    {
23
        $this->value = strtolower($value);
24
    }
25
26
    /**
27
     * Returns the string value of the enum.
28
     *
29
     * @return string
30
     */
31
    final public function __toString() : string
32
    {
33
        return $this->value;
34
    }
35
36
    /**
37
     * Returns a new instance of the AbstractEnum class.
38
     *
39
     * @param string $name      The string value of the enum.
40
     * @param array  $arguments Unused.
41
     *
42
     * @return AbstractEnum
43
     *
44
     * @throws \UnexpectedValueException Thrown if $name is not a defined Enum constant.
45
     */
46
    final public static function __callStatic(string $name, /** @scrutinizer ignore-unused */array $arguments) : self
47
    {
48
        $class = get_called_class();
49
        if (defined("{$class}::" . strtoupper($name))) {
50
            return new static($name);
51
        }
52
53
        throw new \UnexpectedValueException("'{$name}' is not a valid {$class}");
54
    }
55
56
    /**
57
     * Returns an array of all enums.
58
     *
59
     * @return AbstractEnum[]
60
     */
61
    final public static function all() : array
62
    {
63
        static $all = null;
64
65
        if ($all === null) {
66
            foreach ((new \ReflectionClass(get_called_class()))->getConstants() as $constant) {
67
                $all[] = new static($constant);
68
            }
69
        }
70
71
        return $all;
72
    }
73
}
74