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

api-platform / core / 15040977736

15 May 2025 09:02AM UTC coverage: 21.754% (+13.3%) from 8.423%
15040977736

Pull #6960

github

web-flow
Merge 7a7a13526 into 1862d03b7
Pull Request #6960: feat(json-schema): mutualize json schema between formats

320 of 460 new or added lines in 24 files covered. (69.57%)

1863 existing lines in 109 files now uncovered.

11069 of 50882 relevant lines covered (21.75%)

29.49 hits per line

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

84.28
/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 {
855✔
65
            $iri = $this->iriConverter->getIriFromResource($object);
×
66
            if (null === $iri) {
×
67
                return null;
×
68
            }
69

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

73
        parent::__construct($propertyNameCollectionFactory, $propertyMetadataFactory, $iriConverter, $resourceClassResolver, $propertyAccessor, $nameConverter, $classMetadataFactory, $defaultContext, $resourceMetadataCollectionFactory, $resourceAccessChecker, $tagCollector);
855✔
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);
40✔
82
    }
83

84
    public function getSupportedTypes($format): array
85
    {
86
        return self::FORMAT === $format ? parent::getSupportedTypes($format) : [];
782✔
87
    }
88

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

99
        $previousResourceClass = $context['resource_class'] ?? null;
38✔
100
        if ($this->resourceClassResolver->isResourceClass($resourceClass) && (null === $previousResourceClass || $this->resourceClassResolver->isResourceClass($previousResourceClass))) {
38✔
101
            $resourceClass = $this->resourceClassResolver->getResourceClass($object, $previousResourceClass);
36✔
102
        }
103

104
        $context = $this->initContext($resourceClass, $context);
38✔
105

106
        $iri = $context['iri'] ??= $this->iriConverter->getIriFromResource($object, UrlGeneratorInterface::ABS_PATH, $context['operation'] ?? null, $context);
38✔
107
        $context['object'] = $object;
38✔
108
        $context['format'] = $format;
38✔
109
        $context['api_normalize'] = true;
38✔
110

111
        if (!isset($context['cache_key'])) {
38✔
112
            $context['cache_key'] = $this->getCacheKey($format, $context);
38✔
113
        }
114

115
        $data = parent::normalize($object, $format, $context);
38✔
116

117
        if (!\is_array($data)) {
38✔
118
            return $data;
×
119
        }
120

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

132
        return $metadata + $data;
38✔
133
    }
134

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

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

154
    /**
155
     * {@inheritdoc}
156
     */
157
    protected function getAttributes($object, $format = null, array $context = []): array
158
    {
159
        return $this->getComponents($object, $format, $context)['states'];
38✔
160
    }
161

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

169
        if (isset($this->componentsCache[$cacheKey])) {
38✔
170
            return $this->componentsCache[$cacheKey];
38✔
171
        }
172

173
        $attributes = parent::getAttributes($object, $format, $context);
38✔
174
        $options = $this->getFactoryOptions($context);
38✔
175

176
        $components = [
38✔
177
            'states' => [],
38✔
178
            'links' => [],
38✔
179
            'embedded' => [],
38✔
180
        ];
38✔
181

182
        foreach ($attributes as $attribute) {
38✔
183
            $propertyMetadata = $this->propertyMetadataFactory->create($context['resource_class'], $attribute, $options);
38✔
184

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

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

200
            foreach ($types as $type) {
38✔
201
                $isOne = $isMany = false;
36✔
202

203
                /** @var Type|LegacyType|null $valueType */
204
                $valueType = null;
36✔
205

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

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

227
                $relation = ['name' => $attribute, 'cardinality' => $isOne ? 'one' : 'many', 'iri' => null, 'operation' => null];
33✔
228

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

235
                    $operation = $this->resourceMetadataCollectionFactory->create($className)->getOperation(
1✔
236
                        operationName: $uriTemplate,
1✔
237
                        httpOperation: true
1✔
238
                    );
1✔
239

240
                    $relation['iri'] = $this->iriConverter->getIriFromResource($object, UrlGeneratorInterface::ABS_PATH, $operation, $childContext);
1✔
241
                    $relation['operation'] = $operation;
1✔
242
                    $cacheKey = null;
1✔
243
                }
244

245
                if ($propertyMetadata->isReadableLink()) {
33✔
246
                    $components['embedded'][] = $relation;
9✔
247
                }
248

249
                $components['links'][] = $relation;
33✔
250
                $isRelationship = true;
33✔
251
            }
252

253
            // if all types are not relationships, declare it as an attribute
254
            if (!$isRelationship) {
38✔
255
                $components['states'][] = $attribute;
38✔
256
            }
257
        }
258

259
        if ($cacheKey && false !== $context['cache_key']) {
38✔
260
            $this->componentsCache[$cacheKey] = $components;
38✔
261
        }
