Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
11 changes: 11 additions & 0 deletions src/GraphQl/Serializer/ItemNormalizer.php
Original file line number Diff line number Diff line change
Expand Up @@ -88,6 +88,17 @@ public function normalize(mixed $data, ?string $format = null, array $context =

unset($context['operation_name'], $context['operation']); // Remove operation and operation_name only when cache key has been created
$normalizedData = parent::normalize($data, $format, $context);

// The default circular_reference_handler returns the visited object's IRI
// as a string; return an identifier-only node so the GraphQL field shape
// is preserved instead of crashing.
if (\is_string($normalizedData)) {
return [
self::ITEM_RESOURCE_CLASS_KEY => $resourceClass,
self::ITEM_IDENTIFIERS_KEY => $this->identifiersExtractor->getIdentifiersFromItem($data),
];
}

if (!\is_array($normalizedData)) {
throw new UnexpectedValueException('Expected data to be an array.');
}
Expand Down
11 changes: 11 additions & 0 deletions src/GraphQl/Serializer/ObjectNormalizer.php
Original file line number Diff line number Diff line change
Expand Up @@ -64,6 +64,17 @@ public function normalize(mixed $data, ?string $format = null, array $context =
}

$normalizedData = $this->decorated->normalize($data, $format, $context);

// The default circular_reference_handler returns the visited object's IRI
// as a string; return an identifier-only node so the GraphQL field shape
// is preserved instead of crashing.
if (\is_string($normalizedData) && isset($originalResource)) {
return [
self::ITEM_RESOURCE_CLASS_KEY => $this->getObjectClass($originalResource),
self::ITEM_IDENTIFIERS_KEY => $this->identifiersExtractor->getIdentifiersFromItem($originalResource),
];
}

if (!\is_array($normalizedData)) {
throw new UnexpectedValueException('Expected data to be an array.');
}
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
<?php

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

declare(strict_types=1);

namespace ApiPlatform\Tests\Fixtures\TestBundle\Entity\GraphQlCircularReference;

use ApiPlatform\Metadata\ApiResource;
use Doctrine\ORM\Mapping as ORM;

#[ApiResource]
#[ORM\Entity]
class CircularReferenceAddress
{
#[ORM\Id]
#[ORM\Column(type: 'integer')]
#[ORM\GeneratedValue(strategy: 'AUTO')]
public ?int $id = null;

#[ORM\Column(type: 'string')]
public ?string $street = null;

#[ORM\ManyToOne(targetEntity: CircularReferenceCustomer::class, inversedBy: 'addresses')]
#[ORM\JoinColumn(nullable: false)]
public ?CircularReferenceCustomer $owner = null;
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,44 @@
<?php

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

declare(strict_types=1);

namespace ApiPlatform\Tests\Fixtures\TestBundle\Entity\GraphQlCircularReference;

use ApiPlatform\Metadata\ApiResource;
use Doctrine\Common\Collections\ArrayCollection;
use Doctrine\Common\Collections\Collection;
use Doctrine\ORM\Mapping as ORM;

#[ApiResource]
#[ORM\Entity]
class CircularReferenceCustomer
{
#[ORM\Id]
#[ORM\Column(type: 'integer')]
#[ORM\GeneratedValue(strategy: 'AUTO')]
public ?int $id = null;

#[ORM\Column(type: 'string')]
public ?string $name = null;

#[ORM\OneToMany(targetEntity: CircularReferenceAddress::class, mappedBy: 'owner', cascade: ['persist'])]
public Collection $addresses;

#[ORM\ManyToOne(targetEntity: CircularReferenceAddress::class)]
#[ORM\JoinColumn(nullable: true)]
public ?CircularReferenceAddress $invoiceAddress = null;

public function __construct()
{
$this->addresses = new ArrayCollection();
}
}
92 changes: 92 additions & 0 deletions tests/Functional/GraphQl/CircularReferenceNormalizationTest.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,92 @@
<?php

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

declare(strict_types=1);

namespace ApiPlatform\Tests\Functional\GraphQl;

use ApiPlatform\Symfony\Bundle\Test\ApiTestCase;
use ApiPlatform\Tests\Fixtures\TestBundle\Entity\GraphQlCircularReference\CircularReferenceAddress;
use ApiPlatform\Tests\Fixtures\TestBundle\Entity\GraphQlCircularReference\CircularReferenceCustomer;
use ApiPlatform\Tests\RecreateSchemaTrait;
use ApiPlatform\Tests\SetupClassResourcesTrait;

/**
* Two ApiResource entities with mutual ManyToOne/OneToMany references must not crash
* the GraphQL ItemNormalizer when the traversal hits a circular reference. The default
* circular_reference_handler returns an IRI string; the GraphQL normalizer used to
* assert the result was an array and threw "Expected data to be an array.".
*
* @see https://github.com/api-platform/core/issues/8080
*/
final class CircularReferenceNormalizationTest extends ApiTestCase
{
use RecreateSchemaTrait;
use SetupClassResourcesTrait;

protected static ?bool $alwaysBootKernel = false;

/**
* @return class-string[]
*/
public static function getResources(): array
{
return [CircularReferenceCustomer::class, CircularReferenceAddress::class];
}

public function testCircularReferenceTraversalDoesNotCrash(): void
{
if ($this->isMongoDB()) {
$this->markTestSkipped('CircularReference entities are ORM-only.');
}

$this->recreateSchema([CircularReferenceCustomer::class, CircularReferenceAddress::class]);

$manager = $this->getManager();
$customer = new CircularReferenceCustomer();
$customer->name = 'Acme';

$address = new CircularReferenceAddress();
$address->street = '1 Test Street';
$address->owner = $customer;
$customer->addresses->add($address);
$customer->invoiceAddress = $address;

$manager->persist($customer);
$manager->persist($address);
$manager->flush();

$iri = '/circular_reference_addresses/'.$address->id;

$response = self::createClient()->request('POST', '/graphql', ['json' => [
'query' => <<<GRAPHQL
{
circularReferenceAddress(id: "{$iri}") {
id
street
owner {
id
name
}
}
}
GRAPHQL,
]]);

$this->assertResponseIsSuccessful();
$json = $response->toArray(false);
// Pre-fix the inner normalization triggered "Expected data to be an array."
// because the circular_reference_handler returned the IRI string.
$this->assertArrayNotHasKey('errors', $json, json_encode($json['errors'] ?? null));
$this->assertSame('1 Test Street', $json['data']['circularReferenceAddress']['street']);
$this->assertSame('Acme', $json['data']['circularReferenceAddress']['owner']['name']);
}
}
Loading