-
Notifications
You must be signed in to change notification settings - Fork 2
/
EntityDataExtractor.php
executable file
·386 lines (322 loc) · 12.6 KB
/
EntityDataExtractor.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
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
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
<?php
/**
* Webiny Framework (http://www.webiny.com/framework)
*
* @copyright Copyright Webiny LTD
*/
namespace Webiny\Component\Entity;
use Webiny\Component\Entity\Attribute\AbstractAttribute;
use Webiny\Component\Entity\Attribute\AttributeType;
use Webiny\Component\StdLib\StdLibTrait;
use Webiny\Component\StdLib\StdObject\ArrayObject\ArrayObject;
use Webiny\Component\StdLib\StdObject\StringObject\StringObject;
/**
* EntityDataExtractor class converts AbstractEntity instance to an array representation.
*
* @package Webiny\Component\Entity
*/
class EntityDataExtractor
{
use StdLibTrait;
/**
* @var AbstractEntity
*/
protected $entity;
protected static $currentLevel = 0;
protected static $cache = [];
protected $nestedLevel = 10; // Maximum depth is 10 which is hard to achieve
public function __construct(AbstractEntity $entity)
{
$this->entity = $entity;
}
/**
* Extract AbstractEntity data to array using specified list of attributes.
* If no attributes are specified, only simple and Many2One attributes will be extracted.
* If you need to get One2Many and Many2Many attributes, you need to explicitly specify a list of attributes.
*
* @param array $attributes Ex: 'title,author.name,comments.id,comments.text'
*
* @return array
*/
public function extractData($attributes = [])
{
if ($this->isEmpty($attributes)) {
$attributes = $this->getDefaultAttributes();
}
$data = [];
/* @var array $attributes Array that contains all fields, aliases and dotted fields */
$attributes = $this->buildEntityFields($attributes);
foreach ($attributes['fields'] as $attr => $subAttributes) {
$parts = explode(':', $attr);
$attrName = $parts[0];
$params = array_slice($parts, 1);
try {
$entityAttribute = $this->entity->getAttribute($attrName);
} catch (EntityException $e) {
continue;
}
$entityAttributeValue = $entityAttribute->getValue($params);
$isOne2Many = $this->isInstanceOf($entityAttribute, AttributeType::ONE2MANY);
$isMany2Many = $this->isInstanceOf($entityAttribute, AttributeType::MANY2MANY);
$isMany2One = $this->isInstanceOf($entityAttribute, AttributeType::MANY2ONE) || $entityAttributeValue instanceof AbstractEntity;
$isArray = $this->isInstanceOf($entityAttribute, AttributeType::ARR);
$isObject = $this->isInstanceOf($entityAttribute, AttributeType::OBJECT);
$isDynamic = $this->isInstanceOf($entityAttribute, AttributeType::DYNAMIC);
if ($isMany2One) {
if ($this->isNull($entityAttributeValue)) {
$data[$attrName] = null;
continue;
}
if ($entityAttribute->hasToArrayCallback()) {
$data[$attrName] = $entityAttribute->toArray($params);
continue;
}
if (self::$currentLevel < $this->nestedLevel) {
self::$currentLevel++;
$data[$attrName] = $entityAttributeValue->toArray($subAttributes, $this->nestedLevel);
self::$currentLevel--;
}
} elseif ($isOne2Many || $isMany2Many) {
$data[$attrName] = [];
foreach ($entityAttributeValue as $item) {
if (self::$currentLevel < $this->nestedLevel) {
self::$currentLevel++;
$data[$attrName][] = $item->toArray($subAttributes, $this->nestedLevel);
self::$currentLevel--;
}
}
} elseif ($isObject) {
$value = $entityAttribute->toArray($params);
if ($subAttributes) {
$keys = $this->buildNestedKeys($subAttributes);
$value = $this->arr();
foreach ($keys as $key) {
$value->keyNested($key, $entityAttribute->getValue()->keyNested($key));
}
$value = $value->val();
}
if (count($value) == 0) {
$value = new \stdClass();
}
$data[$attrName] = $value;
} elseif ($isArray) {
$value = $entityAttribute->toArray();
if ($subAttributes) {
$subValues = [];
foreach ($value as $array) {
$subValues[] = $this->getSubAttributesFromArray($subAttributes, $array);
}
$value = $subValues;
$value['__webiny_array__'] = true;
}
$data[$attrName] = $value;
} elseif ($isDynamic) {
$data[$attrName] = $entityAttribute->toArray($subAttributes, $params);
} else {
$data[$attrName] = $entityAttribute->toArray($params);
}
}
// Populate alias value
$copy = $data;
$data = $this->arr($data);
// If aliases were used, recreate the entire array to remove junk keys of aliased attributes
if (count($attributes['aliases'])) {
$cleanData = $this->arr();
foreach ($attributes['dottedFields'] as $key) {
if (array_key_exists($key, $attributes['aliases'])) {
$cleanData->keyNested($attributes['aliases'][$key], $data->keyNested($key), true);
continue;
}
$cleanData->keyNested($key, $data->keyNested($key), true);
}
$data = $cleanData;
}
// Copy ArrayAttribute value from backup
foreach ($copy as $key => $value) {
if (is_array($value) && array_key_exists('__webiny_array__', $value)) {
unset($value['__webiny_array__']);
$data[$key] = $value;
}
}
return $data->val();
}
/**
* Parse fields string and build nested fields structure.<br>
* If array is given, will just return that array.
*
* @param string|array $fields
*
* @return array
*/
public function buildEntityFields($fields)
{
$aliases = [];
$dottedFields = [];
if (!$this->isArray($fields)) {
$cacheKey = $fields;
if (array_key_exists($cacheKey, self::$cache)) {
return self::$cache[$cacheKey];
}
$fields = $this->str($fields);
if ($fields->contains('[')) {
$fields = $this->parseGroupedNestedFields($fields);
}
$fields = $fields->explode(',')->filter()->map('trim')->val();
} else {
$cacheKey = serialize($fields);
if (array_key_exists($cacheKey, self::$cache)) {
return self::$cache[$cacheKey];
}
// Check if asterisk is present and replace it with actual attribute names
if ($this->arr($fields)->keyExists('*')) {
unset($fields['*']);
$defaultFields = $this->str($this->getDefaultAttributes())->explode(',')->filter()->map('trim')->flip()->val();
$fields = $this->arr($fields)->merge($defaultFields)->val();
}
return self::$cache[$cacheKey] = [
'fields' => $fields,
'aliases' => $aliases,
'dottedFields' => $dottedFields
];
}
$parsedFields = $this->arr(['id' => true]);
$unsetFields = [];
foreach ($fields as $f) {
$f = $this->str($f);
if ($f->contains('@')) {
list($f, $alias) = $f->explode('@')->val();
$aliases[$f] = $alias;
$f = $this->str($f);
}
$dottedFields[] = $f->val();
if ($f->startsWith('!')) {
$unsetFields[] = $f->trimLeft('!')->val();
continue;
}
if ($f->val() == '*') {
$defaultFields = $this->str($this->getDefaultAttributes())->explode(',')->filter()->map('trim')->val();
foreach ($defaultFields as $df) {
$this->buildFields($parsedFields, $this->str($df));
}
continue;
}
$this->buildFields($parsedFields, $f);
}
foreach ($unsetFields as $field) {
$parsedFields->removeKey($field);
}
return self::$cache[$cacheKey] = [
'fields' => $parsedFields->val(),
'aliases' => $aliases,
'dottedFields' => $dottedFields
];
}
/**
* Check if there are grouped nested keys (by using '[' and ']' and converts that string
* into a plain version - a string that only contains comma-separated full paths of each field
*
* @param $string
*
* @return StringObject
*/
private function parseGroupedNestedFields(StringObject $string)
{
$output = $this->str('');
$currentPath = [
'array' => [],
'string' => ''
];
$parts = $string->explode('[');
$lastPart = $parts->count() - 1;
foreach ($parts as $index => $part) {
$fields = explode(',', $part);
$isLast = $index == $lastPart;
if (!$isLast) {
$newNestedKey = array_pop($fields) . '.';
}
foreach ($fields as $field) {
$fullPath = '';
if (substr($field, 0, 1) == '!') {
$fullPath = '!';
$field = ltrim($field, '!');
}
$closingBrackets = substr_count($field, ']');
$field = rtrim($field, ']');
$fullPath .= $currentPath['string'] . $field;
$output->append($fullPath . ',');
if ($closingBrackets > 0) {
$currentPath['array'] = array_slice($currentPath['array'], 0, count($currentPath['array']) - $closingBrackets);
$currentPath['string'] = implode('.', $currentPath['array']);
}
}
if (!$isLast) {
$currentPath['string'] .= $newNestedKey;
$currentPath['array'][] = $newNestedKey;
}
}
return $output->trimRight(',');
}
/**
* Parse attribute key recursively
*
* @param ArrayObject $parsedFields Reference to array of parsed fields
* @param StringObject $key Current key to parse
*/
private function buildFields(&$parsedFields, StringObject $key)
{
if ($key->contains('.')) {
$parts = $key->explode('.', 2)->val();
if (!isset($parsedFields[$parts[0]])) {
$parsedFields[$parts[0]] = [];
} elseif (!is_array($parsedFields[$parts[0]])) {
$parsedFields[$parts[0]] = [];
}
$this->buildFields($parsedFields[$parts[0]], $this->str($parts[1]));
} else {
$parsedFields[$key->val()] = '';
}
}
private function buildNestedKeys($fields)
{
$keys = [];
foreach ($fields as $f => $nestedFields) {
if (is_array($nestedFields)) {
$nestedKeys = $this->buildNestedKeys($nestedFields);
foreach ($nestedKeys as $k) {
$keys[] = $f . '.' . $k;
}
} else {
$keys[] = $f;
}
}
return $keys;
}
private function getSubAttributesFromArray($subAttributes, $array)
{
$keys = $this->buildNestedKeys($subAttributes);
$value = $this->arr();
$entityAttributeValue = $this->arr($array);
foreach ($keys as $key) {
$key = $this->str($key);
$value->keyNested($key, $entityAttributeValue->keyNested($key), true);
}
return $value->val();
}
/**
* Get default list of entity attributes.<br>
* Only simple and Many2One attributes are considered to be default attributes.
*
* @return string
*/
private function getDefaultAttributes()
{
$attributes = ['id'];
foreach ($this->entity->getAttributes() as $name => $attribute) {
/* @var AbstractAttribute $attribute */
if ($attribute->getToArrayDefault()) {
$attributes[] = $name;
}
}
return $this->arr($attributes)->implode(',')->val();
}
}