-
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathItemNormalizer.php
More file actions
453 lines (360 loc) · 18.4 KB
/
Copy pathItemNormalizer.php
File metadata and controls
453 lines (360 loc) · 18.4 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
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
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
<?php
/*
* This file is part of the API Platform project.
*
* (c) Kévin Dunglas <dunglas@gmail.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
declare(strict_types=1);
namespace ApiPlatform\JsonApi\Serializer;
use ApiPlatform\JsonApi\Util\ResourceLinkageResolver;
use ApiPlatform\Metadata\ApiProperty;
use ApiPlatform\Metadata\IdentifiersExtractorInterface;
use ApiPlatform\Metadata\IriConverterInterface;
use ApiPlatform\Metadata\Property\Factory\PropertyMetadataFactoryInterface;
use ApiPlatform\Metadata\Property\Factory\PropertyNameCollectionFactoryInterface;
use ApiPlatform\Metadata\Resource\Factory\ResourceMetadataCollectionFactoryInterface;
use ApiPlatform\Metadata\ResourceAccessCheckerInterface;
use ApiPlatform\Metadata\ResourceClassResolverInterface;
use ApiPlatform\Metadata\UrlGeneratorInterface;
use ApiPlatform\Metadata\Util\ClassInfoTrait;
use ApiPlatform\Metadata\Util\CompositeIdentifierParser;
use ApiPlatform\Serializer\AbstractItemNormalizer;
use ApiPlatform\Serializer\ContextTrait;
use ApiPlatform\Serializer\OperationResourceClassResolverInterface;
use ApiPlatform\Serializer\TagCollectorInterface;
use Symfony\Component\ErrorHandler\Exception\FlattenException;
use Symfony\Component\PropertyAccess\PropertyAccessorInterface;
use Symfony\Component\Serializer\Exception\LogicException;
use Symfony\Component\Serializer\Exception\UnexpectedValueException;
use Symfony\Component\Serializer\Mapping\Factory\ClassMetadataFactoryInterface;
use Symfony\Component\Serializer\NameConverter\NameConverterInterface;
use Symfony\Component\Serializer\Normalizer\NormalizerInterface;
/**
* Converts objects to JSON:API documents (normalization only).
*
* @author Kévin Dunglas <dunglas@gmail.com>
* @author Amrouche Hamza <hamza.simperfit@gmail.com>
* @author Baptiste Meyer <baptiste.meyer@gmail.com>
*/
final class ItemNormalizer extends AbstractItemNormalizer
{
use ClassInfoTrait;
use ContextTrait;
use ItemNormalizerTrait {
denormalize as private doDenormalize;
}
public const FORMAT = 'jsonapi';
/**
* Denormalization context flag enabling client-generated IDs on POST per
* https://jsonapi.org/format/#crud-creating-client-ids. Off by default to
* avoid an id-spoofing footgun on public endpoints. Set in the context or
* via the bundle configuration ("api_platform.jsonapi.allow_client_generated_id").
*/
public const ALLOW_CLIENT_GENERATED_ID = 'allow_client_generated_id';
private array $componentsCache = [];
private bool $useIriAsId;
private readonly ResourceLinkageResolver $resourceLinkageResolver;
public function __construct(
PropertyNameCollectionFactoryInterface $propertyNameCollectionFactory,
PropertyMetadataFactoryInterface $propertyMetadataFactory,
IriConverterInterface $iriConverter,
ResourceClassResolverInterface $resourceClassResolver,
?PropertyAccessorInterface $propertyAccessor = null,
?NameConverterInterface $nameConverter = null,
?ClassMetadataFactoryInterface $classMetadataFactory = null,
array $defaultContext = [],
?ResourceMetadataCollectionFactoryInterface $resourceMetadataCollectionFactory = null,
?ResourceAccessCheckerInterface $resourceAccessChecker = null,
protected ?TagCollectorInterface $tagCollector = null,
?OperationResourceClassResolverInterface $operationResourceResolver = null,
private readonly ?IdentifiersExtractorInterface $identifiersExtractor = null,
bool $useIriAsId = true,
?ResourceLinkageResolver $resourceLinkageResolver = null,
) {
parent::__construct($propertyNameCollectionFactory, $propertyMetadataFactory, $iriConverter, $resourceClassResolver, $propertyAccessor, $nameConverter, $classMetadataFactory, $defaultContext, $resourceMetadataCollectionFactory, $resourceAccessChecker, $tagCollector, $operationResourceResolver);
$this->useIriAsId = $useIriAsId;
$this->resourceLinkageResolver = $resourceLinkageResolver ?? new ResourceLinkageResolver($resourceClassResolver);
}
public function supportsNormalization(mixed $data, ?string $format = null, array $context = []): bool
{
return self::FORMAT === $format && parent::supportsNormalization($data, $format, $context) && !($data instanceof \Exception || $data instanceof FlattenException);
}
public function getSupportedTypes(?string $format): array
{
return self::FORMAT === $format ? parent::getSupportedTypes($format) : [];
}
public function denormalize(mixed $data, string $type, ?string $format = null, array $context = []): mixed
{
trigger_deprecation('api-platform/core', '4.4', 'Calling "denormalize()" on "%s" is deprecated, use "%s" instead.', self::class, ItemDenormalizer::class);
return $this->doDenormalize($data, $type, $format, $context);
}
public function normalize(mixed $data, ?string $format = null, array $context = []): array|string|int|float|bool|\ArrayObject|null
{
$resourceClass = $this->getObjectClass($data);
if ($this->getOutputClass($context)) {
return parent::normalize($data, $format, $context);
}
$previousResourceClass = $context['resource_class'] ?? null;
if ($this->resourceClassResolver->isResourceClass($resourceClass) && (null === $previousResourceClass || $this->resourceClassResolver->isResourceClass($previousResourceClass))) {
$resourceClass = $this->resourceClassResolver->getResourceClass($data, $previousResourceClass);
}
if (($operation = $context['operation'] ?? null) && method_exists($operation, 'getItemUriTemplate')) {
$context['item_uri_template'] = $operation->getItemUriTemplate();
}
$context = $this->initContext($resourceClass, $context);
$iri = $context['iri'] ??= $this->iriConverter->getIriFromResource($data, UrlGeneratorInterface::ABS_PATH, $context['operation'] ?? null, $context);
$context['object'] = $data;
$context['format'] = $format;
$context['api_normalize'] = true;
if (!isset($context['cache_key'])) {
$context['cache_key'] = $this->isCacheKeySafe($context) ? $this->getCacheKey($format, $context) : false;
}
$normalizedData = parent::normalize($data, $format, $context);
if (!\is_array($normalizedData)) {
return $normalizedData;
}
['relationships' => $allRelationshipsData, 'links' => $links] = $this->getComponents($data, $format, $context);
$populatedRelationContext = $context;
$relationshipsData = $this->getPopulatedRelations($data, $format, $populatedRelationContext, $allRelationshipsData);
$id = $iri;
if (!$this->useIriAsId) {
$identifiers = $this->identifiersExtractor->getIdentifiersFromItem($data, context: $context);
$id = $this->getIdStringFromIdentifiers($identifiers);
}
$resourceShortName = $this->getResourceShortName($resourceClass);
// Do not include primary resources — use type:id composite key to avoid cross-type collisions
$context['api_included_resources'] = [$resourceShortName.':'.$id => true];
$includedResourcesData = $this->getRelatedResources($data, $format, $context, $allRelationshipsData);
$resourceData = [
'id' => $id,
'type' => $resourceShortName,
];
if (!$this->useIriAsId) {
$resourceData['links'] = ['self' => $iri];
}
if ($normalizedData) {
$resourceData['attributes'] = $normalizedData;
}
if ($relationshipsData) {
$resourceData['relationships'] = $relationshipsData;
}
$document = [];
if ($links) {
$document['links'] = $links;
}
$document['data'] = $resourceData;
if ($includedResourcesData) {
$document['included'] = $includedResourcesData;
}
return $document;
}
protected function getAttributes(object $object, ?string $format = null, array $context = []): array
{
return $this->getComponents($object, $format, $context)['attributes'];
}
/**
* @see http://jsonapi.org/format/#document-resource-object-linkage
*/
protected function normalizeRelation(ApiProperty $propertyMetadata, ?object $relatedObject, string $resourceClass, ?string $format, array $context): \ArrayObject|array|string|null
{
if (null !== $relatedObject) {
$iri = $this->iriConverter->getIriFromResource($relatedObject);
$context['iri'] = $iri;
if (!$this->tagCollector && isset($context['resources'])) {
$context['resources'][$iri] = $iri;
}
}
if (null === $relatedObject || isset($context['api_included'])) {
if (!$this->serializer instanceof NormalizerInterface) {
throw new LogicException(\sprintf('The injected serializer must be an instance of "%s".', NormalizerInterface::class));
}
$normalizedRelatedObject = $this->serializer->normalize($relatedObject, $format, $context);
if (!\is_string($normalizedRelatedObject) && !\is_array($normalizedRelatedObject) && !$normalizedRelatedObject instanceof \ArrayObject && null !== $normalizedRelatedObject) {
throw new UnexpectedValueException('Expected normalized relation to be an IRI, array, \ArrayObject or null');
}
return $normalizedRelatedObject;
}
$id = $iri;
if (!$this->useIriAsId) {
$identifiers = $this->identifiersExtractor->getIdentifiersFromItem($relatedObject);
$id = $this->getIdStringFromIdentifiers($identifiers);
}
$context['data'] = [
'data' => [
'type' => $this->getResourceShortName($resourceClass),
'id' => $id,
],
];
$context['iri'] = $iri;
$context['object'] = $relatedObject;
unset($context['property_metadata']);
unset($context['api_attribute']);
if ($this->tagCollector) {
$this->tagCollector->collect($context);
}
return $context['data'];
}
/**
* Gets JSON API components of the resource: attributes, relationships, meta and links.
*/
private function getComponents(object $object, ?string $format, array $context): array
{
$cacheKey = $this->getObjectClass($object).'-'.$context['cache_key'];
if (isset($this->componentsCache[$cacheKey])) {
return $this->componentsCache[$cacheKey];
}
$attributes = parent::getAttributes($object, $format, $context);
$options = $this->getFactoryOptions($context);
$components = [
'links' => [],
'relationships' => [],
'attributes' => [],
'meta' => [],
];
foreach ($attributes as $attribute) {
$propertyMetadata = $this
->propertyMetadataFactory
->create($context['resource_class'], $attribute, $options);
// Shared with the JSON Schema SchemaFactory so the documented split cannot drift from this output.
$relationships = $this->resourceLinkageResolver->getRelationships($propertyMetadata);
foreach ($relationships as [$className, $isCollection]) {
$relation = [
'name' => $attribute,
'type' => $this->getResourceShortName($className),
'cardinality' => $isCollection ? 'many' : 'one',
];
// if we specify the uriTemplate, generates its value for link definition
// @see ApiPlatform\Serializer\AbstractItemNormalizer:getAttributeValue logic for intentional duplicate content
if ($itemUriTemplate = $propertyMetadata->getUriTemplate()) {
$attributeValue = $this->propertyAccessor->getValue($object, $attribute);
$resourceClass = $this->resourceClassResolver->getResourceClass($attributeValue, $className);
$childContext = $this->createChildContext($context, $attribute, $format);
unset($childContext['iri'], $childContext['uri_variables'], $childContext['resource_class'], $childContext['operation']);
$operation = $this->resourceMetadataCollectionFactory->create($resourceClass)->getOperation(
operationName: $itemUriTemplate,
httpOperation: true
);
$components['links'][$attribute] = $this->iriConverter->getIriFromResource($object, UrlGeneratorInterface::ABS_PATH, $operation, $childContext);
}
$components['relationships'][] = $relation;
}
if ([] === $relationships) {
$components['attributes'][] = $attribute;
}
}
if (false !== $context['cache_key']) {
$this->componentsCache[$cacheKey] = $components;
}
return $components;
}
/**
* @throws UnexpectedValueException
*/
private function getPopulatedRelations(object $object, ?string $format, array $context, array $relationships): array
{
$data = [];
if (!isset($context['resource_class'])) {
return $data;
}
unset($context['api_included']);
foreach ($relationships as $relationshipDataArray) {
$relationshipName = $relationshipDataArray['name'];
$attributeValue = $this->getAttributeValue($object, $relationshipName, $format, $context);
if ($this->nameConverter) {
$relationshipName = $this->nameConverter->normalize($relationshipName, $context['resource_class'], self::FORMAT, $context);
}
if ('one' === $relationshipDataArray['cardinality']) {
$data[$relationshipName] = ['data' => null];
if (!$attributeValue) {
continue;
}
unset($attributeValue['data']['attributes']);
$data[$relationshipName] = $attributeValue;
continue;
}
$data[$relationshipName] = ['data' => []];
if (!$attributeValue) {
continue;
}
foreach ($attributeValue as $attributeValueElement) {
if (!isset($attributeValueElement['data'])) {
throw new UnexpectedValueException(\sprintf('The JSON API attribute \'%s\' must contain a "data" key.', $relationshipName));
}
unset($attributeValueElement['data']['attributes']);
$data[$relationshipName]['data'][] = $attributeValueElement['data'];
}
}
return $data;
}
private function getRelatedResources(object $object, ?string $format, array $context, array $relationships): array
{
if (!isset($context['api_included'])) {
return [];
}
$included = [];
foreach ($relationships as $relationshipDataArray) {
$relationshipName = $relationshipDataArray['name'];
if (!$this->shouldIncludeRelation($relationshipName, $context)) {
continue;
}
$relationContext = $context;
$relationContext['api_included'] = $this->getIncludedNestedResources($relationshipName, $context);
$attributeValue = $this->getAttributeValue($object, $relationshipName, $format, $relationContext);
if (!$attributeValue) {
continue;
}
$attributeValues = $attributeValue;
if ('one' === $relationshipDataArray['cardinality']) {
$attributeValues = [$attributeValue];
}
foreach ($attributeValues as $attributeValueElement) {
if (isset($attributeValueElement['data'])) {
$this->addIncluded($attributeValueElement['data'], $included, $context);
if (isset($attributeValueElement['included']) && \is_array($attributeValueElement['included'])) {
foreach ($attributeValueElement['included'] as $include) {
$this->addIncluded($include, $included, $context);
}
}
}
}
}
return $included;
}
private function addIncluded(array $data, array &$included, array &$context): void
{
$trackingKey = ($data['type'] ?? '').':'.($data['id'] ?? '');
if (isset($data['id']) && !isset($context['api_included_resources'][$trackingKey])) {
$included[] = $data;
$context['api_included_resources'][$trackingKey] = true;
}
}
private function shouldIncludeRelation(string $relationshipName, array $context): bool
{
$normalizedName = $this->nameConverter ? $this->nameConverter->normalize($relationshipName, $context['resource_class'], self::FORMAT, $context) : $relationshipName;
return \in_array($normalizedName, $context['api_included'], true) || \count($this->getIncludedNestedResources($relationshipName, $context)) > 0;
}
private function getIncludedNestedResources(string $relationshipName, array $context): array
{
$normalizedName = $this->nameConverter ? $this->nameConverter->normalize($relationshipName, $context['resource_class'], self::FORMAT, $context) : $relationshipName;
$filtered = array_filter($context['api_included'] ?? [], static fn (string $included): bool => str_starts_with($included, $normalizedName.'.'));
return array_map(static fn (string $nested): string => substr($nested, strpos($nested, '.') + 1), $filtered);
}
private function getIdStringFromIdentifiers(array $identifiers): string
{
if (1 === \count($identifiers)) {
return (string) array_values($identifiers)[0];
}
return CompositeIdentifierParser::stringify($identifiers);
}
private function getResourceShortName(string $resourceClass): string
{
if ($this->resourceClassResolver->isResourceClass($resourceClass)) {
$resourceMetadata = $this->resourceMetadataCollectionFactory->create($resourceClass);
return $resourceMetadata->getOperation()->getShortName();
}
return (new \ReflectionClass($resourceClass))->getShortName();
}
}