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

api-platform / core / 3713134090

pending completion
3713134090

Pull #5254

github

GitHub
Merge b2ec54b3c into ac711530f
Pull Request #5254: [OpenApi] Add ApiResource::openapi and deprecate openapiContext

197 of 197 new or added lines in 5 files covered. (100.0%)

10372 of 12438 relevant lines covered (83.39%)

11.97 hits per line

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

49.71
/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;
17
use ApiPlatform\Api\ResourceClassResolverInterface;
18
use ApiPlatform\Api\UrlGeneratorInterface;
19
use ApiPlatform\Exception\ItemNotFoundException;
20
use ApiPlatform\Metadata\ApiProperty;
21
use ApiPlatform\Metadata\Property\Factory\PropertyMetadataFactoryInterface;
22
use ApiPlatform\Metadata\Property\Factory\PropertyNameCollectionFactoryInterface;
23
use ApiPlatform\Metadata\Resource\Factory\ResourceMetadataCollectionFactoryInterface;
24
use ApiPlatform\Serializer\AbstractItemNormalizer;
25
use ApiPlatform\Serializer\CacheKeyTrait;
26
use ApiPlatform\Serializer\ContextTrait;
27
use ApiPlatform\Symfony\Security\ResourceAccessCheckerInterface;
28
use ApiPlatform\Util\ClassInfoTrait;
29
use Symfony\Component\PropertyAccess\PropertyAccessorInterface;
30
use Symfony\Component\Serializer\Exception\LogicException;
31
use Symfony\Component\Serializer\Exception\NotNormalizableValueException;
32
use Symfony\Component\Serializer\Exception\RuntimeException;
33
use Symfony\Component\Serializer\Exception\UnexpectedValueException;
34
use Symfony\Component\Serializer\Mapping\Factory\ClassMetadataFactoryInterface;
35
use Symfony\Component\Serializer\NameConverter\NameConverterInterface;
36
use Symfony\Component\Serializer\Normalizer\NormalizerInterface;
37

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

51
    public const FORMAT = 'jsonapi';
52

53
    private array $componentsCache = [];
54

55
    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)
56
    {
57
        parent::__construct($propertyNameCollectionFactory, $propertyMetadataFactory, $iriConverter, $resourceClassResolver, $propertyAccessor, $nameConverter, $classMetadataFactory, $defaultContext, $resourceMetadataCollectionFactory, $resourceAccessChecker);
34✔
58
    }
59

60
    /**
61
     * {@inheritdoc}
62
     */
63
    public function supportsNormalization(mixed $data, string $format = null, array $context = []): bool
64
    {
65
        return self::FORMAT === $format && parent::supportsNormalization($data, $format, $context);
13✔
66
    }
67

68
    /**
69
     * {@inheritdoc}
70
     */
71
    public function normalize(mixed $object, string $format = null, array $context = []): array|string|int|float|bool|\ArrayObject|null
72
    {
73
        $resourceClass = $this->getObjectClass($object);
3✔
74
        if ($this->getOutputClass($context)) {
3✔
75
            return parent::normalize($object, $format, $context);
×
76
        }
77

78
        if (!isset($context['cache_key'])) {
3✔
79
            $context['cache_key'] = $this->getCacheKey($format, $context);
3✔
80
        }
81

82
        if ($this->resourceClassResolver->isResourceClass($resourceClass)) {
3✔
83
            $resourceClass = $this->resourceClassResolver->getResourceClass($object, $context['resource_class'] ?? null);
3✔
84
        }
85

86
        if (($operation = $context['operation'] ?? null) && method_exists($operation, 'getItemUriTemplate')) {
3✔
87
            $context['item_uri_template'] = $operation->getItemUriTemplate();
×
88
        }
89

90
        $context = $this->initContext($resourceClass, $context);
3✔
91
        $iri = $this->iriConverter->getIriFromResource($object, UrlGeneratorInterface::ABS_PATH, $context['operation'] ?? null, $context);
3✔
92
        $context['iri'] = $iri;
3✔
93
        $context['api_normalize'] = true;
3✔
94

95
        $data = parent::normalize($object, $format, $context);
3✔
96
        if (!\is_array($data)) {
2✔
97
            return $data;
1✔
98
        }
99

100
        // Get and populate relations
101
        $allRelationshipsData = $this->getComponents($object, $format, $context)['relationships'];
1✔
102
        $populatedRelationContext = $context;
1✔
103
        $relationshipsData = $this->getPopulatedRelations($object, $format, $populatedRelationContext, $allRelationshipsData);
1✔
104

105
        // Do not include primary resources
106
        $context['api_included_resources'] = [$context['iri']];
1✔
107

108
        $includedResourcesData = $this->getRelatedResources($object, $format, $context, $allRelationshipsData);
1✔
109

110
        $resourceData = [
1✔
111
            'id' => $context['iri'],
1✔
112
            'type' => $this->getResourceShortName($resourceClass),
1✔
113
        ];
1✔
114

115
        if ($data) {
1✔
116
            $resourceData['attributes'] = $data;
1✔
117
        }
118

119
        if ($relationshipsData) {
1✔
120
            $resourceData['relationships'] = $relationshipsData;
×
121
        }
122

123
        $document = ['data' => $resourceData];
1✔
124

125
        if ($includedResourcesData) {
1✔
126
            $document['included'] = $includedResourcesData;
×
127
        }
128

129
        return $document;
1✔
130
    }
