/
Marshaller.php
386 lines (346 loc) · 11.3 KB
/
Marshaller.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
/**
* CakePHP(tm) : Rapid Development Framework (http://cakephp.org)
* Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org)
*
* Licensed under The MIT License
* For full copyright and license information, please see the LICENSE.txt
* Redistributions of files must retain the above copyright notice.
*
* @copyright Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org)
* @link http://cakephp.org CakePHP(tm) Project
* @since CakePHP(tm) v 3.0.0
* @license MIT License (http://www.opensource.org/licenses/mit-license.php)
*/
namespace Cake\ORM;
use Cake\Collection\Collection;
use Cake\Database\Expression\TupleComparison;
use Cake\Database\Type;
use Cake\Datasource\EntityInterface;
use Cake\ORM\Association;
use Cake\ORM\Table;
/**
* Contains logic to convert array data into entities.
*
* Useful when converting request data into entities.
*
* @see \Cake\ORM\Table::newEntity()
* @see \Cake\ORM\Table::newEntities()
*/
class Marshaller {
/**
* Whether or not this marhshaller is in safe mode.
*
* @var boolean
*/
protected $_safe;
/**
* The table instance this marshaller is for.
*
* @var \Cake\ORM\Table
*/
protected $_table;
/**
* Constructor.
*
* @param \Cake\ORM\Table $table
* @param boolean Whether or not this marshaller is in safe mode
*/
public function __construct(Table $table, $safe = false) {
$this->_table = $table;
$this->_safe = $safe;
}
/**
* Build the map of property => association names.
*
* @param array $include The array of included associations.
* @return array
*/
protected function _buildPropertyMap($include) {
$map = [];
foreach ($include as $key => $nested) {
if (is_int($key) && is_scalar($nested)) {
$key = $nested;
$nested = [];
}
$nested = isset($nested['associated']) ? $nested['associated'] : [];
$assoc = $this->_table->association($key);
if ($assoc) {
$map[$assoc->property()] = [
'association' => $assoc,
'nested' => $nested
];
}
}
return $map;
}
/**
* Hydrate one entity and its associated data.
*
* @param array $data The data to hydrate.
* @param array $include The associations to include.
* @return \Cake\ORM\Entity
* @see \Cake\ORM\Table::newEntity()
*/
public function one(array $data, $include = []) {
$propertyMap = $this->_buildPropertyMap($include);
$schema = $this->_table->schema();
$tableName = $this->_table->alias();
$entityClass = $this->_table->entityClass();
$entity = new $entityClass();
if (isset($data[$tableName])) {
$data = $data[$tableName];
}
$properties = [];
foreach ($data as $key => $value) {
$columnType = $schema->columnType($key);
if (isset($propertyMap[$key])) {
$assoc = $propertyMap[$key]['association'];
$nested = $propertyMap[$key]['nested'];
$value = $this->_marshalAssociation($assoc, $value, $nested);
} elseif ($columnType) {
$converter = Type::build($columnType);
$value = $converter->marshall($value);
}
$properties[$key] = $value;
}
$entity->set($properties);
return $entity;
}
/**
* Create a new sub-marshaller and marshal the associated data.
*
* @param \Cake\ORM\Association $assoc
* @param array $value The data to hydrate
* @param array $include The associations to include.
* @return mixed
*/
protected function _marshalAssociation($assoc, $value, $include) {
$targetTable = $assoc->target();
$marshaller = $targetTable->marshaller();
if ($assoc->type() === Association::ONE_TO_ONE) {
return $marshaller->one($value, (array)$include);
}
if ($assoc->type() === Association::MANY_TO_MANY) {
return $marshaller->_belongsToMany($assoc, $value, (array)$include);
}
return $marshaller->many($value, (array)$include);
}
/**
* Hydrate many entities and their associated data.
*
* @param array $data The data to hydrate.
* @param array $include The associations to include.
* @return array An array of hydrated records.
* @see \Cake\ORM\Table::newEntities()
*/
public function many(array $data, $include = []) {
$output = [];
foreach ($data as $record) {
$output[] = $this->one($record, $include);
}
return $output;
}
/**
* Marshalls data for belongsToMany associations.
*
* Builds the related entities and handles the special casing
* for junction table entities.
*
* @param Association $assoc The association to marshall.
* @param array $data The data to convert into entities.
* @param array $include The nested associations to convert.
* @return array An array of built entities.
*/
protected function _belongsToMany(Association $assoc, array $data, $include = []) {
if (isset($data['_ids']) && is_array($data['_ids'])) {
return $this->_loadBelongsToMany($assoc, $data['_ids']);
}
$records = $this->many($data, $include);
if (!in_array('_joinData', $include) && !isset($include['_joinData'])) {
return $records;
}
$joint = $assoc->junction();
$jointMarshaller = $joint->marshaller();
$nested = [];
if (isset($include['_joinData']['associated'])) {
$nested = (array)$include['_joinData']['associated'];
}
foreach ($records as $i => $record) {
if (isset($data[$i]['_joinData'])) {
$joinData = $jointMarshaller->one($data[$i]['_joinData'], $nested);
$record->set('_joinData', $joinData);
}
}
return $records;
}
/**
* Loads a list of belongs to many from ids.
*
* @param Association $assoc The association class for the belongsToMany association.
* @param array $ids The list of ids to load.
* @return array An array of entities.
*/
protected function _loadBelongsToMany($assoc, $ids) {
$target = $assoc->target();
$primaryKey = (array)$target->primaryKey();
$multi = count($primaryKey) > 1;
if ($multi) {
if (count(current($ids)) !== count($primaryKey)) {
return [];
}
$filter = new TupleComparison($primaryKey, $ids, [], 'IN');
} else {
$filter = [$primaryKey[0] . ' IN' => $ids];
}
return $assoc->find()->where($filter)->toArray();
}
/**
* Merges `$data` into `$entity` and recursively does the same for each one of
* the association names passed in `$include`. When merging association, if an
* entity is not present in the parent entity for such association, a new one
* will be created.
*
* When merging HasMany or BelongsToMany associations, all the entities in the
* `$data` array will appear, those that can be matched by primary key will get
* the data merged, but those that cannot, will be discarded.
*
* @param \Cake\Datasource\EntityInterface $entity the entity that will get the
* data merged in
* @param array $data key value list of fields to be merged into the entity
* @param array $include The list of associations to be merged
* @return \Cake\Datasource\EntityInterface
*/
public function merge(EntityInterface $entity, array $data, $include = []) {
$propertyMap = $this->_buildPropertyMap($include);
$tableName = $this->_table->alias();
if (isset($data[$tableName])) {
$data = $data[$tableName];
}
$properties = [];
foreach ($data as $key => $value) {
$original = $entity->get($key);
if (isset($propertyMap[$key])) {
$assoc = $propertyMap[$key]['association'];
$nested = $propertyMap[$key]['nested'];
$value = $this->_mergeAssociation($original, $assoc, $value, $nested);
} elseif ($original == $value) {
continue;
}
$properties[$key] = $value;
}
$entity->set($properties);
return $entity;
}
/**
* Merges each of the elements from `$data` into each of the entities in `$entities
* and recursively does the same for each one of the association names passed in
* `$include`. When merging association, if an entity is not present in the parent
* entity for such association, a new one will be created.
*
* Records in `$data` are matched against the entities by using the primary key
* column. Those entries in `$entities` that cannot be matched to any record in
* `$data` will be discarded. Records in `$data` that could not be matched will
* be marshalled as a new entity.
*
* When merging HasMany or BelongsToMany associations, all the entities in the
* `$data` array will appear, those that can be matched by primary key will get
* the data merged, but those that cannot, will be discarded.
*
* @param array|\Traversable $entities the entities that will get the
* data merged in
* @param array $data list of arrays to be merged into the entities
* @param array $include The list of associations to be merged
* @return array
*/
public function mergeMany($entities, array $data, $include = []) {
$primary = (array)$this->_table->primaryKey();
$indexed = (new Collection($data))->groupBy($primary[0])->toArray();
$new = isset($indexed[null]) ? [$indexed[null]] : [];
unset($indexed[null]);
$output = [];
foreach ($entities as $entity) {
if (!($entity instanceof EntityInterface)) {
continue;
}
$key = $entity->get($primary[0]);
if ($key === null || !isset($indexed[$key])) {
continue;
}
$output[] = $this->merge($entity, $indexed[$key][0], $include);
unset($indexed[$key]);
}
foreach (array_merge($indexed, $new) as $record) {
foreach ($record as $value) {
$output[] = $this->one($value, $include);
}
}
return $output;
}
/**
* Creates a new sub-marshaller and merges the associated data.
*
* @param \Cake\Datasource\EntityInterface $original
* @param \Cake\ORM\Association $assoc
* @param array $value The data to hydrate
* @param array $include The associations to include.
* @return mixed
*/
protected function _mergeAssociation($original, $assoc, $value, $include) {
if (!$original) {
return $this->_marshalAssociation($assoc, $value, $include);
}
$targetTable = $assoc->target();
$marshaller = $targetTable->marshaller();
if ($assoc->type() === Association::ONE_TO_ONE) {
return $marshaller->merge($original, $value, (array)$include);
}
if ($assoc->type() === Association::MANY_TO_MANY) {
return $marshaller->_mergeBelongsToMany($original, $assoc, $value, (array)$include);
}
return $marshaller->mergeMany($original, $value, (array)$include);
}
/**
* Creates a new sub-marshaller and merges the associated data for a BelongstoMany
* association.
*
* @param \Cake\Datasource\EntityInterface $original
* @param \Cake\ORM\Association $assoc
* @param array $value The data to hydrate
* @param array $include The associations to include.
* @return mixed
*/
protected function _mergeBelongsToMany($original, $assoc, $data, $include) {
if (isset($data['_ids']) && is_array($data['_ids'])) {
return $this->_loadBelongsToMany($assoc, $data['_ids']);
}
if (!in_array('_joinData', $include) && !isset($include['_joinData'])) {
return $this->mergeMany($original, $data, $include);
}
$extra = [];
foreach ($original as $entity) {
$joinData = $entity->get('_joinData');
if ($joinData) {
$extra[spl_object_hash($entity)] = $joinData;
}
}
$joint = $assoc->junction();
$marshaller = $joint->marshaller();
$nested = [];
if (isset($include['_joinData']['associated'])) {
$nested = (array)$include['_joinData']['associated'];
}
$records = $this->mergeMany($original, $data, $include);
foreach ($records as $record) {
$hash = spl_object_hash($record);
$data = $record->get('_joinData');
if (isset($extra[$hash])) {
$record->set('_joinData', $marshaller->merge($extra[$hash], (array)$data, $nested));
} else {
$joinData = $marshaller->one($data, $nested);
$record->set('_joinData', $joinData);
}
}
return $records;
}
}