Passed
Push — master ( a08302...5e3dfd )
by Jhao
02:06
created

Enum::__toString()   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
eloc 1
c 1
b 0
f 0
dl 0
loc 3
ccs 2
cts 2
cp 1
rs 10
cc 1
nc 1
nop 0
crap 1
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 20
    public function __construct($value)
23
    {
24 20
        if ($value instanceof static) {
25 2
            $value = $value->getValue();
26
        }
27
28 20
        if (! \in_array($value, static::toArray(), true)) {
29 1
            throw new \UnexpectedValueException("Value '$value' is not part of the enum ".static::class);
30
        }
31
32 19
        $this->value = $value;
33 19
    }
34
35 21
    public static function toArray(): array
36
    {
37 21
        $class = static::class;
38
39 21
        if (! isset(static::$cache[$class])) {
40 5
            static::$cache[$class] = (new \ReflectionClass($class))->getConstants();
41
        }
42
43 21
        return static::$cache[$class];
44
    }
45
46 18
    public static function __callStatic($name, $arguments)
47
    {
48 18
        $options = static::toArray();
49
50 18
        if (isset($options[$name]) || \array_key_exists($name, $options)) {
51 17
            return new static($options[$name]);
52
        }
53
54 1
        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 3
    public function __toString(): string
63
    {
64 3
        return (string) $this->getValue();
65
    }
66
67 2
    final public function equals(Enum $other): bool
68
    {
69 2
        return $this === $other || (\get_class($other) === static::class && $this->value === $other->value);
70
    }
71
72 21
    final public function getValue()
73
    {
74 21
        return $this->value;
75
    }
76
77 1
    final public function __clone()
78
    {
79 1
        throw new \LogicException('Enums are not cloneable');
80
    }
81
}
82