131

132
    /**
133
     * {@inheritdoc}
134
     */
135
    public function supportsDenormalization(mixed $data, string $type, string $format = null, array $context = []): bool
136
    {
137
        return self::FORMAT === $format && parent::supportsDenormalization($data, $type, $format, $context);
3✔
138
    }
139

140
    /**
141
     * {@inheritdoc}
142
     *
143
     * @throws NotNormalizableValueException
144
     */
145
    public function denormalize(mixed $data, string $class, string $format = null, array $context = []): mixed
146
    {
147
        // Avoid issues with proxies if we populated the object
148
        if (!isset($context[self::OBJECT_TO_POPULATE]) && isset($data['data']['id'])) {
5✔
149
            if (true !== ($context['api_allow_update'] ?? true)) {
1✔
150
                throw new NotNormalizableValueException('Update is not allowed for this operation.');
1✔
151
            }
152

153
            $context[self::OBJECT_TO_POPULATE] = $this->iriConverter->getResourceFromIri(
×
154
                $data['data']['id'],
×
155
                $context + ['fetch_data' => false]
×
156
            );
×
157
        }
158

159
        // Merge attributes and relationships, into format expected by the parent normalizer
160
        $dataToDenormalize = array_merge(
4✔
161
            $data['data']['attributes'] ?? [],
4✔
162
            $data['data']['relationships'] ?? []
4✔
163
        );
4✔
164

165
        return parent::denormalize(
4✔
166
            $dataToDenormalize,
4✔
167
            $class,
4✔
168
            $format,
4✔
169
            $context
4✔
170
        );
4✔
171
    }
172

173
    /**
174
     * {@inheritdoc}
175
     */
176
    protected function getAttributes(object $object, ?string $format = null, array $context = []): array
177
    {
178
        return $this->getComponents($object, $format, $context)['attributes'];
2✔
179
    }
180

181
    /**
182
     * {@inheritdoc}
183
     */
184
    protected function setAttributeValue(object $object, string $attribute, mixed $value, string $format = null, array $context = []): void
185
    {
186
        parent::setAttributeValue($object, $attribute, \is_array($value) && \array_key_exists('data', $value) ? $value['data'] : $value, $format, $context);
4✔
187
    }
188

189
    /**
190
     * {@inheritdoc}
191
     *
192
     * @see http://jsonapi.org/format/#document-resource-object-linkage
193
     *
194
     * @throws RuntimeException
195
     * @throws NotNormalizableValueException
196
     */
197
    protected function denormalizeRelation(string $attributeName, ApiProperty $propertyMetadata, string $className, mixed $value, ?string $format, array $context): object
198
    {
199
        if (!\is_array($value) || !isset($value['id'], $value['type'])) {
2✔
200
            throw new NotNormalizableValueException('Only resource linkage supported currently, see: http://jsonapi.org/format/#document-resource-object-linkage.');
1✔
201
        }
202

203
        try {
204
            return $this->iriConverter->getResourceFromIri($value['id'], $context + ['fetch_data' => true]);
1✔
205
        } catch (ItemNotFoundException $e) {
×
206
            throw new RuntimeException($e->getMessage(), $e->getCode(), $e);
×
207
        }
208
    }
209

210
    /**
211
     * {@inheritdoc}
212
     *
213
     * @see http://jsonapi.org/format/#document-resource-object-linkage
214
     */
215
    protected function normalizeRelation(ApiProperty $propertyMetadata, ?object $relatedObject, string $resourceClass, ?string $format, array $context): \ArrayObject|array|string|null
