Passed
Push — master ( 761f71...ff7c30 )
by Jhao
02:43
created

Enum::jsonSerialize()   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 0
Metric Value
cc 1
eloc 1
nc 1
nop 0
dl 0
loc 3
ccs 2
cts 2
cp 1
crap 1
rs 10
c 0
b 0
f 0
1
<?php
2
3
/**
4
 * This file is part of RussianPost SDK package.
5
 *
6
 * © Appwilio (http://appwilio.com), greabock (https://github.com/greabock), JhaoDa (https://github.com/jhaoda)
7
 *
8
 * For the full copyright and license information, please view the LICENSE
9
 * file that was distributed with this source code.
10
 */
11
12
declare(strict_types=1);
13
14
namespace Appwilio\RussianPostSDK\Core;
15
16
abstract class Enum implements \JsonSerializable
17
{
18
    protected static $cache = [];
19
20
    protected $value;
21
22 16
    public function __construct($value)
23
    {
24 16
        if ($value instanceof static) {
25 1
            $value = $value->getValue();
26
        }
27
28 16
        if (! \in_array($value, static::toArray(), true)) {
29
            throw new \UnexpectedValueException("Value '$value' is not part of the enum ".static::class);
30
        }
31
32 16
        $this->value = $value;
33 16
    }
34
35 16
    public static function toArray(): array
36
    {
37 16
        $class = static::class;
38
39 16
        if (! isset(static::$cache[$class])) {
40 4
            static::$cache[$class] = (new \ReflectionClass($class))->getConstants();
41
        }
42
43 16
        return static::$cache[$class];
44
    }
45
46 16
    public static function __callStatic($name, $arguments)
47
    {
48 16
        $options = static::toArray();
49
50 16
        if (isset($options[$name]) || \array_key_exists($name, $options)) {
51 16
            return new static($options[$name]);
52
        }
53
54
        throw new \BadMethodCallException("No static method or enum constant '$name' in class ".static::class);
55
    }
56
57 1
    public function jsonSerialize()
58
    {
59 1
        return $this->getValue();
60
    }
61
62 2
    final public function equals(Enum $other): bool
63
    {
64 2
        return $this === $other || (\get_class($other) === static::class && $this->value === $other->value);
65
    }
66
67 16
    final public function getValue()
68
    {
69 16
        return $this->value;
70
    }
71
72
    final private function __clone()
73
    {
74
        throw new \LogicException('Enums are not cloneable');
75
    }
76
77
    final public function __sleep()
78
    {
79
        throw new \LogicException('Enums are not serializable');
80
    }
81
82
    final public function __wakeup()
83
    {
84
        throw new \LogicException('Enums are not serializable');
85
    }
86
}
87