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);