Enum   A
last analyzed

Complexity

Total Complexity 7

Size/Duplication

Total Lines 63
Duplicated Lines 0 %

Test Coverage

Coverage 100%

Importance

Changes 3
Bugs 0 Features 1
Metric Value
wmc 7
eloc 24
c 3
b 0
f 1
dl 0
loc 63
ccs 25
cts 25
cp 1
rs 10

5 Methods

Rating   Name   Duplication   Size   Complexity  
A validate() 0 17 3
A __construct() 0 4 1
A __toString() 0 3 1
A getConstants() 0 4 1
A __debugInfo() 0 5 1
1
<?php
2
3
declare(strict_types=1);
4
5
namespace Teabugger\Enum;
6
7
use ReflectionClass;
8
use ReflectionException;
9
10
abstract class Enum
11
{
12
    private string $value;
13
14
    /**
15
     * Enum constructor.
16
     * @param string $value
17
     * @throws EnumException
18
     */
19 5
    public function __construct(string $value)
20
    {
21 5
        $this->validate($value);
22 3
        $this->value = $value;
23 3
    }
24
25
    /**
26
     * @param string $value
27
     * @throws EnumException
28
     */
29 5
    private function validate(string $value): void
30
    {
31 5
        $constants = $this->getConstants();
32 5
        $valid = in_array($value, $constants, true);
33 5
        if (!$valid) {
34 2
            $class = get_class($this);
35 2
            if (!empty($constants)) {
36 1
                $implodedConstants = implode(PHP_EOL, $constants);
37
                $message = <<< EOD
38 1
                Invalid ENUM option for class {$class}.
39 1
                Given: {$value}. Expected one of:
40 1
                $implodedConstants
41
                EOD;
42
            } else {
43 1
                $message = "Invalid ENUM: missing options. Class: {$class}.";
44
            }
45 2
            throw new EnumException($message);
46
        }
47 3
    }
48
49
    /**
50
     * @return string[]
51
     * @throws ReflectionException
52
     */
53 5
    private function getConstants(): array
54
    {
55 5
        $class = new ReflectionClass($this);
56 5
        return $class->getConstants();
57
    }
58
59 1
    public function __toString(): string
60
    {
61 1
        return $this->value;
62
    }
63
64
    /**
65
     * @return mixed[]
66
     * @throws ReflectionException
67
     */
68 1
    public function __debugInfo(): array
69
    {
70
        return [
71 1
            'value' => $this->value,
72 1
            'options' => $this->getConstants(),
73
        ];
74
    }
75
}
76