Passed
Push — 1.0.0 ( 044a70...a05234 )
by Alex
01:34
created

Enum::fromValue()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 3
Code Lines 1

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 2
CRAP Score 1

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 1
eloc 1
c 1
b 0
f 0
nc 1
nop 1
dl 0
loc 3
rs 10
ccs 2
cts 2
cp 1
crap 1
1
<?php
2
3
namespace StraTDeS\VO\Single;
4
5
abstract class Enum
6
{
7
    protected $value;
8
9 2
    private function __construct($value)
10
    {
11 2
        $this->checkValueIsValid($value);
12 1
        $this->value = $value;
13 1
    }
14
15
    /**
16
     * @param $value
17
     * @return static
18
     */
19 2
    public static function fromValue($value)
20
    {
21 2
        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 2
    protected function checkValueIsValid($value): void
46
    {
47 2
        if (!in_array($value, $this->allowedValues())) {
48 1
            throw new \InvalidArgumentException($this->valueNotValidMessage($value));
49
        }
50 1
    }
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