262

263
        return $components;
38✔
264
    }
265

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

273
        if ($this->isHalCircularReference($object, $context)) {
38✔
274
            return $this->handleHalCircularReference($object, $format, $context);
×
275
        }
276

277
        $attributesMetadata = \array_key_exists($class, $this->attributesMetadataCache) ?
38✔
278
            $this->attributesMetadataCache[$class] :
38✔
279
            $this->attributesMetadataCache[$class] = $this->classMetadataFactory ? $this->classMetadataFactory->getMetadataFor($class)->getAttributesMetadata() : null;
38✔
280

281
        $key = '_'.$type;
38✔
282
        foreach ($components[$type] as $relation) {
38✔
283
            if (null !== $attributesMetadata && $this->isMaxDepthReached($attributesMetadata, $class, $relation['name'], $context)) {
33✔
284
                continue;
3✔
285
            }
286

287
            $relationName = $relation['name'];
33✔
288
            if ($this->nameConverter) {
33✔
289
                $relationName = $this->nameConverter->normalize($relationName, $class, $format, $context);
33✔
290
            }
291

292
            // if we specify the uriTemplate, then the link takes the uriTemplate defined.
293
            if ('links' === $type && $iri = $relation['iri']) {
33✔
294
                $data[$key][$relationName]['href'] = $iri;
1✔
295
                continue;
1✔
296
            }
297

298
            $childContext = $this->createChildContext($context, $relationName, $format);
33✔
299
            unset($childContext['iri'], $childContext['uri_variables'], $childContext['operation'], $childContext['operation_name']);
33✔
300

301
            if ($operation = $relation['operation']) {
33✔
302
                $childContext['operation'] = $operation;
1✔
303
                $childContext['operation_name'] = $operation->getName();
1✔
304
            }
305

306
            $attributeValue = $this->getAttributeValue($object, $relation['name'], $format, $childContext);
33✔
307

308
            if (empty($attributeValue)) {
33✔
309
                continue;
21✔
310
            }
311

312
            if ('one' === $relation['cardinality']) {
21✔
313
                if ('links' === $type) {
17✔
314
                    $data[$key][$relationName]['href'] = $this->getRelationIri($attributeValue);
16✔
315
                    continue;
16✔
316
                }
317

318
                $data[$key][$relationName] = $attributeValue;
8✔
319
                continue;
8✔
320
            }
321

322
            // many
323
            $data[$key][$relationName] = [];
9✔
324
            foreach ($attributeValue as $rel) {
9✔
325
                if ('links' === $type) {
9✔
326
                    $rel = ['href' => $this->getRelationIri($rel)];
8✔
327
                }
328

329
                $data[$key][$relationName][] = $rel;
9✔
330
            }
331
        }
332

333
        return $data;
38✔
334
    }
335

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

347
        return \is_string($rel) ? $rel : $rel['_links']['self']['href'];
20✔
348
    }
349

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

365
        $key = \sprintf(self::DEPTH_KEY_PATTERN, $class, $attribute);
3✔
366
        if (!isset($context[$key])) {
3✔
367
            $context[$key] = 1;
3✔
368

369
            return false;
3✔
370
        }
371

372
        if ($context[$key] === $maxDepth) {
3✔
373
            return true;
3✔
374
        }
375

376
        ++$context[$key];
×
377

378
        return false;
×
379
    }
380

381
    /**
382
     * Detects if the configured circular reference limit is reached.
383
     *
384
     * @throws CircularReferenceException
385
     */
386
    protected function isHalCircularReference(object $object, array &$context): bool
387
    {
388
        $objectHash = spl_object_hash($object);
38✔
389

390
        $circularReferenceLimit = $context[AbstractNormalizer::CIRCULAR_REFERENCE_LIMIT] ?? $this->defaultContext[AbstractNormalizer::CIRCULAR_REFERENCE_LIMIT];
38✔
391
        if (isset($context[self::HAL_CIRCULAR_REFERENCE_LIMIT_COUNTERS][$objectHash])) {
38✔
392
            if ($context[self::HAL_CIRCULAR_REFERENCE_LIMIT_COUNTERS][$objectHash] >= $circularReferenceLimit) {
×
393
                unset($context[self::HAL_CIRCULAR_REFERENCE_LIMIT_COUNTERS][$objectHash]);
×
394

395
                return true;
×
396
            }
397

398
            ++$context[self::HAL_CIRCULAR_REFERENCE_LIMIT_COUNTERS][$objectHash];
×
399
        } else {
400
            $context[self::HAL_CIRCULAR_REFERENCE_LIMIT_COUNTERS][$objectHash] = 1;
38✔
401
        }
402

403
        return false;
38✔
404
    }
405

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

423
        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]));
×
424
    }
425
}
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