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

api-platform / core / 17054069864

18 Aug 2025 10:27PM UTC coverage: 21.952% (+0.2%) from 21.769%
17054069864

Pull #7151

github

web-flow
Merge 0da010d8d into 6491bfc7a
Pull Request #7151: fix: 7119 parameter array shape uses invalid syntax

11524 of 52497 relevant lines covered (21.95%)

11.86 hits per line

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

74.38
/src/Hal/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\Hal\Serializer;
15

16
use ApiPlatform\Metadata\IriConverterInterface;
17
use ApiPlatform\Metadata\Property\Factory\PropertyMetadataFactoryInterface;
18
use ApiPlatform\Metadata\Property\Factory\PropertyNameCollectionFactoryInterface;
19
use ApiPlatform\Metadata\Resource\Factory\ResourceMetadataCollectionFactoryInterface;
20
use ApiPlatform\Metadata\ResourceAccessCheckerInterface;
21
use ApiPlatform\Metadata\ResourceClassResolverInterface;
22
use ApiPlatform\Metadata\UrlGeneratorInterface;
23
use ApiPlatform\Metadata\Util\ClassInfoTrait;
24
use ApiPlatform\Metadata\Util\TypeHelper;
25
use ApiPlatform\Serializer\AbstractItemNormalizer;
26
use ApiPlatform\Serializer\CacheKeyTrait;
27
use ApiPlatform\Serializer\ContextTrait;
28
use ApiPlatform\Serializer\TagCollectorInterface;
29
use Symfony\Component\PropertyAccess\PropertyAccessorInterface;
30
use Symfony\Component\PropertyInfo\PropertyInfoExtractor;
31
use Symfony\Component\PropertyInfo\Type as LegacyType;
32
use Symfony\Component\Serializer\Exception\CircularReferenceException;
33
use Symfony\Component\Serializer\Exception\LogicException;
34
use Symfony\Component\Serializer\Exception\UnexpectedValueException;
35
use Symfony\Component\Serializer\Mapping\AttributeMetadataInterface;
36
use Symfony\Component\Serializer\Mapping\Factory\ClassMetadataFactoryInterface;
37
use Symfony\Component\Serializer\NameConverter\NameConverterInterface;
38
use Symfony\Component\Serializer\Normalizer\AbstractNormalizer;
39
use Symfony\Component\TypeInfo\Type;
40
use Symfony\Component\TypeInfo\Type\CollectionType;
41
use Symfony\Component\TypeInfo\Type\CompositeTypeInterface;
42
use Symfony\Component\TypeInfo\Type\ObjectType;
43

44
/**
45
 * Converts between objects and array including HAL metadata.
46
 *
47
 * @author Kévin Dunglas <dunglas@gmail.com>
48
 */
49
final class ItemNormalizer extends AbstractItemNormalizer
50
{
51
    use CacheKeyTrait;
52
    use ClassInfoTrait;
53
    use ContextTrait;
54

55
    public const FORMAT = 'jsonhal';
56

57
    protected const HAL_CIRCULAR_REFERENCE_LIMIT_COUNTERS = 'hal_circular_reference_limit_counters';
58

59
    private array $componentsCache = [];
60
    private array $attributesMetadataCache = [];
61

62
    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, ?TagCollectorInterface $tagCollector = null)
63
    {
64
        $defaultContext[AbstractNormalizer::CIRCULAR_REFERENCE_HANDLER] = function ($object): ?array {
310✔
65
            $iri = $this->iriConverter->getIriFromResource($object);
×
66
            if (null === $iri) {
×
67
                return null;
×
68
            }
69

70
            return ['_links' => ['self' => ['href' => $iri]]];
×
71
        };
310✔
72

73
        parent::__construct($propertyNameCollectionFactory, $propertyMetadataFactory, $iriConverter, $resourceClassResolver, $propertyAccessor, $nameConverter, $classMetadataFactory, $defaultContext, $resourceMetadataCollectionFactory, $resourceAccessChecker, $tagCollector);
310✔
74
    }
