AbstractEnum   A
last analyzed

Complexity

Total Complexity 4

Size/Duplication

Total Lines 29
Duplicated Lines 0 %

Importance

Changes 0
Metric Value
eloc 8
dl 0
loc 29
rs 10
c 0
b 0
f 0
wmc 4

2 Methods

Rating   Name   Duplication   Size   Complexity  
A validate() 0 10 3
A getAvailableValues() 0 5 1
1
<?php
2
3
namespace App\Enum;
4
5
use InvalidArgumentException;
6
use ReflectionClass;
7
8
abstract class AbstractEnum
9
{
10
    /**
11
     * @param string|null $value
12
     * @param bool        $allowNull
13
     *
14
     * @throws InvalidArgumentException
15
     */
16
    public static function validate(?string $value, bool $allowNull = false): void
17
    {
18
        $availableValues = static::getAvailableValues();
19
20
        if ($allowNull) {
21
            $availableValues[] = null;
22
        }
23
24
        if (!in_array($value, $availableValues, true)) {
25
            throw new InvalidArgumentException(sprintf('Invalid value "%s". Available values are: %s', $value, implode(', ', $availableValues)));
26
        }
27
    }
28
29
    /**
30
     * @return string[]
31
     */
32
    public static function getAvailableValues(): array
33
    {
34
        $rf = new ReflectionClass(static::class);
35
36
        return array_values($rf->getConstants());
37
    }
38
}
39