Passed
Push — master ( 57b875...15d7d3 )
by Zachary
02:20
created

AbstractEnum   A

Complexity

Total Complexity 7

Size/Duplication

Total Lines 81
Duplicated Lines 0 %

Importance

Changes 0
Metric Value
eloc 18
dl 0
loc 81
rs 10
c 0
b 0
f 0
wmc 7

6 Methods

Rating   Name   Duplication   Size   Complexity  
A getConstantName() 0 3 1
A is() 0 3 1
A __construct() 0 11 2
A getValue() 0 3 1
A getDisplayName() 0 6 1
A __toString() 0 3 1
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 $generator;
18
19
    /**
20
     * @var string
21
     */
22
    private $constantName;
23
24
    /**
25
     * @var mixed
26
     */
27
    private $value;
28
29
30
    /**
31
     * AbstractEnum constructor.
32
     * @param mixed $value
33
     * @throws Exception\EnumException
34
     * @throws Exception\MissingValueException
35
     * @throws InvalidValueException
36
     */
37
    public function __construct($value)
38
    {
39
        $this->generator = GeneratorFactory::create();
40
        $meta = $this->generator->get($this);
41
42
        if (!$meta->isValid($value)) {
43
            throw new InvalidValueException($value);
44
        }
45
46
        $this->constantName = $meta->getConstantName($value);
47
        $this->value        = $value;
48
    }
49
50
    /**
51
     * @return string
52
     */
53
    public function getConstantName(): string
54
    {
55
        return $this->constantName;
56
    }
57
58
    /**
59
     * @return mixed
60
     */
61
    public function getValue()
62
    {
63
        return $this->value;
64
    }
65
66
    /**
67
     * @return string
68
     */
69
    public function getDisplayName(): string
70
    {
71
        return mb_convert_case(
72
            strtolower(str_replace('_', ' ', $this->constantName)),
73
            MB_CASE_TITLE,
74
            'UTF-8'
75
        );
76
    }
77
78
    /**
79
     * @param mixed $value
80
     * @return bool
81
     */
82
    public function is($value): bool
83
    {
84
        return $value === $this->getValue();
85
    }
86
87
    /**
88
     * @return string
89
     */
90
    public function __toString(): string
91
    {
92
        return strval($this->getValue());
93
    }
94
}
95