Skip to content

Commit ab88353

Browse files
fix(hal): detecting and handling circular reference (#6752)
Co-authored-by: Valentin Dassonville <[email protected]>
1 parent aa1667d commit ab88353

File tree

4 files changed

+241
-0
lines changed

4 files changed

+241
-0
lines changed

src/Hal/Serializer/ItemNormalizer.php

Lines changed: 77 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -13,14 +13,26 @@
1313

1414
namespace ApiPlatform\Hal\Serializer;
1515

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;
1622
use ApiPlatform\Metadata\UrlGeneratorInterface;
1723
use ApiPlatform\Metadata\Util\ClassInfoTrait;
1824
use ApiPlatform\Serializer\AbstractItemNormalizer;
1925
use ApiPlatform\Serializer\CacheKeyTrait;
2026
use ApiPlatform\Serializer\ContextTrait;
27+
use ApiPlatform\Serializer\TagCollectorInterface;
28+
use Symfony\Component\PropertyAccess\PropertyAccessorInterface;
29+
use Symfony\Component\Serializer\Exception\CircularReferenceException;
2130
use Symfony\Component\Serializer\Exception\LogicException;
2231
use Symfony\Component\Serializer\Exception\UnexpectedValueException;
2332
use Symfony\Component\Serializer\Mapping\AttributeMetadataInterface;
33+
use Symfony\Component\Serializer\Mapping\Factory\ClassMetadataFactoryInterface;
34+
use Symfony\Component\Serializer\NameConverter\NameConverterInterface;
35+
use Symfony\Component\Serializer\Normalizer\AbstractNormalizer;
2436

2537
/**
2638
* Converts between objects and array including HAL metadata.
@@ -35,9 +47,25 @@ final class ItemNormalizer extends AbstractItemNormalizer
3547

3648
public const FORMAT = 'jsonhal';
3749

50+
protected const HAL_CIRCULAR_REFERENCE_LIMIT_COUNTERS = 'hal_circular_reference_limit_counters';
51+
3852
private array $componentsCache = [];
3953
private array $attributesMetadataCache = [];
4054

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, ?TagCollectorInterface $tagCollector = null)
56+
{
57+
$defaultContext[AbstractNormalizer::CIRCULAR_REFERENCE_HANDLER] = function ($object): ?array {
58+
$iri = $this->iriConverter->getIriFromResource($object);
59+
if (null === $iri) {
60+
return null;
61+
}
62+
63+
return ['_links' => ['self' => ['href' => $iri]]];
64+
};
65+
66+
parent::__construct($propertyNameCollectionFactory, $propertyMetadataFactory, $iriConverter, $resourceClassResolver, $propertyAccessor, $nameConverter, $classMetadataFactory, $defaultContext, $resourceMetadataCollectionFactory, $resourceAccessChecker, $tagCollector);
67+
}
68+
4169
/**
4270
* {@inheritdoc}
4371
*/
@@ -216,6 +244,10 @@ private function populateRelation(array $data, object $object, ?string $format,
216244
{
217245
$class = $this->getObjectClass($object);
218246

247+
if ($this->isHalCircularReference($object, $context)) {
248+
return $this->handleHalCircularReference($object, $format, $context);
249+
}
250+
219251
$attributesMetadata = \array_key_exists($class, $this->attributesMetadataCache) ?
220252
$this->attributesMetadataCache[$class] :
221253
$this->attributesMetadataCache[$class] = $this->classMetadataFactory ? $this->classMetadataFactory->getMetadataFor($class)->getAttributesMetadata() : null;
@@ -319,4 +351,49 @@ private function isMaxDepthReached(array $attributesMetadata, string $class, str
319351

320352
return false;
321353
}
354+
355+
/**
356+
* Detects if the configured circular reference limit is reached.
357+
*
358+
* @throws CircularReferenceException
359+
*/
360+
protected function isHalCircularReference(object $object, array &$context): bool
361+
{
362+
$objectHash = spl_object_hash($object);
363+
364+
$circularReferenceLimit = $context[AbstractNormalizer::CIRCULAR_REFERENCE_LIMIT] ?? $this->defaultContext[AbstractNormalizer::CIRCULAR_REFERENCE_LIMIT];
365+
if (isset($context[self::HAL_CIRCULAR_REFERENCE_LIMIT_COUNTERS][$objectHash])) {
366+
if ($context[self::HAL_CIRCULAR_REFERENCE_LIMIT_COUNTERS][$objectHash] >= $circularReferenceLimit) {
367+
unset($context[self::HAL_CIRCULAR_REFERENCE_LIMIT_COUNTERS][$objectHash]);
368+
369+
return true;
370+
}
371+
372+
++$context[self::HAL_CIRCULAR_REFERENCE_LIMIT_COUNTERS][$objectHash];
373+
} else {
374+
$context[self::HAL_CIRCULAR_REFERENCE_LIMIT_COUNTERS][$objectHash] = 1;
375+
}
376+
377+
return false;
378+
}
379+
380+
/**
381+
* Handles a circular reference.
382+
*
383+
* If a circular reference handler is set, it will be called. Otherwise, a
384+
* {@class CircularReferenceException} will be thrown.
385+
*
386+
* @final
387+
*
388+
* @throws CircularReferenceException
389+
*/
390+
protected function handleHalCircularReference(object $object, ?string $format = null, array $context = []): mixed
391+
{
392+
$circularReferenceHandler = $context[AbstractNormalizer::CIRCULAR_REFERENCE_HANDLER] ?? $this->defaultContext[AbstractNormalizer::CIRCULAR_REFERENCE_HANDLER];
393+
if ($circularReferenceHandler) {
394+
return $circularReferenceHandler($object, $format, $context);
395+
}
396+
397+
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]));
398+
}
322399
}
Lines changed: 64 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,64 @@
1+
<?php
2+
3+
/*
4+
* This file is part of the API Platform project.
5+
*
6+
* (c) Kévin Dunglas <[email protected]>
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\Tests\Fixtures\TestBundle\ApiResource\Issue4358;
15+
16+
use ApiPlatform\Metadata\ApiProperty;
17+
use ApiPlatform\Metadata\Get;
18+
use Symfony\Component\Serializer\Annotation\Groups;
19+
use Symfony\Component\Serializer\Annotation\MaxDepth;
20+
21+
#[Get(uriTemplate: 'resource_a',
22+
formats: ['jsonhal'],
23+
outputFormats: ['jsonhal'],
24+
normalizationContext: ['groups' => ['ResourceA:read'], 'enable_max_depth' => true],
25+
provider: [self::class, 'provide'])]
26+
final class ResourceA
27+
{
28+
private static ?ResourceA $resourceA = null;
29+
30+
#[ApiProperty(readableLink: true)]
31+
#[Groups(['ResourceA:read', 'ResourceB:read'])]
32+
#[MaxDepth(6)]
33+
public ResourceB $b;
34+
35+
public function __construct(?ResourceB $b = null)
36+
{
37+
if (null !== $b) {
38+
$this->b = $b;
39+
}
40+
}
41+
42+
public static function provide(): self
43+
{
44+
return self::provideWithResource();
45+
}
46+
47+
public static function provideWithResource(?ResourceB $b = null): self
48+
{
49+
if (!isset(self::$resourceA)) {
50+
self::$resourceA = new self($b);
51+
52+
if (null === ResourceB::getInstance()) {
53+
self::$resourceA->b = ResourceB::provideWithResource(self::$resourceA);
54+
}
55+
}
56+
57+
return self::$resourceA;
58+
}
59+
60+
public static function getInstance(): ?self
61+
{
62+
return self::$resourceA;
63+
}
64+
}
Lines changed: 64 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,64 @@
1+
<?php
2+
3+
/*
4+
* This file is part of the API Platform project.
5+
*
6+
* (c) Kévin Dunglas <[email protected]>
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\Tests\Fixtures\TestBundle\ApiResource\Issue4358;
15+
16+
use ApiPlatform\Metadata\ApiProperty;
17+
use ApiPlatform\Metadata\Get;
18+
use Symfony\Component\Serializer\Annotation\Groups;
19+
use Symfony\Component\Serializer\Annotation\MaxDepth;
20+
21+
#[Get(uriTemplate: 'resource_b',
22+
formats: ['jsonhal'],
23+
outputFormats: ['jsonhal'],
24+
normalizationContext: ['groups' => ['ResourceB:read'], 'enable_max_depth' => true],
25+
provider: [self::class, 'provide'])]
26+
final class ResourceB
27+
{
28+
private static ?ResourceB $resourceB = null;
29+
30+
#[ApiProperty(readableLink: true)]
31+
#[Groups(['ResourceA:read', 'ResourceB:read'])]
32+
#[MaxDepth(6)]
33+
public ResourceA $a;
34+
35+
public function __construct(?ResourceA $a = null)
36+
{
37+
if (null !== $a) {
38+
$this->a = $a;
39+
}
40+
}
41+
42+
public static function provide(): self
43+
{
44+
return self::provideWithResource();
45+
}
46+
47+
public static function provideWithResource(?ResourceA $a = null): self
48+
{
49+
if (!isset(self::$resourceB)) {
50+
self::$resourceB = new self($a);
51+
52+
if (null === ResourceA::getInstance()) {
53+
self::$resourceB->a = ResourceA::provideWithResource(self::$resourceB);
54+
}
55+
}
56+
57+
return self::$resourceB;
58+
}
59+
60+
public static function getInstance(): ?self
61+
{
62+
return self::$resourceB;
63+
}
64+
}
Lines changed: 36 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,36 @@
1+
<?php
2+
3+
/*
4+
* This file is part of the API Platform project.
5+
*
6+
* (c) Kévin Dunglas <[email protected]>
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\Tests\Functional;
15+
16+
use ApiPlatform\Symfony\Bundle\Test\ApiTestCase;
17+
use ApiPlatform\Tests\Fixtures\TestBundle\ApiResource\Issue4358\ResourceA;
18+
use ApiPlatform\Tests\Fixtures\TestBundle\ApiResource\Issue4358\ResourceB;
19+
use ApiPlatform\Tests\SetupClassResourcesTrait;
20+
21+
class HALCircularReference extends ApiTestCase
22+
{
23+
use SetupClassResourcesTrait;
24+
25+
public function testIssue4358(): void
26+
{
27+
$r1 = self::createClient()->request('GET', '/resource_a', ['headers' => ['Accept' => 'application/hal+json']]);
28+
self::assertResponseIsSuccessful();
29+
self::assertEquals('{"_links":{"self":{"href":"\/resource_a"},"b":{"href":"\/resource_b"}},"_embedded":{"b":{"_links":{"self":{"href":"\/resource_b"},"a":{"href":"\/resource_a"}},"_embedded":{"a":{"_links":{"self":{"href":"\/resource_a"}}}}}}}', $r1->getContent());
30+
}
31+
32+
public static function getResources(): array
33+
{
34+
return [ResourceA::class, ResourceB::class];
35+
}
36+
}

0 commit comments

Comments
 (0)