1
|
|
|
<?php |
2
|
|
|
namespace SpareParts\Enum; |
3
|
|
|
|
4
|
|
|
use SpareParts\Enum\Exception\InvalidEnumSetupException; |
5
|
|
|
use SpareParts\Enum\Exception\InvalidEnumValueException; |
6
|
|
|
use SpareParts\Enum\Exception\OperationNotAllowedException; |
7
|
|
|
|
8
|
|
|
/** |
9
|
|
|
* |
10
|
|
|
*/ |
11
|
|
|
abstract class Enum |
12
|
|
|
{ |
13
|
|
|
|
14
|
|
|
/** |
15
|
|
|
* @var string[] |
16
|
|
|
*/ |
17
|
|
|
protected static $values = []; |
18
|
|
|
|
19
|
|
|
/** |
20
|
|
|
* @var $this[] |
21
|
|
|
*/ |
22
|
|
|
protected static $instances = []; |
23
|
|
|
|
24
|
|
|
/** |
25
|
|
|
* @var string |
26
|
|
|
*/ |
27
|
|
|
protected $value; |
28
|
|
|
|
29
|
|
|
/** |
30
|
|
|
* PROTECTED!! Not callable directly. |
31
|
|
|
* @see static::instance() |
32
|
|
|
* @see static::__callStatic() |
33
|
|
|
* @internal |
34
|
|
|
* |
35
|
|
|
* @param string $value |
36
|
|
|
*/ |
37
|
4 |
|
protected function __construct($value) |
38
|
|
|
{ |
39
|
4 |
|
if (empty(static::$values)) { |
40
|
1 |
|
throw new InvalidEnumSetupException('Incorrect setup! Enum '.get_called_class().' doesn\'t have its static::$values set.'); |
41
|
|
|
} |
42
|
3 |
|
if (!in_array($value, static::$values)) { |
43
|
2 |
|
throw new InvalidEnumValueException('Enum '.get_called_class().'does not contain value '.$value.'. Possible values are: '.implode(', ', static::$values)); |
44
|
|
|
} |
45
|
1 |
|
$this->value = $value; |
46
|
1 |
|
} |
47
|
|
|
|
48
|
|
|
/** |
49
|
|
|
* String representation |
50
|
|
|
*/ |
51
|
1 |
|
public function __toString() |
52
|
|
|
{ |
53
|
1 |
|
return $this->value; |
54
|
|
|
} |
55
|
|
|
|
56
|
|
|
/** |
57
|
|
|
* @param string $method |
58
|
|
|
* @param array $args |
59
|
|
|
* |
60
|
|
|
* @return \SpareParts\Enum\Enum |
61
|
|
|
*/ |
62
|
7 |
|
public static function __callStatic($method, $args) |
63
|
|
|
{ |
64
|
7 |
|
return static::instance($method); |
65
|
|
|
} |
66
|
|
|
|
67
|
|
|
/** |
68
|
|
|
* @param string $value |
69
|
|
|
* |
70
|
|
|
* @return $this |
71
|
|
|
*/ |
72
|
9 |
|
public static function instance($value) |
73
|
|
|
{ |
74
|
9 |
|
if (!isset(static::$instances[get_called_class()][$value])) { |
75
|
4 |
|
static::$instances[get_called_class()][$value] = new static($value); |
76
|
1 |
|
} |
77
|
|
|
|
78
|
6 |
|
return static::$instances[get_called_class()][$value]; |
79
|
|
|
} |
80
|
|
|
|
81
|
1 |
|
public function __clone() |
82
|
|
|
{ |
83
|
1 |
|
throw new OperationNotAllowedException('Singleton cannot be cloned.'); |
84
|
|
|
} |
85
|
|
|
|
86
|
1 |
|
public function __sleep() |
87
|
|
|
{ |
88
|
1 |
|
throw new OperationNotAllowedException('Singleton cannot be serialized.'); |
89
|
|
|
} |
90
|
|
|
|
91
|
1 |
|
public function __wakeup() |
92
|
|
|
{ |
93
|
1 |
|
throw new OperationNotAllowedException('Singleton cannot be serialized'); |
94
|
|
|
} |
95
|
|
|
} |
96
|
|
|
|