Completed
Push — master ( 3b2722...88d5e0 )
by Ondrej
11s
created

Enum::__toString()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 4
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 2
CRAP Score 1

Importance

Changes 1
Bugs 0 Features 0
Metric Value
c 1
b 0
f 0
dl 0
loc 4
ccs 2
cts 2
cp 1
rs 10
cc 1
eloc 2
nc 1
nop 0
crap 1
1
<?php
2
namespace SpareParts\Enum;
3
4
use SpareParts\Enum\Exception\InvalidEnumSetupException;
5
use SpareParts\Enum\Exception\InvalidEnumValueException;
6
7
/**
8
 *
9
 */
10
abstract class Enum
11
{
12
13
    /**
14
     * @var string[]
15
     */
16
    protected static $values = [];
17
18
    /**
19
     * @var $this[]
20
     */
21
    protected static $instances = [];
22
23
    /**
24
     * @var string
25
     */
26
    protected $value;
27
28
    /**
29
     * PROTECTED!! Not callable directly.
30
     * @see static::instance()
31
     * @see static::__callStatic()
32
     * @internal
33
     *
34
     * @param string $value
35
     */
36 4
    protected function __construct($value)
37
    {
38 4
        if (empty(static::$values)) {
39 1
            throw new InvalidEnumSetupException('Incorrect setup! Enum '.get_called_class().' doesn\'t have its static::$values set.');
40
        }
41 3
        if (!in_array($value, static::$values)) {
42 2
            throw new InvalidEnumValueException('Enum '.get_called_class().'does not contain value '.$value.'. Possible values are: '.implode(', ', static::$values));
43
        }
44 1
        $this->value = $value;
45 1
    }
46
47
    /**
48
     *
49
     */
50 1
    public function __toString()
51
    {
52 1
        return $this->value;
53
    }
54
55
    /**
56
     * @param string $method
57
     * @param array $args
58
     *
59
     * @return \SpareParts\Enum\Enum
60
     */
61 5
    public static function __callStatic($method, $args)
62
    {
63 5
        return static::instance($method);
64
    }
65
66
    /**
67
     * @param string $value
68
     *
69
     * @return $this
70
     */
71 7
    public static function instance($value)
72
    {
73 7
        if (!isset(static::$instances[get_called_class()][$value])) {
74 4
            static::$instances[get_called_class()][$value] = new static($value);
75 1
        }
76
77 4
        return static::$instances[get_called_class()][$value];
78
    }
79
}
80