• Home
  • Features
  • Pricing
  • Docs
  • Announcements
  • Sign In

api-platform / core / 7328478858

26 Dec 2023 09:45AM UTC coverage: 37.33% (+0.3%) from 37.046%
7328478858

push

github

web-flow
feat(serializer): collect cache tags using a TagCollector (#5758)

* feat(serializer): collect cache tags using a TagCollector

* simplify function signature

* fix bug in JsonApi normalizer

* minor changes as per latest review

* disable new tests for Symfony lowest

* cs

---------

Co-authored-by: Antoine Bluchet <soyuka@users.noreply.github.com>

31 of 44 new or added lines in 4 files covered. (70.45%)

3 existing lines in 1 file now uncovered.

10359 of 27750 relevant lines covered (37.33%)

28.57 hits per line

Source File
Press 'n' to go to next uncovered line, 'b' for previous

41.26
/src/JsonApi/Serializer/ItemNormalizer.php
1
<?php
2

3
/*
4
 * This file is part of the API Platform project.
5
 *
6
 * (c) Kévin Dunglas <dunglas@gmail.com>
7
 *
8
 * For the full copyright and license information, please view the LICENSE
9
 * file that was distributed with this source code.
10
 */
11

12
declare(strict_types=1);
13

14
namespace ApiPlatform\JsonApi\Serializer;
15

16
use ApiPlatform\Api\IriConverterInterface as LegacyIriConverterInterface;
17
use ApiPlatform\Api\ResourceClassResolverInterface as LegacyResourceClassResolverInterface;
18
use ApiPlatform\Exception\ItemNotFoundException;
19
use ApiPlatform\Metadata\ApiProperty;
20
use ApiPlatform\Metadata\IriConverterInterface;
21
use ApiPlatform\Metadata\Property\Factory\PropertyMetadataFactoryInterface;
22
use ApiPlatform\Metadata\Property\Factory\PropertyNameCollectionFactoryInterface;
23
use ApiPlatform\Metadata\Resource\Factory\ResourceMetadataCollectionFactoryInterface;
24
use ApiPlatform\Metadata\ResourceClassResolverInterface;
25
use ApiPlatform\Metadata\UrlGeneratorInterface;
26
use ApiPlatform\Metadata\Util\ClassInfoTrait;
27
use ApiPlatform\Serializer\AbstractItemNormalizer;
28
use ApiPlatform\Serializer\CacheKeyTrait;
29
use ApiPlatform\Serializer\ContextTrait;
30
use ApiPlatform\Serializer\TagCollectorInterface;
31
use ApiPlatform\Symfony\Security\ResourceAccessCheckerInterface;
32
use Symfony\Component\ErrorHandler\Exception\FlattenException;
33
use Symfony\Component\PropertyAccess\PropertyAccessorInterface;
34
use Symfony\Component\Serializer\Exception\LogicException;
35
use Symfony\Component\Serializer\Exception\NotNormalizableValueException;
36
use Symfony\Component\Serializer\Exception\RuntimeException;
37
use Symfony\Component\Serializer\Exception\UnexpectedValueException;
38
use Symfony\Component\Serializer\Mapping\Factory\ClassMetadataFactoryInterface;
39
use Symfony\Component\Serializer\NameConverter\NameConverterInterface;
40
use Symfony\Component\Serializer\Normalizer\NormalizerInterface;
41

42
/**
43
 * Converts between objects and array.
44
 *
45
 * @author Kévin Dunglas <dunglas@gmail.com>
46
 * @author Amrouche Hamza <hamza.simperfit@gmail.com>
47
 * @author Baptiste Meyer <baptiste.meyer@gmail.com>
48
 */
49
final class ItemNormalizer extends AbstractItemNormalizer
50
{
51
    use CacheKeyTrait;
52
    use ClassInfoTrait;
53
    use ContextTrait;
54

55
    public const FORMAT = 'jsonapi';
56

57
    private array $componentsCache = [];
58

59
    public function __construct(PropertyNameCollectionFactoryInterface $propertyNameCollectionFactory, PropertyMetadataFactoryInterface $propertyMetadataFactory, IriConverterInterface|LegacyIriConverterInterface $iriConverter, ResourceClassResolverInterface|LegacyResourceClassResolverInterface $resourceClassResolver, PropertyAccessorInterface $propertyAccessor = null, NameConverterInterface $nameConverter = null, ClassMetadataFactoryInterface $classMetadataFactory = null, array $defaultContext = [], ResourceMetadataCollectionFactoryInterface $resourceMetadataCollectionFactory = null, ResourceAccessCheckerInterface $resourceAccessChecker = null, protected ?TagCollectorInterface $tagCollector = null)
60
    {
61
        parent::__construct($propertyNameCollectionFactory, $propertyMetadataFactory, $iriConverter, $resourceClassResolver, $propertyAccessor, $nameConverter, $classMetadataFactory, $defaultContext, $resourceMetadataCollectionFactory, $resourceAccessChecker, $tagCollector);
148✔
62
    }
63

64
    /**
65
     * {@inheritdoc}
66
     */
67
    public function supportsNormalization(mixed $data, string $format = null, array $context = []): bool
68
    {
69
        return self::FORMAT === $format && parent::supportsNormalization($data, $format, $context) && !($data instanceof \Exception || $data instanceof FlattenException);
×
70
    }
71

72
    public function getSupportedTypes($format): array
73
    {
74
        return self::FORMAT === $format ? parent::getSupportedTypes($format) : [];
72✔
75
    }
76

77
    /**
78
     * {@inheritdoc}
79
     */
80
    public function normalize(mixed $object, string $format = null, array $context = []): array|string|int|float|bool|\ArrayObject|null
81
    {
82
        $resourceClass = $this->getObjectClass($object);
12✔
83
        if ($this->getOutputClass($context)) {
12✔
84
            return parent::normalize($object, $format, $context);
×
85
        }
86

87
        if ($this->resourceClassResolver->isResourceClass($resourceClass)) {
12✔
88
            $resourceClass = $this->resourceClassResolver->getResourceClass($object, $context['resource_class'] ?? null);
12✔
89
        }
90

91
        if (($operation = $context['operation'] ?? null) && method_exists($operation, 'getItemUriTemplate')) {
12✔
92
            $context['item_uri_template'] = $operation->getItemUriTemplate();
×
93
        }
94

95
        $context = $this->initContext($resourceClass, $context);
12✔
96
        $iri = $this->iriConverter->getIriFromResource($object, UrlGeneratorInterface::ABS_PATH, $context['operation'] ?? null, $context);
12✔
97
        $context['iri'] = $iri;
12✔
98
        $context['api_normalize'] = true;
12✔
99

100
        if (!isset($context['cache_key'])) {
12✔
101
            $context['cache_key'] = $this->getCacheKey($format, $context);
12✔
102
        }
103

104
        $data = parent::normalize($object, $format, $context);
12✔
105
        if (!\is_array($data)) {
8✔
106
            return $data;
4✔
107
        }
108

109
        // Get and populate relations
110
        ['relationships' => $allRelationshipsData, 'links' => $links] = $this->getComponents($object, $format, $context);
4✔
111
        $populatedRelationContext = $context;
4✔
112
        $relationshipsData = $this->getPopulatedRelations($object, $format, $populatedRelationContext, $allRelationshipsData);
4✔
113

114
        // Do not include primary resources
115
        $context['api_included_resources'] = [$context['iri']];
4✔
116

117
        $includedResourcesData = $this->getRelatedResources($object, $format, $context, $allRelationshipsData);
4✔
118

119
        $resourceData = [
4✔
120
            'id' => $context['iri'],
4✔
121
            'type' => $this->getResourceShortName($resourceClass),
4✔
122
        ];
4✔
123

124
        if ($data) {
4✔
125
            $resourceData['attributes'] = $data;
4✔
126
        }
127

128
        if ($relationshipsData) {
4✔
129
            $resourceData['relationships'] = $relationshipsData;
×
130
        }
131

132
        $document = [];
4✔
133

134
        if ($links) {
4✔
135
            $document['links'] = $links;
×
136
        }
137

138
        $document['data'] = $resourceData;
4✔
139

140
        if ($includedResourcesData) {
4✔
141
            $document['included'] = $includedResourcesData;
×
142
        }
143

144
        return $document;
4✔
145
    }
146

147
    /**
148
     * {@inheritdoc}
149
     */
150
    public function supportsDenormalization(mixed $data, string $type, string $format = null, array $context = []): bool
151
    {
152
        return self::FORMAT === $format && parent::supportsDenormalization($data, $type, $format, $context);
×
153
    }
154

155
    /**
156
     * {@inheritdoc}
157
     *
158
     * @throws NotNormalizableValueException
159
     */
160
    public function denormalize(mixed $data, string $class, string $format = null, array $context = []): mixed
161
    {
162
        // Avoid issues with proxies if we populated the object
163
        if (!isset($context[self::OBJECT_TO_POPULATE]) && isset($data['data']['id'])) {
20✔
164
            if (true !== ($context['api_allow_update'] ?? true)) {
4✔
165
                throw new NotNormalizableValueException('Update is not allowed for this operation.');
4✔
166
            }
167

168
            $context[self::OBJECT_TO_POPULATE] = $this->iriConverter->getResourceFromIri(
×
169
                $data['data']['id'],
×
170
                $context + ['fetch_data' => false]
×
171
            );
×
172
        }
173

174
        // Merge attributes and relationships, into format expected by the parent normalizer
175
        $dataToDenormalize = array_merge(
16✔
176
            $data['data']['attributes'] ?? [],
16✔
177
            $data['data']['relationships'] ?? []
16✔
178
        );
16✔
179

180
        return parent::denormalize(
16✔
181
            $dataToDenormalize,
16✔
182
            $class,
16✔
183
            $format,
16✔
184
            $context
16✔
185
        );
16✔
186
    }
187

188
    /**
189
     * {@inheritdoc}
190
     */
191
    protected function getAttributes(object $object, string $format = null, array $context = []): array
192
    {
193
        return $this->getComponents($object, $format, $context)['attributes'];
8✔
194
    }
195

196
    /**
197
     * {@inheritdoc}
198
     */
199
    protected function setAttributeValue(object $object, string $attribute, mixed $value, string $format = null, array $context = []): void
200
    {
201
        parent::setAttributeValue($object, $attribute, \is_array($value) && \array_key_exists('data', $value) ? $value['data'] : $value, $format, $context);
16✔
202
    }
203

204
    /**
205
     * {@inheritdoc}
206
     *
207
     * @see http://jsonapi.org/format/#document-resource-object-linkage
208
     *
209
     * @throws RuntimeException
210
     * @throws UnexpectedValueException
211
     */
212
    protected function denormalizeRelation(string $attributeName, ApiProperty $propertyMetadata, string $className, mixed $value, ?string $format, array $context): ?object
213
    {
214
        if (!\is_array($value) || !isset($value['id'], $value['type'])) {
8✔
215
            throw new UnexpectedValueException('Only resource linkage supported currently, see: http://jsonapi.org/format/#document-resource-object-linkage.');
4✔
216
        }
217

218
        try {
219
            return $this->iriConverter->getResourceFromIri($value['id'], $context + ['fetch_data' => true]);
4✔
220
        } catch (ItemNotFoundException $e) {
×
221
            if (!isset($context['not_normalizable_value_exceptions'])) {
×
222
                throw new RuntimeException($e->getMessage(), $e->getCode(), $e);
×
223
            }
224
            $context['not_normalizable_value_exceptions'][] = NotNormalizableValueException::createForUnexpectedDataType(
×
225
                $e->getMessage(),
×
226
                $value,
×
227
                [$className],
×
228
                $context['deserialization_path'] ?? null,
×
229
                true,
×
230
                $e->getCode(),
×
231
                $e
×
232
            );
×
233

234
            return null;
×
235
        }
236
    }
237

238
    /**
239
     * {@inheritdoc}
240
     *
241
     * @see http://jsonapi.org/format/#document-resource-object-linkage
242
     */
243
    protected function normalizeRelation(ApiProperty $propertyMetadata, ?object $relatedObject, string $resourceClass, ?string $format, array $context): \ArrayObject|array|string|null
244
    {
245
        if (null !== $relatedObject) {
×
246
            $iri = $this->iriConverter->getIriFromResource($relatedObject);
×
247
            $context['iri'] = $iri;
×
248

NEW
249
            if (!$this->tagCollector && isset($context['resources'])) {
×
250
                $context['resources'][$iri] = $iri;
×
251
            }
252
        }
253

254
        if (null === $relatedObject || isset($context['api_included'])) {
×
255
            if (!$this->serializer instanceof NormalizerInterface) {
×
256
                throw new LogicException(sprintf('The injected serializer must be an instance of "%s".', NormalizerInterface::class));
×
257
            }
258

259
            $normalizedRelatedObject = $this->serializer->normalize($relatedObject, $format, $context);
×
260
            if (!\is_string($normalizedRelatedObject) && !\is_array($normalizedRelatedObject) && !$normalizedRelatedObject instanceof \ArrayObject && null !== $normalizedRelatedObject) {
×
261
                throw new UnexpectedValueException('Expected normalized relation to be an IRI, array, \ArrayObject or null');
×
262
            }
263

264
            return $normalizedRelatedObject;
×
265
        }
266

NEW
267
        $context['data'] = [
×
268
            'data' => [
×
269
                'type' => $this->getResourceShortName($resourceClass),
×
270
                'id' => $iri,
×
271
            ],
×
272
        ];
×
273

NEW
274
        $context['iri'] = $iri;
×
NEW
275
        $context['object'] = $relatedObject;
×
NEW
276
        unset($context['property_metadata']);
×
NEW
277
        unset($context['api_attribute']);
×
278

NEW
279
        if ($this->tagCollector) {
×
NEW
280
            $this->tagCollector->collect($context);
×
281
        }
282

NEW
283
        return $context['data'];
×
284
    }
285

286
    /**
287
     * {@inheritdoc}
288
     */
289
    protected function isAllowedAttribute(object|string $classOrObject, string $attribute, string $format = null, array $context = []): bool
290
    {
291
        return preg_match('/^\\w[-\\w_]*$/', $attribute) && parent::isAllowedAttribute($classOrObject, $attribute, $format, $context);
24✔
292
    }
293

294
    /**
295
     * Gets JSON API components of the resource: attributes, relationships, meta and links.
296
     */
297
    private function getComponents(object $object, ?string $format, array $context): array
298
    {
299
        $cacheKey = $this->getObjectClass($object).'-'.$context['cache_key'];
8✔
300

301
        if (isset($this->componentsCache[$cacheKey])) {
8✔
302
            return $this->componentsCache[$cacheKey];
4✔
303
        }
304

305
        $attributes = parent::getAttributes($object, $format, $context);
8✔
306

307
        $options = $this->getFactoryOptions($context);
8✔
308

309
        $components = [
8✔
310
            'links' => [],
8✔
311
            'relationships' => [],
8✔
312
            'attributes' => [],
8✔
313
            'meta' => [],
8✔
314
        ];
8✔
315

316
        foreach ($attributes as $attribute) {
8✔
317
            $propertyMetadata = $this
8✔
318
                ->propertyMetadataFactory
8✔
319
                ->create($context['resource_class'], $attribute, $options);
8✔
320

321
            $types = $propertyMetadata->getBuiltinTypes() ?? [];
8✔
322

323
            // prevent declaring $attribute as attribute if it's already declared as relationship
324
            $isRelationship = false;
8✔
325

326
            foreach ($types as $type) {
8✔
327
                $isOne = $isMany = false;
×
328

329
                if ($type->isCollection()) {
×
330
                    $collectionValueType = $type->getCollectionValueTypes()[0] ?? null;
×
331
                    $isMany = $collectionValueType && ($className = $collectionValueType->getClassName()) && $this->resourceClassResolver->isResourceClass($className);
×
332
                } else {
333
                    $isOne = ($className = $type->getClassName()) && $this->resourceClassResolver->isResourceClass($className);
×
334
                }
335

336
                if (!isset($className) || !$isOne && !$isMany) {
×
337
                    // don't declare it as an attribute too quick: maybe the next type is a valid resource
338
                    continue;
×
339
                }
340

341
                $relation = [
×
342
                    'name' => $attribute,
×
343
                    'type' => $this->getResourceShortName($className),
×
344
                    'cardinality' => $isOne ? 'one' : 'many',
×
345
                ];
×
346

347
                // if we specify the uriTemplate, generates its value for link definition
348
                // @see ApiPlatform\Serializer\AbstractItemNormalizer:getAttributeValue logic for intentional duplicate content
349
                if ($itemUriTemplate = $propertyMetadata->getUriTemplate()) {
×
350
                    $attributeValue = $this->propertyAccessor->getValue($object, $attribute);
×
351
                    $resourceClass = $this->resourceClassResolver->getResourceClass($attributeValue, $className);
×
352
                    $childContext = $this->createChildContext($context, $attribute, $format);
×
353
                    unset($childContext['iri'], $childContext['uri_variables'], $childContext['resource_class'], $childContext['operation']);
×
354

355
                    $operation = $this->resourceMetadataCollectionFactory->create($resourceClass)->getOperation(
×
356
                        operationName: $itemUriTemplate,
×
357
                        httpOperation: true
×
358
                    );
×
359

360
                    $components['links'][$attribute] = $this->iriConverter->getIriFromResource($object, UrlGeneratorInterface::ABS_PATH, $operation, $childContext);
×
361
                }
362

363
                $components['relationships'][] = $relation;
×
364
                $isRelationship = true;
×
365
            }
366

367
            // if all types are not relationships, declare it as an attribute
368
            if (!$isRelationship) {
8✔
369
                $components['attributes'][] = $attribute;
8✔
370
            }
371
        }
372

373
        if (false !== $context['cache_key']) {
8✔
374
            $this->componentsCache[$cacheKey] = $components;
8✔
375
        }
376

377
        return $components;
8✔
378
    }
379

380
    /**
381
     * Populates relationships keys.
382
     *
383
     * @throws UnexpectedValueException
384
     */
385
    private function getPopulatedRelations(object $object, ?string $format, array $context, array $relationships): array
386
    {
387
        $data = [];
4✔
388

389
        if (!isset($context['resource_class'])) {
4✔
390
            return $data;
×
391
        }
392

393
        unset($context['api_included']);
4✔
394
        foreach ($relationships as $relationshipDataArray) {
4✔
395
            $relationshipName = $relationshipDataArray['name'];
×
396

397
            $attributeValue = $this->getAttributeValue($object, $relationshipName, $format, $context);
×
398

399
            if ($this->nameConverter) {
×
400
                $relationshipName = $this->nameConverter->normalize($relationshipName, $context['resource_class'], self::FORMAT, $context);
×
401
            }
402

403
            if (!$attributeValue) {
×
404
                continue;
×
405
            }
406

407
            $data[$relationshipName] = [
×
408
                'data' => [],
×
409
            ];
×
410

411
            // Many to one relationship
412
            if ('one' === $relationshipDataArray['cardinality']) {
×
413
                unset($attributeValue['data']['attributes']);
×
414
                $data[$relationshipName] = $attributeValue;
×
415

416
                continue;
×
417
            }
418

419
            // Many to many relationship
420
            foreach ($attributeValue as $attributeValueElement) {
×
421
                if (!isset($attributeValueElement['data'])) {
×
422
                    throw new UnexpectedValueException(sprintf('The JSON API attribute \'%s\' must contain a "data" key.', $relationshipName));
×
423
                }
424
                unset($attributeValueElement['data']['attributes']);
×
425
                $data[$relationshipName]['data'][] = $attributeValueElement['data'];
×
426
            }
427
        }
428

429
        return $data;
4✔
430
    }
431

432
    /**
433
     * Populates included keys.
434
     */
435
    private function getRelatedResources(object $object, ?string $format, array $context, array $relationships): array
436
    {
437
        if (!isset($context['api_included'])) {
4✔
438
            return [];
4✔
439
        }
440

441
        $included = [];
×
442
        foreach ($relationships as $relationshipDataArray) {
×
443
            $relationshipName = $relationshipDataArray['name'];
×
444

445
            if (!$this->shouldIncludeRelation($relationshipName, $context)) {
×
446
                continue;
×
447
            }
448

449
            $relationContext = $context;
×
450
            $relationContext['api_included'] = $this->getIncludedNestedResources($relationshipName, $context);
×
451

452
            $attributeValue = $this->getAttributeValue($object, $relationshipName, $format, $relationContext);
×
453

454
            if (!$attributeValue) {
×
455
                continue;
×
456
            }
457

458
            // Many to many relationship
459
            $attributeValues = $attributeValue;
×
460
            // Many to one relationship
461
            if ('one' === $relationshipDataArray['cardinality']) {
×
462
                $attributeValues = [$attributeValue];
×
463
            }
464

465
            foreach ($attributeValues as $attributeValueElement) {
×
466
                if (isset($attributeValueElement['data'])) {
×
467
                    $this->addIncluded($attributeValueElement['data'], $included, $context);
×
468
                    if (isset($attributeValueElement['included']) && \is_array($attributeValueElement['included'])) {
×
469
                        foreach ($attributeValueElement['included'] as $include) {
×
470
                            $this->addIncluded($include, $included, $context);
×
471
                        }
472
                    }
473
                }
474
            }
475
        }
476

477
        return $included;
×
478
    }
479

480
    /**
481
     * Add data to included array if it's not already included.
482
     */
483
    private function addIncluded(array $data, array &$included, array &$context): void
484
    {
485
        if (isset($data['id']) && !\in_array($data['id'], $context['api_included_resources'], true)) {
×
486
            $included[] = $data;
×
487
            // Track already included resources
488
            $context['api_included_resources'][] = $data['id'];
×
489
        }
490
    }
491

492
    /**
493
     * Figures out if the relationship is in the api_included hash or has included nested resources (path).
494
     */
495
    private function shouldIncludeRelation(string $relationshipName, array $context): bool
496
    {
497
        $normalizedName = $this->nameConverter ? $this->nameConverter->normalize($relationshipName, $context['resource_class'], self::FORMAT, $context) : $relationshipName;
×
498

499
        return \in_array($normalizedName, $context['api_included'], true) || \count($this->getIncludedNestedResources($relationshipName, $context)) > 0;
×
500
    }
501

502
    /**
503
     * Returns the names of the nested resources from a path relationship.
504
     */
505
    private function getIncludedNestedResources(string $relationshipName, array $context): array
506
    {
507
        $normalizedName = $this->nameConverter ? $this->nameConverter->normalize($relationshipName, $context['resource_class'], self::FORMAT, $context) : $relationshipName;
×
508

509
        $filtered = array_filter($context['api_included'] ?? [], static fn (string $included): bool => str_starts_with($included, $normalizedName.'.'));
×
510

511
        return array_map(static fn (string $nested): string => substr($nested, strpos($nested, '.') + 1), $filtered);
×
512
    }
513

514
    // TODO: this code is similar to the one used in JsonLd
515
    private function getResourceShortName(string $resourceClass): string
516
    {
517
        if ($this->resourceClassResolver->isResourceClass($resourceClass)) {
4✔
518
            $resourceMetadata = $this->resourceMetadataCollectionFactory->create($resourceClass);
4✔
519

520
            return $resourceMetadata->getOperation()->getShortName();
4✔
521
        }
522

523
        return (new \ReflectionClass($resourceClass))->getShortName();
×
524
    }
525
}
STATUS · Troubleshooting · Open an Issue · Sales · Support · CAREERS · ENTERPRISE · START FREE · SCHEDULE DEMO
ANNOUNCEMENTS · TWITTER · TOS & SLA · Supported CI Services · What's a CI service? · Automated Testing

© 2026 Coveralls, Inc