75

76
    /**
77
     * {@inheritdoc}
78
     */
79
    public function supportsNormalization(mixed $data, ?string $format = null, array $context = []): bool
80
    {
81
        return self::FORMAT === $format && parent::supportsNormalization($data, $format, $context);
18✔
82
    }
83

84
    /**
85
     * @param string|null $format
86
     */
87
    public function getSupportedTypes($format): array
88
    {
89
        return self::FORMAT === $format ? parent::getSupportedTypes($format) : [];
254✔
90
    }
91

92
    /**
93
     * {@inheritdoc}
94
     */
95
    public function normalize(mixed $object, ?string $format = null, array $context = []): array|string|int|float|bool|\ArrayObject|null
96
    {
97
        $resourceClass = $this->getObjectClass($object);
22✔
98
        if ($this->getOutputClass($context)) {
22✔
99
            return parent::normalize($object, $format, $context);
1✔
100
        }
101

102
        $previousResourceClass = $context['resource_class'] ?? null;
22✔
103
        if ($this->resourceClassResolver->isResourceClass($resourceClass) && (null === $previousResourceClass || $this->resourceClassResolver->isResourceClass($previousResourceClass))) {
22✔
104
            $resourceClass = $this->resourceClassResolver->getResourceClass($object, $previousResourceClass);
21✔
105
        }
106

107
        $context = $this->initContext($resourceClass, $context);
22✔
108

109
        $iri = $context['iri'] ??= $this->iriConverter->getIriFromResource($object, UrlGeneratorInterface::ABS_PATH, $context['operation'] ?? null, $context);
22✔
110
        $context['object'] = $object;
22✔
111
        $context['format'] = $format;
22✔
112
        $context['api_normalize'] = true;
22✔
113

114
        if (!isset($context['cache_key'])) {
22✔
115
            $context['cache_key'] = $this->getCacheKey($format, $context);
22✔
116
        }
117

118
        $data = parent::normalize($object, $format, $context);
22✔
119

120
        if (!\is_array($data)) {
22✔
121
            return $data;
×
122
        }
123

124
        $metadata = [
22✔
125
            '_links' => [
22✔
126
                'self' => [
22✔
127
                    'href' => $iri,
22✔
128
                ],
22✔
129
            ],
22✔
130
        ];
22✔
131
        $components = $this->getComponents($object, $format, $context);
22✔
132
        $metadata = $this->populateRelation($metadata, $object, $format, $context, $components, 'links');
22✔
133
        $metadata = $this->populateRelation($metadata, $object, $format, $context, $components, 'embedded');
22✔
134

135
        return $metadata + $data;
22✔
136
    }
137

138
    /**
139
     * {@inheritdoc}
140
     */
141
    public function supportsDenormalization(mixed $data, string $type, ?string $format = null, array $context = []): bool
142
    {
143
        // prevent the use of lower priority normalizers (e.g. serializer.normalizer.object) for this format
144
        return self::FORMAT === $format;
1✔
145
    }
146

147
    /**
148
     * {@inheritdoc}
149
     *
150
     * @throws LogicException
151
     */
152
    public function denormalize(mixed $data, string $type, ?string $format = null, array $context = []): never
153
    {
154
        throw new LogicException(\sprintf('%s is a read-only format.', self::FORMAT));
1✔
155
    }
156

157
    /**
158
     * {@inheritdoc}
159
     */
160
    protected function getAttributes(object $object, ?string $format = null, array $context = []): array
161
    {
162
        return $this->getComponents($object, $format, $context)['states'];
22✔
163
    }
164

165
    /**
166
     * Gets HAL components of the resource: states, links and embedded.
167
     */
168
    private function getComponents(object $object, ?string $format, array $context): array
