Passed
Pull Request — main (#8)
by Alex
03:11 queued 01:35
created

Enum::value()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 3
Code Lines 1

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 2

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 1
eloc 1
c 1
b 0
f 0
nc 1
nop 0
dl 0
loc 3
rs 10
ccs 0
cts 2
cp 0
crap 2
1
<?php
2
3
namespace StraTDeS\VO\Single;
4
5
abstract class Enum
6
{
7
    protected $value;
8
9 6
    private function __construct($value)
10
    {
11 6
        $this->checkValueIsValid($value);
12 5
        $this->value = $value;
13 5
    }
14
15
    /**
16
     * @param $value
17
     * @return static
18
     */
19 6
    public static function fromValue($value)
20
    {
21 6
        return new static($value);
22
    }
23
24
    /**
25
     * Returns value.
26
     *
27
     * Override this method to strict type your Enum.
28
     *
29
     * @return mixed
30
     */
31
    public function value()
32
    {
33
        return $this->value;
34
    }
35
36
    public abstract function allowedValues(): array;
37
38
    /**
39
     * Checks whether the value is valid for this Enum.
40
     *
41
     * Override this method to add other validations.
42
     *
43
     * @param $value
44
     */
45 6
    protected function checkValueIsValid($value): void
46
    {
47 6
        if (!in_array($value, $this->allowedValues())) {
48 1
            throw new \InvalidArgumentException($this->valueNotValidMessage($value));
49
        }
50 5
    }
51
52
    /**
53
     * Generates the error message.
54
     *
55
     * Override this method if the validation is ok but you want a different message.
56
     *
57
     * @param $value
58
     * @return string
59
     */
60
    protected function valueNotValidMessage($value): string
61
    {
62
        return "$value is not a valid value for this Enum";
63
    }
64
65 2
    public function equal(Enum $enum): bool
66
    {
67 2
        return $this->value == $enum->value;
68
    }
69
}
70