-
Notifications
You must be signed in to change notification settings - Fork 41
Expand file tree
/
Copy pathMarshaller.php
More file actions
312 lines (270 loc) · 10.2 KB
/
Marshaller.php
File metadata and controls
312 lines (270 loc) · 10.2 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
302
303
304
305
306
307
308
309
310
311
312
<?php
declare(strict_types=1);
namespace Muffin\Webservice\Datasource;
use ArrayObject;
use Cake\Collection\Collection;
use Cake\Datasource\EntityInterface;
use Cake\Datasource\InvalidPropertyInterface;
use Muffin\Webservice\Model\Endpoint;
use RuntimeException;
use Traversable;
/**
* Contains logic to convert array data into resources.
*
* Useful when converting request data into resources.
*/
class Marshaller
{
/**
* The endpoint instance this marshaller is for.
*
* @var \Muffin\Webservice\Model\Endpoint
*/
protected Endpoint $_endpoint;
/**
* Constructor.
*
* @param \Muffin\Webservice\Model\Endpoint $endpoint The endpoint this marshaller is for.
*/
public function __construct(Endpoint $endpoint)
{
$this->_endpoint = $endpoint;
}
/**
* Hydrate one entity.
*
* ### Options:
*
* * fieldList: A whitelist of fields to be assigned to the entity. If not present,
* the accessible fields list in the entity will be used.
* * accessibleFields: A list of fields to allow or deny in entity accessible fields.
*
* @param array $data The data to hydrate.
* @param array $options List of options
* @return \Cake\Datasource\EntityInterface
* @see \Muffin\Webservice\Model\Endpoint::newEntity()
*/
public function one(array $data, array $options = []): EntityInterface
{
[$data, $options] = $this->_prepareDataAndOptions($data, $options);
$primaryKey = (array)$this->_endpoint->getPrimaryKey();
/** @psalm-var class-string<\Muffin\Webservice\Model\Resource> */
$resourceClass = $this->_endpoint->getResourceClass();
$entity = new $resourceClass();
$entity->setSource($this->_endpoint->getRegistryAlias());
if (isset($options['accessibleFields'])) {
foreach ((array)$options['accessibleFields'] as $key => $value) {
$entity->setAccess($key, $value);
}
}
$errors = $this->_validate($data, $options, true);
$properties = [];
foreach ($data as $key => $value) {
if (!empty($errors[$key])) {
$entity->setInvalidField($key, $value);
continue;
}
if ($value === '' && in_array($key, $primaryKey, true)) {
// Skip marshalling '' for pk fields.
continue;
}
$properties[$key] = $value;
}
if (!isset($options['fieldList'])) {
$entity->set($properties);
$entity->setErrors($errors);
return $entity;
}
foreach ((array)$options['fieldList'] as $field) {
if (array_key_exists($field, $properties)) {
$entity->set($field, $properties[$field]);
}
}
$entity->setErrors($errors);
return $entity;
}
/**
* Returns the validation errors for a data set based on the passed options
*
* @param array $data The data to validate.
* @param array $options The options passed to this marshaller.
* @param bool $isNew Whether it is a new entity or one to be updated.
* @return array The list of validation errors.
* @throws \RuntimeException If no validator can be created.
*/
protected function _validate(array $data, array $options, bool $isNew): array
{
if (!$options['validate']) {
return [];
}
if ($options['validate'] === true) {
$options['validate'] = $this->_endpoint->getValidator('default');
}
if (is_string($options['validate'])) {
$options['validate'] = $this->_endpoint->getValidator($options['validate']);
}
if (!is_object($options['validate'])) {
throw new RuntimeException(
sprintf('validate must be a boolean, a string or an object. Got %s.', gettype($options['validate']))
);
}
return $options['validate']->validate($data, $isNew);
}
/**
* Returns data and options prepared to validate and marshall.
*
* @param array $data The data to prepare.
* @param array $options The options passed to this marshaller.
* @return array An array containing prepared data and options.
*/
protected function _prepareDataAndOptions(array $data, array $options): array
{
$options += ['validate' => true];
$endpointName = $this->_endpoint->getAlias();
if (isset($data[$endpointName])) {
$data = $data[$endpointName];
}
$data = new ArrayObject($data);
$options = new ArrayObject($options);
$this->_endpoint->dispatchEvent('Model.beforeMarshal', compact('data', 'options'));
return [(array)$data, (array)$options];
}
/**
* Hydrate many entities.
*
* ### Options:
*
* * fieldList: A whitelist of fields to be assigned to the entity. If not present,
* the accessible fields list in the entity will be used.
* * accessibleFields: A list of fields to allow or deny in entity accessible fields.
*
* @param array $data The data to hydrate.
* @param array $options List of options
* @return array<\Cake\Datasource\EntityInterface> An array of hydrated records.
* @see \Muffin\Webservice\Model\Endpoint::newEntities()
*/
public function many(array $data, array $options = []): array
{
$output = [];
foreach ($data as $record) {
if (!is_array($record)) {
continue;
}
$output[] = $this->one($record, $options);
}
return $output;
}
/**
* Merges `$data` into `$entity`.
*
* ### Options:
*
* * validate: Whether or not to validate data before hydrating the entities. Can
* also be set to a string to use a specific validator. Defaults to true/default.
* * fieldList: A whitelist of fields to be assigned to the entity. If not present
* the accessible fields list in the entity will be used.
* * accessibleFields: A list of fields to allow or deny in entity accessible fields.
*
* @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 $options List of options.
* @return \Cake\Datasource\EntityInterface
*/
public function merge(EntityInterface $entity, array $data, array $options = []): EntityInterface
{
[$data, $options] = $this->_prepareDataAndOptions($data, $options);
$isNew = $entity->isNew();
$keys = [];
if (!$isNew) {
$keys = $entity->extract((array)$this->_endpoint->getPrimaryKey());
}
if (isset($options['accessibleFields'])) {
foreach ((array)$options['accessibleFields'] as $key => $value) {
$entity->setAccess($key, $value);
}
}
$errors = $this->_validate($data + $keys, $options, $isNew);
$properties = [];
foreach ($data as $key => $value) {
if (!empty($errors[$key])) {
if ($entity instanceof InvalidPropertyInterface) {
$entity->setInvalidField($key, $value);
}
continue;
}
$properties[$key] = $value;
}
if (!isset($options['fieldList'])) {
$entity->set($properties);
$entity->setErrors($errors);
return $entity;
}
foreach ((array)$options['fieldList'] as $field) {
if (array_key_exists($field, $properties)) {
$entity->set($field, $properties[$field]);
}
}
$entity->setErrors($errors);
return $entity;
}
/**
* Merges each of the elements from `$data` into each of the entities in `$entities`.
*
* Records in `$data` are matched against the entities using the primary key
* column. 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.
*
* ### Options:
*
* - fieldList: A whitelist of fields to be assigned to the entity. If not present,
* the accessible fields list in the entity will be used.
* - accessibleFields: A list of fields to allow or deny in entity accessible fields.
*
* @param \Traversable|array $entities the entities that will get the
* data merged in
* @param array $data list of arrays to be merged into the entities
* @param array $options List of options.
* @return array<\Cake\Datasource\EntityInterface>
*/
public function mergeMany(array|Traversable $entities, array $data, array $options = []): array
{
$primary = (array)$this->_endpoint->getPrimaryKey();
$indexed = (new Collection($data))
->groupBy(function ($el) use ($primary) {
$keys = [];
foreach ($primary as $key) {
$keys[] = $el[$key] ?? '';
}
return implode(';', $keys);
})
->map(function ($element, $key) {
return $key === '' ? $element : $element[0];
})
->toArray();
/** @psalm-suppress NullArrayOffset, InvalidArrayOffset */
$new = $indexed[null] ?? [];
/** @psalm-suppress PossiblyNullArrayOffset, InvalidArrayOffset */
unset($indexed[null]);
$output = [];
foreach ($entities as $entity) {
if (!($entity instanceof EntityInterface)) {
continue;
}
$key = implode(';', $entity->extract($primary));
if ($key === '' || !isset($indexed[$key])) {
continue;
}
$output[] = $this->merge($entity, $indexed[$key], $options);
unset($indexed[$key]);
}
foreach ((new Collection($indexed))->append($new) as $value) {
if (!is_array($value)) {
continue;
}
$output[] = $this->one($value, $options);
}
return $output;
}
}