169
    {
170
        $cacheKey = $this->getObjectClass($object).'-'.$context['cache_key'];
22✔
171

172
        if (isset($this->componentsCache[$cacheKey])) {
22✔
173
            return $this->componentsCache[$cacheKey];
21✔
174
        }
175

176
        $attributes = parent::getAttributes($object, $format, $context);
22✔
177
        $options = $this->getFactoryOptions($context);
22✔
178

179
        $components = [
22✔
180
            'states' => [],
22✔
181
            'links' => [],
22✔
182
            'embedded' => [],
22✔
183
        ];
22✔
184

185
        foreach ($attributes as $attribute) {
22✔
186
            $propertyMetadata = $this->propertyMetadataFactory->create($context['resource_class'], $attribute, $options);
21✔
187

188
            if (method_exists(PropertyInfoExtractor::class, 'getType')) {
21✔
189
                $type = $propertyMetadata->getNativeType();
21✔
190
                $types = $type instanceof CompositeTypeInterface ? $type->getTypes() : (null === $type ? [] : [$type]);
21✔
191
                /** @var class-string|null $className */
192
                $className = null;
21✔
193
            } else {
194
                $types = $propertyMetadata->getBuiltinTypes() ?? [];
×
195
            }
196

197
            // prevent declaring $attribute as attribute if it's already declared as relationship
198
            $isRelationship = false;
21✔
199
            $typeIsResourceClass = function (Type $type) use (&$className): bool {
21✔
200
                return $type instanceof ObjectType && $this->resourceClassResolver->isResourceClass($className = $type->getClassName());
21✔
201
            };
21✔
202

203
            foreach ($types as $type) {
21✔
204
                $isOne = $isMany = false;
21✔
205

206
                /** @var Type|LegacyType|null $valueType */
207
                $valueType = null;
21✔
208

209
                if ($type instanceof LegacyType) {
21✔
210
                    if ($type->isCollection()) {
×
211
                        $valueType = $type->getCollectionValueTypes()[0] ?? null;
×
212
                        $isMany = null !== $valueType && ($className = $valueType->getClassName()) && $this->resourceClassResolver->isResourceClass($className);
×
213
                    } else {
214
                        $className = $type->getClassName();
×
215
                        $isOne = $className && $this->resourceClassResolver->isResourceClass($className);
×
216
                    }
217
                } elseif ($type instanceof Type) {
21✔
218
                    if ($type->isSatisfiedBy(fn ($t) => $t instanceof CollectionType)) {
21✔
219
                        $isMany = TypeHelper::getCollectionValueType($type)?->isSatisfiedBy($typeIsResourceClass);
2✔
220
                    } else {
221
                        $isOne = $type->isSatisfiedBy($typeIsResourceClass);
21✔
222
                    }
223
                }
224

225
                if (!$isOne && !$isMany) {
21✔
226
                    // don't declare it as an attribute too quick: maybe the next type is a valid resource
227
                    continue;
21✔
228
                }
229

230
                $relation = ['name' => $attribute, 'cardinality' => $isOne ? 'one' : 'many', 'iri' => null, 'operation' => null];
8✔
231

232
                // if we specify the uriTemplate, generates its value for link definition
233
                // @see ApiPlatform\Serializer\AbstractItemNormalizer:getAttributeValue logic for intentional duplicate content
234
                if (($className ?? false) && $uriTemplate = $propertyMetadata->getUriTemplate()) {
8✔
235
                    $childContext = $this->createChildContext($context, $attribute, $format);
×
236
                    unset($childContext['iri'], $childContext['uri_variables'], $childContext['resource_class'], $childContext['operation'], $childContext['operation_name']);
×
237

238
                    $operation = $this->resourceMetadataCollectionFactory->create($className)->getOperation(
×
239
                        operationName: $uriTemplate,
×
240
                        httpOperation: true
×
241
                    );
×
242

243
                    $relation['iri'] = $this->iriConverter->getIriFromResource($object, UrlGeneratorInterface::ABS_PATH, $operation, $childContext);
×
244
                    $relation['operation'] = $operation;
×
245
                    $cacheKey = null;
×
246
                }
247

248
                if ($propertyMetadata->isReadableLink()) {
8✔
249
                    $components['embedded'][] = $relation;
4✔
250
                }
251

252
                $components['links'][] = $relation;
8✔
253
                $isRelationship = true;
8✔
254
            }
255

256
            // if all types are not relationships, declare it as an attribute
257
            if (!$isRelationship) {
21✔
258
                $components['states'][] = $attribute;
21✔
259
            }
260
        }
261

262
        if ($cacheKey && false !== $context['cache_key']) {
22✔
263
            $this->componentsCache[$cacheKey] = $components;
21✔
264
        }
265

266
        return $components;
22✔
267
    }