216
    {
217
        if (null !== $relatedObject) {
×
218
            $iri = $this->iriConverter->getIriFromResource($relatedObject);
×
219
            $context['iri'] = $iri;
×
220

221
            if (isset($context['resources'])) {
×
222
                $context['resources'][$iri] = $iri;
×
223
            }
224
        }
225

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

231
            $normalizedRelatedObject = $this->serializer->normalize($relatedObject, $format, $context);
×
232
            // @phpstan-ignore-next-line throwing an explicit exception helps debugging
233
            if (!\is_string($normalizedRelatedObject) && !\is_array($normalizedRelatedObject) && !$normalizedRelatedObject instanceof \ArrayObject && null !== $normalizedRelatedObject) {
×
234
                throw new UnexpectedValueException('Expected normalized relation to be an IRI, array, \ArrayObject or null');
×
235
            }
236

237
            return $normalizedRelatedObject;
×
238
        }
239

240
        return [
×
241
            'data' => [
×
242
                'type' => $this->getResourceShortName($resourceClass),
×
243
                'id' => $iri,
×
244
            ],
×
245
        ];
×
246
    }
247

248
    /**
249
     * {@inheritdoc}
250
     */
251
    protected function isAllowedAttribute(object|string $classOrObject, string $attribute, string $format = null, array $context = []): bool
252
    {
253
        return preg_match('/^\\w[-\\w_]*$/', $attribute) && parent::isAllowedAttribute($classOrObject, $attribute, $format, $context);
6✔
254
    }
255

256
    /**
257
     * Gets JSON API components of the resource: attributes, relationships, meta and links.
258
     */
259
    private function getComponents(object $object, ?string $format, array $context): array
260
    {
261
        $cacheKey = $this->getObjectClass($object).'-'.$context['cache_key'];
2✔
262

263
        if (isset($this->componentsCache[$cacheKey])) {
2✔
264
            return $this->componentsCache[$cacheKey];
1✔
265
        }
266

267
        $attributes = parent::getAttributes($object, $format, $context);
2✔
268

269
        $options = $this->getFactoryOptions($context);
2✔
270

271
        $components = [
2✔
272
            'links' => [],
2✔
273
            'relationships' => [],
2✔
274
            'attributes' => [],
2✔
275
            'meta' => [],
2✔
276
        ];
2✔
277

278
        foreach ($attributes as $attribute) {
2✔
279
            $propertyMetadata = $this
2✔
280
                ->propertyMetadataFactory
2✔
281
                ->create($context['resource_class'], $attribute, $options);
2✔
282

283
            // TODO: 3.0 support multiple types, default value of types will be [] instead of null
284
            $type = $propertyMetadata->getBuiltinTypes()[0] ?? null;
2✔
285
            $isOne = $isMany = false;
2✔
286

287
            if (null !== $type) {
2✔
288
                if ($type->isCollection()) {
×
289
                    $collectionValueType = $type->getCollectionValueTypes()[0] ?? null;
×
290
                    $isMany = $collectionValueType && ($className = $collectionValueType->getClassName()) && $this->resourceClassResolver->isResourceClass($className);
×
291
                } else {
292
                    $isOne = ($className = $type->getClassName()) && $this->resourceClassResolver->isResourceClass($className);
×
293
                }
294
            }
295

296
            if (!isset($className) || !$isOne && !$isMany) {
2✔
297
                $components['attributes'][] = $attribute;
2✔
298

299
                continue;
2✔
300
            }
301

302
            $relation = [
×
303
                'name' => $attribute,
×
304
                'type' => $this->getResourceShortName($className),
×
305
                'cardinality' => $isOne ? 'one' : 'many',
×
306
            ];
×
307

308
            $components['relationships'][] = $relation;
×
309
        }
310

311
        if (false !== $context['cache_key']) {
2✔
312
            $this->componentsCache[$cacheKey] = $components;
2✔
313
        }
314

315
        return $components;
2✔
316
    }
317

318
    /**
319
     * Populates relationships keys.
320
     *
321
     * @throws UnexpectedValueException
322
     */
323
    private function getPopulatedRelations(object $object, ?string $format, array $context, array $relationships): array
