Completed
Push — master ( 15d7d3...76d300 )
by Zachary
01:42
created

AbstractEnum::__construct()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 11
Code Lines 6

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 2
eloc 6
nc 2
nop 1
dl 0
loc 11
rs 10
c 0
b 0
f 0
1
<?php
2
3
namespace ZingleCom\Enum;
4
5
use ZingleCom\Enum\Exception\InvalidValueException;
6
use ZingleCom\Enum\Meta\GeneratorFactory;
7
use ZingleCom\Enum\Meta\GeneratorInterface;
8
9
/**
10
 * Class AbstractEnum
11
 */
12
abstract class AbstractEnum implements EnumInterface
13
{
14
    /**
15
     * @var GeneratorInterface
16
     */
17
    private static $generator;
18
19
    /**
20
     * @var MetaInterface
21
     */
22
    private static $meta;
23
24
    /**
25
     * @var string
26
     */
27
    private $constantName;
28
29
    /**
30
     * @var mixed
31
     */
32
    private $value;
33
34
35
    /**
36
     * AbstractEnum constructor.
37
     * @param mixed $value
38
     * @throws Exception\EnumException
39
     * @throws Exception\MissingValueException
40
     * @throws InvalidValueException
41
     */
42
    public function __construct($value)
43
    {
44
        self::$generator = GeneratorFactory::create();
45
        self::$meta      = self::$generator->get($this);
46
47
        if (!self::$meta->isValid($value)) {
48
            throw new InvalidValueException($value);
49
        }
50
51
        $this->constantName = self::$meta->getConstantName($value);
52
        $this->value        = $value;
53
    }
54
55
    /**
56
     * @return string
57
     */
58
    public function getConstantName(): string
59
    {
60
        return $this->constantName;
61
    }
62
63
    /**
64
     * @return mixed
65
     */
66
    public function getValue()
67
    {
68
        return $this->value;
69
    }
70
71
    /**
72
     * @return string
73
     */
74
    public function getDisplayName(): string
75
    {
76
        return mb_convert_case(
77
            strtolower(str_replace('_', ' ', $this->constantName)),
78
            MB_CASE_TITLE,
79
            'UTF-8'
80
        );
81
    }
82
83
    /**
84
     * @param mixed $value
85
     * @return bool
86
     */
87
    public function is($value): bool
88
    {
89
        return $value === $this->getValue();
90
    }
91
92
    /**
93
     * @return string
94
     */
95
    public function __toString(): string
96
    {
97
        return strval($this->getValue());
98
    }
99
100
    /**
101
     * Makes this compatible with Symfony
102
     * 
103
     * @return array
104
     */
105
    public static function getOptions(): array 
106
    {
107
        return array_flip(self::$meta->getConstants()->toArray());
0 ignored issues
show
Bug Best Practice introduced by
The expression return array_flip(self::...Constants()->toArray()) could return the type null which is incompatible with the type-hinted return array. Consider adding an additional type-check to rule them out.
Loading history...
108
    }
109
}
110