268

269
    /**
270
     * Populates _links and _embedded keys.
271
     */
272
    private function populateRelation(array $data, object $object, ?string $format, array $context, array $components, string $type): array
273
    {
274
        $class = $this->getObjectClass($object);
22✔
275

276
        if ($this->isHalCircularReference($object, $context)) {
22✔
277
            return $this->handleHalCircularReference($object, $format, $context);
×
278
        }
279

280
        $attributesMetadata = \array_key_exists($class, $this->attributesMetadataCache) ?
22✔
281
            $this->attributesMetadataCache[$class] :
22✔
282
            $this->attributesMetadataCache[$class] = $this->classMetadataFactory ? $this->classMetadataFactory->getMetadataFor($class)->getAttributesMetadata() : null;
22✔
283

284
        $key = '_'.$type;
22✔
285
        foreach ($components[$type] as $relation) {
22✔
286
            if (null !== $attributesMetadata && $this->isMaxDepthReached($attributesMetadata, $class, $relation['name'], $context)) {
8✔
287
                continue;
1✔
288
            }
289

290
            $relationName = $relation['name'];
8✔
291
            if ($this->nameConverter) {
8✔
292
                $relationName = $this->nameConverter->normalize($relationName, $class, $format, $context);
7✔
293
            }
294

295
            // if we specify the uriTemplate, then the link takes the uriTemplate defined.
296
            if ('links' === $type && $iri = $relation['iri']) {
8✔
297
                $data[$key][$relationName]['href'] = $iri;
×
298
                continue;
×
299
            }
300

301
            $childContext = $this->createChildContext($context, $relationName, $format);
8✔
302
            unset($childContext['iri'], $childContext['uri_variables'], $childContext['operation'], $childContext['operation_name']);
8✔
303

304
            if ($operation = $relation['operation']) {
8✔
305
                $childContext['operation'] = $operation;
×
306
                $childContext['operation_name'] = $operation->getName();
×
307
            }
308

309
            $attributeValue = $this->getAttributeValue($object, $relation['name'], $format, $childContext);
8✔
310

311
            if (empty($attributeValue) && ($context[self::SKIP_NULL_TO_ONE_RELATIONS] ?? $this->defaultContext[self::SKIP_NULL_TO_ONE_RELATIONS] ?? true)) {
8✔
312
                continue;
4✔
313
            }
314

315
            if ('one' === $relation['cardinality']) {
6✔
316
                if ('links' === $type) {
6✔
317
                    if (null !== $attributeValue) {
6✔
318
                        $data[$key][$relationName]['href'] = $this->getRelationIri($attributeValue);
5✔
319
                        continue;
5✔
320
                    }
321
                }
322

323
                $data[$key][$relationName] = $attributeValue;
4✔
324
                continue;
4✔
325
            }
326

327
            // many
328
            $data[$key][$relationName] = [];
×
329
            foreach ($attributeValue as $rel) {
×
330
                if ('links' === $type) {
×
331
                    $rel = ['href' => $this->getRelationIri($rel)];
×
332
                }
333

334
                $data[$key][$relationName][] = $rel;
×
335
            }
336
        }
337

338
        return $data;
22✔
339
    }
340

341
    /**
342
     * Gets the IRI of the given relation.
343
     *
344
     * @throws UnexpectedValueException
345
     */
