-
Notifications
You must be signed in to change notification settings - Fork 20
Expand file tree
/
Copy pathDTO.php
More file actions
301 lines (269 loc) · 7.5 KB
/
Copy pathDTO.php
File metadata and controls
301 lines (269 loc) · 7.5 KB
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
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
<?php
namespace Mindbox\DTO;
use ArrayAccess;
use ArrayIterator;
use Countable;
use IteratorAggregate;
use Mindbox\Exceptions\MindboxException;
use Mindbox\XMLHelper\MindboxXMLSerializer;
/**
* Class DTO
*
* @package Mindbox\DTO
*/
class DTO implements Countable, ArrayAccess, IteratorAggregate
{
/**
* Мета-данные, необходимы для корректной генерации XML из массива данных.
*/
const XML_ITEM_NAME_INDEX = '@itemName';
/**
* @var array Мэппинг преобразрования полей в объекты DTO.
*/
protected static $DTOMap = [];
/**
* @var string Название элемента для корректной генерации xml.
*/
protected static $xmlName = 'dto';
/**
* @var array Массив всех полей объекта.
*/
protected $items = [];
/**
* Конструктор DTO.
*
* @param array $data Массив данных.
*/
public function __construct(array $data = [])
{
$items = [];
foreach ($data as $key => $value) {
$DTOMap = static::getDTOMap();
if (is_array($value) && isset($DTOMap[$key])) {
$value[static::XML_ITEM_NAME_INDEX] = $DTOMap[$key]::getXmlName();
$items[$key] = static::makeDTO($DTOMap[$key], $value);
} else {
$items[$key] = $value;
}
}
$this->items = $items;
}
/**
* Геттер для $DTOMap.
*
* @return array
*/
public static function getDTOMap()
{
return static::$DTOMap;
}
/**
* Инициализация объекта DTO по его имени.
*
* @param string $name Имя класса DTO.
* @param mixed $data Данные.
*
* @return mixed
*/
protected static function makeDTO($name, $data)
{
if (!is_array($data)) {
return $data;
}
return new $name($data);
}
/**
* Возвращает значение поля DTO по его имени.
*
* @param string $name Имя поля DTO.
* @param mixed $default Значение по умолчанию, будет возвращено в случае, если такое поле отсутствует.
*
* @return mixed
*/
public function getField($name, $default = null)
{
if (isset($this->items[$name])) {
$field = $this->items[$name];
return $this->unsetMetaInfo($field);
}
return $default;
}
/**
* Устанавливает в DTO поле с переданным названием.
*
* @param string $name Название.
* @param mixed $value Значение.
*
* @return void
*/
public function setField($name, $value)
{
$DTOMap = static::getDTOMap();
if (is_array($value) && isset($DTOMap[$name])) {
// Could be a DTO
$value = new $DTOMap[$name]($value);
}
$this->items[$name] = $value;
}
/**
* Возвращает список всех ключей массив полей DTO.
*
* @return array
*/
public function getFieldNames()
{
$fields = $this->items;
return array_keys($this->unsetMetaInfo($fields));
}
/**
* Возвращает все поля DTO.
*
* @return array
*/
public function all()
{
$fields = $this->items;
return $this->unsetMetaInfo($fields);
}
/**
* Возвращает все поля DTO в формате JSON.
*
* @param int $options
*
* @return string
*/
public function toJson($options = 0)
{
return json_encode($this->getFieldsAsArray(), $options) ?: '';
}
/**
* Рекурсивно убирает из переданного массив мета-информацию.
*
* @param mixed $value Массив данных.
*
* @return array
*/
private function unsetMetaInfo($value)
{
if (is_array($value) || is_subclass_of($value, DTO::class)) {
unset($value[static::XML_ITEM_NAME_INDEX]);
foreach ($value as &$item) {
$item = $this->unsetMetaInfo($item);
}
}
return $value;
}
/**
* Возвращает все поля DTO в формате XML.
*
* @return string
*/
public function toXML()
{
return MindboxXMLSerializer::fromArrayToXML(static::getXmlName(), $this->getFieldsAsArray(false));
}
/**
* Геттер для $xmlName.
*
* @return string
*/
public static function getXmlName()
{
return static::$xmlName;
}
/**
* Возвращает все поля DTO в виде массива.
*
* @param bool $unsetXmlMetaInfo Флаг, сообщающий о том нужно ли очищать мета-информацию.
*
* @return array
*/
public function getFieldsAsArray($unsetXmlMetaInfo = true)
{
$fields = $this->items;
if ($unsetXmlMetaInfo) {
unset($fields[static::XML_ITEM_NAME_INDEX]);
}
return array_map(
function ($value) use ($unsetXmlMetaInfo) {
return $value instanceof DTO ?
$value->getFieldsAsArray($unsetXmlMetaInfo) :
($unsetXmlMetaInfo ? $this->unsetMetaInfo($value) : $value);
},
$fields
);
}
/**
* Возвращает количество элементов, модержащихся в DTO.
*
* @return int
*/
public function count(): int
{
$fields = $this->items;
return count($this->unsetMetaInfo($fields));
}
/**
* Возвращает ArrayIterator.
*
* @return ArrayIterator
*/
public function getIterator(): ArrayIterator
{
return new ArrayIterator($this->items);
}
/**
* Возвращает элемент DTO по заданному ключу.
*
* @param mixed $key Ключ.
*
* @return mixed
* @throws MindboxException
*/
#[\ReturnTypeWillChange]
public function offsetGet($key)
{
if (!$this->offsetExists($key)) {
throw new MindboxException('Undefined index: ' . $key);
}
return $this->items[$key];
}
/**
* Проверяет, существует ли заданный ключ в элементах DTO.
*
* @param mixed $key
*
* @return bool
*/
public function offsetExists($key): bool
{
return array_key_exists($key, $this->items);
}
/**
* Устанавливает заданное значение по переданному ключу в элементы DTO.
*
* @param mixed $key
* @param mixed $value
*
* @return void
*/
public function offsetSet($key, $value): void
{
if (is_null($key)) {
$this->items[] = $value;
} else {
$this->items[$key] = $value;
}
}
/**
* Удаляет заданное значение из элементов DTO по ключу.
*
* @param string $key Ключ.
*
* @return void
*/
public function offsetUnset($key): void
{
unset($this->items[$key]);
}
}