-
Notifications
You must be signed in to change notification settings - Fork 0
/
Formatter.php
116 lines (101 loc) · 2.78 KB
/
Formatter.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
<?php
namespace iMega\Formatter;
class Formatter
{
protected $fields = [];
public function __construct(array $meta)
{
foreach ($meta as $item) {
if (empty($item) || !is_array($item)) {
throw new FormatterException('Wrong type');
}
list($name, $default, $type, $error) = $item;
if (0 !== $error) {
throw new FormatterException('Wrong field name');
}
if (get_parent_class($type) == GenericType::class) {
$this->fields[$name] = [$default, $type];
} else {
throw new FormatterException('Wrong instance');
}
}
}
public function getData($name, $value)
{
$type = $this->getType($name);
try {
return $type::getData($value);
} catch (FormatterException $e) {
return $type::getData($this->getDefaultValue($name));
}
}
public function getValue($name, $value)
{
$type = $this->getType($name);
try {
return $type::getValue($value);
} catch (FormatterException $e) {
return $this->getDefaultValue($name);
}
}
public function getDataCollection(array $values)
{
$ret = [];
foreach ($this->getFileds() as $name) {
if (array_key_exists($name, $values)) {
$ret[$name] = $this->getData($name, $values[$name]);
} else {
$type = $this->getType($name);
$ret[$name] = $type::getData($this->getDefaultValue($name));
}
}
return $ret;
}
public function getValueCollection(array $values)
{
$ret = [];
foreach ($this->getFileds() as $name) {
if (array_key_exists($name, $values)) {
$ret[$name] = $this->getValue($name, $values[$name]);
} else {
$ret[$name] = $this->getDefaultValue($name);
}
}
return $ret;
}
/**
* @return array
*/
public function getFileds()
{
return array_keys($this->fields);
}
/**
* @param string $name
*
* @return GenericType
*/
protected function getField($name)
{
if (array_key_exists($name, $this->fields)) {
return $this->fields[$name];
} else {
throw new FormatterException('Field not exists');
}
}
protected function getDefaultValue($name)
{
list($default, $type) = $this->getField($name);
return $default;
}
/**
* @param $name
*
* @return \iMega\Formatter\Typer
*/
protected function getType($name)
{
list($default, $type) = $this->getField($name);
return $type;
}
}