346
    private function getRelationIri(mixed $rel): string
347
    {
348
        if (!(\is_array($rel) || \is_string($rel))) {
5✔
349
            throw new UnexpectedValueException('Expected relation to be an IRI or array');
×
350
        }
351

352
        return \is_string($rel) ? $rel : $rel['_links']['self']['href'];
5✔
353
    }
354

355
    /**
356
     * Is the max depth reached for the given attribute?
357
     *
358
     * @param AttributeMetadataInterface[] $attributesMetadata
359
     */
360
    private function isMaxDepthReached(array $attributesMetadata, string $class, string $attribute, array &$context): bool
361
    {
362
        if (
363
            !($context[self::ENABLE_MAX_DEPTH] ?? false)
4✔
364
            || !isset($attributesMetadata[$attribute])
4✔
365
            || null === $maxDepth = $attributesMetadata[$attribute]->getMaxDepth()
4✔
366
        ) {
367
            return false;
4✔
368
        }
369

370
        $key = \sprintf(self::DEPTH_KEY_PATTERN, $class, $attribute);
1✔
371
        if (!isset($context[$key])) {
1✔
372
            $context[$key] = 1;
1✔
373

374
            return false;
1✔
375
        }
376

377
        if ($context[$key] === $maxDepth) {
1✔
378
            return true;
1✔
379
        }
380

381
        ++$context[$key];
×
382

383
        return false;
×
384
    }
385

386
    /**
387
     * Detects if the configured circular reference limit is reached.
388
     *
389
     * @throws CircularReferenceException
390
     */
391
    protected function isHalCircularReference(object $object, array &$context): bool
392
    {
393
        $objectHash = spl_object_hash($object);
22✔
394

395
        $circularReferenceLimit = $context[AbstractNormalizer::CIRCULAR_REFERENCE_LIMIT] ?? $this->defaultContext[AbstractNormalizer::CIRCULAR_REFERENCE_LIMIT];
22✔
396
        if (isset($context[self::HAL_CIRCULAR_REFERENCE_LIMIT_COUNTERS][$objectHash])) {
22✔
397
            if ($context[self::HAL_CIRCULAR_REFERENCE_LIMIT_COUNTERS][$objectHash] >= $circularReferenceLimit) {
×
398
                unset($context[self::HAL_CIRCULAR_REFERENCE_LIMIT_COUNTERS][$objectHash]);
×
399

400
                return true;
×
401
            }
402

403
            ++$context[self::HAL_CIRCULAR_REFERENCE_LIMIT_COUNTERS][$objectHash];
×
404
        } else {
405
            $context[self::HAL_CIRCULAR_REFERENCE_LIMIT_COUNTERS][$objectHash] = 1;
22✔
406
        }
407

408
        return false;
22✔
409
    }
410

411
    /**
412
     * Handles a circular reference.
413
     *
414
     * If a circular reference handler is set, it will be called. Otherwise, a
415
     * {@class CircularReferenceException} will be thrown.
416
     *
417
     * @final
418
     *
419
     * @throws CircularReferenceException
420
     */
421
    protected function handleHalCircularReference(object $object, ?string $format = null, array $context = []): mixed
422
    {
423
        $circularReferenceHandler = $context[AbstractNormalizer::CIRCULAR_REFERENCE_HANDLER] ?? $this->defaultContext[AbstractNormalizer::CIRCULAR_REFERENCE_HANDLER];
×
424
        if ($circularReferenceHandler) {
×
425
            return $circularReferenceHandler($object, $format, $context);
×
426
        }
427

428
        throw new CircularReferenceException(\sprintf('A circular reference has been detected when serializing the object of class "%s" (configured limit: %d).', get_debug_type($object), $context[AbstractNormalizer::CIRCULAR_REFERENCE_LIMIT] ?? $this->defaultContext[AbstractNormalizer::CIRCULAR_REFERENCE_LIMIT]));
×
429
    }
430
}
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

© 2025 Coveralls, Inc