1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
namespace Zerg\Field; |
4
|
|
|
|
5
|
|
|
use Zerg\Stream\AbstractStream; |
6
|
|
|
|
7
|
|
|
/** |
8
|
|
|
* Enum field return one of given values depends on read value. |
9
|
|
|
* |
10
|
|
|
* @since 0.1 |
11
|
|
|
* @package Zerg\Field |
12
|
|
|
*/ |
13
|
|
|
class Enum extends Int |
14
|
|
|
{ |
15
|
|
|
/** |
16
|
|
|
* @var array Array of possible values. Keys should by integer. |
17
|
|
|
*/ |
18
|
|
|
protected $values; |
19
|
|
|
|
20
|
|
|
/** |
21
|
|
|
* @var mixed Default value, if no one of possible values are not relate to read value. |
22
|
|
|
*/ |
23
|
|
|
protected $default; |
24
|
|
|
|
25
|
6 |
|
public function __construct($size, array $values = [], $options = []) |
26
|
|
|
{ |
27
|
6 |
|
parent::__construct($size, $options); |
28
|
6 |
|
if (!empty($values)) { |
29
|
5 |
|
$this->setValues($values); |
30
|
5 |
|
} |
31
|
6 |
|
} |
32
|
|
|
|
33
|
|
|
/** |
34
|
|
|
* Read key from Stream, and return value by this key or default value. |
35
|
|
|
* |
36
|
|
|
* @param AbstractStream $stream Stream from which resolved field reads. |
37
|
|
|
* @return object|integer|double|string|array|boolean|callable Value by read key or default value if present. |
38
|
|
|
* @throws InvalidKeyException If read key is not exist and default value is not presented. |
39
|
|
|
*/ |
40
|
4 |
|
public function read(AbstractStream $stream) |
41
|
|
|
{ |
42
|
4 |
|
$key = parent::read($stream); |
43
|
4 |
|
$values = $this->getValues(); |
44
|
|
|
|
45
|
4 |
|
if (array_key_exists($key, $values)) { |
46
|
3 |
|
$value = $values[$key]; |
47
|
3 |
|
} else { |
48
|
2 |
|
$value = $this->getDefault(); |
49
|
|
|
} |
50
|
|
|
|
51
|
4 |
|
if ($value === null) { |
52
|
1 |
|
throw new InvalidKeyException( |
53
|
1 |
|
"Value '{$key}' does not correspond to a valid enum key. Presented keys: '" . |
54
|
1 |
|
implode("', '", array_keys($values)) . "'" |
55
|
1 |
|
); |
56
|
|
|
} |
57
|
|
|
|
58
|
3 |
|
return $value; |
59
|
|
|
} |
60
|
|
|
|
61
|
|
|
/** |
62
|
|
|
* @return array |
63
|
|
|
*/ |
64
|
4 |
|
public function getValues() |
65
|
|
|
{ |
66
|
4 |
|
return $this->values; |
67
|
|
|
} |
68
|
|
|
|
69
|
|
|
/** |
70
|
|
|
* @param array $values |
71
|
|
|
*/ |
72
|
5 |
|
public function setValues($values) |
73
|
|
|
{ |
74
|
5 |
|
$this->values = $values; |
75
|
5 |
|
} |
76
|
|
|
|
77
|
|
|
/** |
78
|
|
|
* @return mixed |
79
|
|
|
*/ |
80
|
2 |
|
public function getDefault() |
81
|
|
|
{ |
82
|
2 |
|
return $this->default; |
83
|
|
|
} |
84
|
|
|
|
85
|
|
|
/** |
86
|
|
|
* @param mixed $default |
87
|
|
|
*/ |
88
|
2 |
|
public function setDefault($default) |
89
|
|
|
{ |
90
|
2 |
|
$this->default = $default; |
91
|
|
|
} |
92
|
|
|
} |