324
    {
325
        $data = [];
1✔
326

327
        if (!isset($context['resource_class'])) {
1✔
328
            return $data;
×
329
        }
330

331
        unset($context['api_included']);
1✔
332
        foreach ($relationships as $relationshipDataArray) {
1✔
333
            $relationshipName = $relationshipDataArray['name'];
×
334

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

337
            if ($this->nameConverter) {
×
338
                $relationshipName = $this->nameConverter->normalize($relationshipName, $context['resource_class'], self::FORMAT, $context);
×
339
            }
340

341
            if (!$attributeValue) {
×
342
                continue;
×
343
            }
344

345
            $data[$relationshipName] = [
×
346
                'data' => [],
×
347
            ];
×
348

349
            // Many to one relationship
350
            if ('one' === $relationshipDataArray['cardinality']) {
×
351
                unset($attributeValue['data']['attributes']);
×
352
                $data[$relationshipName] = $attributeValue;
×
353

354
                continue;
×
355
            }
356

357
            // Many to many relationship
358
            foreach ($attributeValue as $attributeValueElement) {
×
359
                if (!isset($attributeValueElement['data'])) {
×
360
                    throw new UnexpectedValueException(sprintf('The JSON API attribute \'%s\' must contain a "data" key.', $relationshipName));
×
361
                }
362
                unset($attributeValueElement['data']['attributes']);
×
363
                $data[$relationshipName]['data'][] = $attributeValueElement['data'];
×
364
            }
365
        }
366

367
        return $data;
1✔
368
    }
369

370
    /**
371
     * Populates included keys.
372
     */
373
    private function getRelatedResources(object $object, ?string $format, array $context, array $relationships): array
374
    {
375
        if (!isset($context['api_included'])) {
1✔
376
            return [];
1✔
377
        }
378

379
        $included = [];
×
380
        foreach ($relationships as $relationshipDataArray) {
×
381
            $relationshipName = $relationshipDataArray['name'];
×
382

383
            if (!$this->shouldIncludeRelation($relationshipName, $context)) {
×
384
                continue;
×
385
            }
386

387
            $relationContext = $context;
×
388
            $relationContext['api_included'] = $this->getIncludedNestedResources($relationshipName, $context);
×
389

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

392
            if (!$attributeValue) {
×
393
                continue;
×
394
            }
395

396
            // Many to many relationship
397
            $attributeValues = $attributeValue;
×
398
            // Many to one relationship
399
            if ('one' === $relationshipDataArray['cardinality']) {
×
400
                $attributeValues = [$attributeValue];
×
401
            }
402

403
            foreach ($attributeValues as $attributeValueElement) {
×
404
                if (isset($attributeValueElement['data'])) {
×
405
                    $this->addIncluded($attributeValueElement['data'], $included, $context);
×
406
                    if (isset($attributeValueElement['included']) && \is_array($attributeValueElement['included'])) {
×
407
                        foreach ($attributeValueElement['included'] as $include) {
×
408
                            $this->addIncluded($include, $included, $context);
×
409
                        }
410
                    }
411
                }
412
            }
413
        }
414

415
        return $included;
×
416
    }
417

418
    /**
419
     * Add data to included array if it's not already included.
420
     */
421
    private function addIncluded(array $data, array &$included, array &$context): void
422
    {
423
        if (isset($data['id']) && !\in_array($data['id'], $context['api_included_resources'], true)) {
×
424
            $included[] = $data;
×
425
            // Track already included resources
426
            $context['api_included_resources'][] = $data['id'];
×
427
        }
428
    }
429

430
    /**
431
     * Figures out if the relationship is in the api_included hash or has included nested resources (path).
432
     */
433
    private function shouldIncludeRelation(string $relationshipName, array $context): bool
434
    {
435
        $normalizedName = $this->nameConverter ? $this->nameConverter->normalize($relationshipName, $context['resource_class'], self::FORMAT, $context) : $relationshipName;
×
436

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

440
    /**
441
     * Returns the names of the nested resources from a path relationship.
442
     */
443
    private function getIncludedNestedResources(string $relationshipName, array $context): array
444
    {
445
        $normalizedName = $this->nameConverter ? $this->nameConverter->normalize($relationshipName, $context['resource_class'], self::FORMAT, $context) : $relationshipName;
×
446

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

449
        return array_map(static fn (string $nested): string => substr($nested, strpos($nested, '.') + 1), $filtered);
×
450
    }
451

452
    // TODO: this code is similar to the one used in JsonLd
453
    private function getResourceShortName(string $resourceClass): string
454
    {
455
        if ($this->resourceClassResolver->isResourceClass($resourceClass)) {
1✔
456
            $resourceMetadata = $this->resourceMetadataCollectionFactory->create($resourceClass);
1✔
457

458
            return $resourceMetadata->getOperation()->getShortName();
1✔
459
        }
460

461
        return (new \ReflectionClass($resourceClass))->getShortName();
×
462
    }
463
}
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