Passed
Push — main ( 8e5304...ba1bb8 )
by Pieter
04:56
created

StringEnumTrait::getLookupTable()   A

Complexity

Conditions 4
Paths 2

Size

Total Lines 13
Code Lines 8

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 4
eloc 8
c 0
b 0
f 0
nc 2
nop 0
dl 0
loc 13
rs 10
1
<?php
2
3
4
namespace Apie\ValueObjects;
5
6
use ReflectionClass;
7
8
trait StringEnumTrait
9
{
10
    use StringTrait;
11
12
    /**
13
     * @var string[]
14
     */
15
    private static $lookupTable;
16
17
    final protected function validValue(string $value): bool
18
    {
19
        $values = self::getLookupTable();
20
        return isset($values[$value]);
21
    }
22
23
    final protected function sanitizeValue(string $value): string
24
    {
25
        $values = self::getLookupTable();
26
        assert(isset($values[$value]));
27
        return $values[$value];
28
    }
29
30
    private static function getLookupTable(): array
31
    {
32
        if (!self::$lookupTable) {
0 ignored issues
show
Bug Best Practice introduced by
The expression self::lookupTable of type string[] is implicitly converted to a boolean; are you sure this is intended? If so, consider using empty($expr) instead to make it clear that you intend to check for an array without elements.

This check marks implicit conversions of arrays to boolean values in a comparison. While in PHP an empty array is considered to be equal (but not identical) to false, this is not always apparent.

Consider making the comparison explicit by using empty(..) or ! empty(...) instead.

Loading history...
33
            $values = self::getValidValues();
34
            self::$lookupTable = [];
35
            foreach ($values as $value) {
36
                self::$lookupTable[$value] = $value;
37
            }
38
            foreach ($values as $key => $value) {
39
                self::$lookupTable[$key] = $value;
40
            }
41
        }
42
        return self::$lookupTable;
43
    }
44
45
    final public static function getValidValues(): array
46
    {
47
        $reflectionClass = new ReflectionClass(__CLASS__);
48
        return $reflectionClass->getConstants();
49
    }
50
}
51