Skip to content
Open
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
8 changes: 6 additions & 2 deletions src/GraphQl/Serializer/ItemNormalizer.php
Original file line number Diff line number Diff line change
Expand Up @@ -77,13 +77,17 @@ public function normalize(mixed $data, ?string $format = null, array $context =
{
$resourceClass = $this->getObjectClass($data);

if ($this->getOutputClass($context)) {
if ($outputClass = $this->getOutputClass($context)) {
$context['graphql_identifiers'] = [
self::ITEM_RESOURCE_CLASS_KEY => $context['operation']->getClass(),
self::ITEM_IDENTIFIERS_KEY => $this->isBlankNode($resourceClass) ? ['id' => $this->propertyAccessor->getValue($data, 'id')] : $this->identifiersExtractor->getIdentifiersFromItem($data, $context['operation'] ?? null),
];

return parent::normalize($data, $format, $context);
if (!$this->isCollected($outputClass)) {
return parent::normalize($data, $format, $context);
}

$context = $this->switchToOutputContext($context, $outputClass);
}

unset($context['operation_name'], $context['operation']); // Remove operation and operation_name only when cache key has been created
Expand Down
38 changes: 1 addition & 37 deletions src/GraphQl/Serializer/ObjectNormalizer.php
Original file line number Diff line number Diff line change
Expand Up @@ -13,9 +13,6 @@

namespace ApiPlatform\GraphQl\Serializer;

use ApiPlatform\Metadata\IdentifiersExtractorInterface;
use ApiPlatform\Metadata\IriConverterInterface;
use ApiPlatform\Metadata\Util\ClassInfoTrait;
use Symfony\Component\Serializer\Exception\UnexpectedValueException;
use Symfony\Component\Serializer\Normalizer\NormalizerInterface;

Expand All @@ -25,13 +22,9 @@
*/
final class ObjectNormalizer implements NormalizerInterface
{
use ClassInfoTrait;

public const FORMAT = 'graphql';
public const ITEM_RESOURCE_CLASS_KEY = '#itemResourceClass';
public const ITEM_IDENTIFIERS_KEY = '#itemIdentifiers';

public function __construct(private readonly NormalizerInterface $decorated, private readonly IriConverterInterface $iriConverter, private readonly IdentifiersExtractorInterface $identifiersExtractor)
public function __construct(private readonly NormalizerInterface $decorated)
{
}

Expand All @@ -58,41 +51,12 @@ public function getSupportedTypes(?string $format): array
*/
public function normalize(mixed $data, ?string $format = null, array $context = []): array
{
if (isset($context['api_resource'])) {
$originalResource = $context['api_resource'];
unset($context['api_resource']);
}

$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.');
}

if (!isset($originalResource)) {
return $normalizedData;
}

if (isset($normalizedData['id'])) {
$normalizedData['_id'] = $normalizedData['id'];
$normalizedData['id'] = $this->iriConverter->getIriFromResource($originalResource);
}

if (!($context['no_resolver_data'] ?? false)) {
$normalizedData[self::ITEM_RESOURCE_CLASS_KEY] = $this->getObjectClass($originalResource);
$normalizedData[self::ITEM_IDENTIFIERS_KEY] = $this->identifiersExtractor->getIdentifiersFromItem($originalResource);
}

return $normalizedData;
}
}
8 changes: 6 additions & 2 deletions src/Hal/Serializer/ItemNormalizer.php
Original file line number Diff line number Diff line change
Expand Up @@ -93,8 +93,12 @@ public function getSupportedTypes(?string $format): array
public function normalize(mixed $data, ?string $format = null, array $context = []): array|string|int|float|bool|\ArrayObject|null
{
$resourceClass = $this->getObjectClass($data);
if ($this->getOutputClass($context)) {
return parent::normalize($data, $format, $context);
if ($outputClass = $this->getOutputClass($context)) {
if (!$this->isCollected($outputClass)) {
return parent::normalize($data, $format, $context);
}

$context = $this->switchToOutputContext($context, $outputClass);
}

$previousResourceClass = $context['resource_class'] ?? null;
Expand Down
27 changes: 2 additions & 25 deletions src/Hal/Serializer/ObjectNormalizer.php
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,6 @@

namespace ApiPlatform\Hal\Serializer;

use ApiPlatform\Metadata\IriConverterInterface;
use Symfony\Component\Serializer\Exception\LogicException;
use Symfony\Component\Serializer\Normalizer\DenormalizerInterface;
use Symfony\Component\Serializer\Normalizer\NormalizerInterface;
Expand All @@ -26,7 +25,7 @@ final class ObjectNormalizer implements NormalizerInterface, DenormalizerInterfa
{
public const FORMAT = 'jsonhal';

public function __construct(private readonly NormalizerInterface $decorated, private readonly IriConverterInterface $iriConverter)
public function __construct(private readonly NormalizerInterface $decorated)
{
}

Expand All @@ -51,29 +50,7 @@ public function getSupportedTypes(?string $format): array
*/
public function normalize(mixed $data, ?string $format = null, array $context = []): array|string|int|float|bool|\ArrayObject|null
{
if (isset($context['api_resource'])) {
$originalResource = $context['api_resource'];
unset($context['api_resource']);
}

$normalizedData = $this->decorated->normalize($data, $format, $context);
if (!\is_array($normalizedData)) {
return $normalizedData;
}

if (!isset($originalResource)) {
return $normalizedData;
}

$metadata = [
'_links' => [
'self' => [
'href' => $this->iriConverter->getIriFromResource($originalResource),
],
],
];

return $metadata + $normalizedData;
return $this->decorated->normalize($data, $format, $context);
}

/**
Expand Down
13 changes: 2 additions & 11 deletions src/Hal/Tests/Serializer/ObjectNormalizerTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,6 @@

use ApiPlatform\Hal\Serializer\ObjectNormalizer;
use ApiPlatform\Hal\Tests\Fixtures\Dummy;
use ApiPlatform\Metadata\IriConverterInterface;
use PHPUnit\Framework\Attributes\Group;
use PHPUnit\Framework\TestCase;
use Symfony\Component\Serializer\Exception\LogicException;
Expand All @@ -32,12 +31,8 @@ public function testDoesNotSupportDenormalization(): void
$this->expectExceptionMessage('jsonhal is a read-only format.');

$normalizerInterfaceMock = $this->createMock(NormalizerInterface::class);
$iriConverterMock = $this->createMock(IriConverterInterface::class);

$normalizer = new ObjectNormalizer(
$normalizerInterfaceMock,
$iriConverterMock
);
$normalizer = new ObjectNormalizer($normalizerInterfaceMock);

$this->assertFalse($normalizer->supportsDenormalization('foo', 'type', 'format'));
$normalizer->denormalize(['foo'], 'Foo');
Expand All @@ -50,11 +45,7 @@ public function testSupportsNormalization(): void
$dummy = new Dummy();

$normalizerInterfaceMock = $this->createMock(NormalizerInterface::class);
$iriConverterMock = $this->createMock(IriConverterInterface::class);
$normalizer = new ObjectNormalizer(
$normalizerInterfaceMock,
$iriConverterMock
);
$normalizer = new ObjectNormalizer($normalizerInterfaceMock);

$normalizerInterfaceMock->method('supportsNormalization')->willReturn(true);

Expand Down
8 changes: 6 additions & 2 deletions src/JsonApi/Serializer/ItemNormalizer.php
Original file line number Diff line number Diff line change
Expand Up @@ -119,8 +119,12 @@ public function denormalize(mixed $data, string $type, ?string $format = null, a
public function normalize(mixed $data, ?string $format = null, array $context = []): array|string|int|float|bool|\ArrayObject|null
{
$resourceClass = $this->getObjectClass($data);
if ($this->getOutputClass($context)) {
return parent::normalize($data, $format, $context);
if ($outputClass = $this->getOutputClass($context)) {
if (!$this->isCollected($outputClass)) {
return parent::normalize($data, $format, $context);
}

$context = $this->switchToOutputContext($context, $outputClass);
}

$previousResourceClass = $context['resource_class'] ?? null;
Expand Down
25 changes: 5 additions & 20 deletions src/JsonApi/Serializer/ObjectNormalizer.php
Original file line number Diff line number Diff line change
Expand Up @@ -14,8 +14,6 @@
namespace ApiPlatform\JsonApi\Serializer;

use ApiPlatform\Metadata\IriConverterInterface;
use ApiPlatform\Metadata\Resource\Factory\ResourceMetadataCollectionFactoryInterface;
use ApiPlatform\Metadata\ResourceClassResolverInterface;
use ApiPlatform\Metadata\Util\ClassInfoTrait;
use Symfony\Component\Serializer\Normalizer\NormalizerInterface;

Expand All @@ -29,7 +27,7 @@ final class ObjectNormalizer implements NormalizerInterface

public const FORMAT = 'jsonapi';

public function __construct(private readonly NormalizerInterface $decorated, private readonly IriConverterInterface $iriConverter, private readonly ResourceClassResolverInterface $resourceClassResolver, private readonly ResourceMetadataCollectionFactoryInterface $resourceMetadataFactory)
public function __construct(private readonly NormalizerInterface $decorated, private readonly IriConverterInterface $iriConverter)
{
}

Expand All @@ -54,28 +52,15 @@ public function getSupportedTypes(?string $format): array
*/
public function normalize(mixed $data, ?string $format = null, array $context = []): array|string|int|float|bool|\ArrayObject|null
{
if (isset($context['api_resource'])) {
$originalResource = $context['api_resource'];
unset($context['api_resource']);
}

$normalizedData = $this->decorated->normalize($data, $format, $context);
if (!\is_array($normalizedData) || isset($context['api_attribute'])) {
return $normalizedData;
}

if (isset($originalResource)) {
$resourceClass = $this->resourceClassResolver->getResourceClass($originalResource);
$resourceData = [
'id' => $this->iriConverter->getIriFromResource($originalResource),
'type' => $this->resourceMetadataFactory->create($resourceClass)->getOperation()->getShortName(),
];
} else {
$resourceData = [
'id' => $this->iriConverter->getIriFromResource($data),
'type' => (new \ReflectionClass($this->getObjectClass($data)))->getShortName(),
];
}
$resourceData = [
'id' => $this->iriConverter->getIriFromResource($data),
'type' => (new \ReflectionClass($this->getObjectClass($data)))->getShortName(),
];

if ($normalizedData) {
$resourceData['attributes'] = $normalizedData;
Expand Down
15 changes: 8 additions & 7 deletions src/JsonLd/Serializer/ItemNormalizer.php
Original file line number Diff line number Diff line change
Expand Up @@ -80,10 +80,13 @@ public function getSupportedTypes(?string $format): array
public function normalize(mixed $data, ?string $format = null, array $context = []): array|string|int|float|bool|\ArrayObject|null
{
$resourceClass = $this->getObjectClass($data);
$outputClass = $this->getOutputClass($context);

if ($outputClass && !($context['item_uri_template'] ?? null)) {
return parent::normalize($data, $format, $context);
if ($outputClass = $this->getOutputClass($context)) {
if (!$this->isCollected($outputClass)) {
return parent::normalize($data, $format, $context);
}

$context = $this->switchToOutputContext($context, $outputClass);
}

// TODO: we should not remove the resource_class in the normalizeRawCollection as we would find out anyway that it's not the same as the requested one
Expand All @@ -93,9 +96,7 @@ public function normalize(mixed $data, ?string $format = null, array $context =
if ($isResourceClass && (null === $previousResourceClass || $this->resourceClassResolver->isResourceClass($previousResourceClass))) {
$resourceClass = $this->resourceClassResolver->getResourceClass($data, $previousResourceClass);
if (isset($context['operation']) && $context['operation'] instanceof HttpOperation && $context['operation']->getClass() !== $resourceClass) {
$context['operation'] = isset($context['item_uri_template']) && $outputClass && $this->operationMetadataFactory
? $this->operationMetadataFactory->create($context['item_uri_template'])
: $this->resourceMetadataCollectionFactory->create($resourceClass)->getOperation(null, false, true);
$context['operation'] = $this->resourceMetadataCollectionFactory->create($resourceClass)->getOperation(null, false, true);
}
$context = $this->initContext($resourceClass, $context);
$metadata = $this->addJsonLdContext($this->contextBuilder, $resourceClass, $context);
Expand All @@ -117,7 +118,7 @@ public function normalize(mixed $data, ?string $format = null, array $context =
}

// Special case: non-resource got serialized and contains a resource therefore we need to reset part of the context
if ($previousResourceClass !== $resourceClass && $resourceClass !== $outputClass) {
if ($previousResourceClass !== $resourceClass) {
unset($context['operation'], $context['operation_name'], $context['output']);
}

Expand Down
5 changes: 0 additions & 5 deletions src/Laravel/ApiPlatformProvider.php
Original file line number Diff line number Diff line change
Expand Up @@ -811,7 +811,6 @@ public function register(): void
$this->app->singleton(HalObjectNormalizer::class, static function (Application $app) {
return new HalObjectNormalizer(
$app->make(ObjectNormalizer::class),
$app->make(IriConverterInterface::class)
);
});

Expand Down Expand Up @@ -1165,8 +1164,6 @@ public function register(): void
return new JsonApiObjectNormalizer(
$app->make(ObjectNormalizer::class),
$app->make(IriConverterInterface::class),
$app->make(ResourceClassResolverInterface::class),
$app->make(ResourceMetadataCollectionFactoryInterface::class),
);
});

Expand Down Expand Up @@ -1500,8 +1497,6 @@ private function registerGraphQl(): void
$this->app->singleton(GraphQlObjectNormalizer::class, static function (Application $app) {
return new GraphQlObjectNormalizer(
$app->make(ObjectNormalizer::class),
$app->make(IriConverterInterface::class),
$app->make(IdentifiersExtractorInterface::class),
);
});

Expand Down
32 changes: 21 additions & 11 deletions src/Serializer/AbstractItemNormalizer.php
Original file line number Diff line number Diff line change
Expand Up @@ -164,18 +164,16 @@ public function normalize(mixed $data, ?string $format = null, array $context =
// Prevent force_resource_class from leaking to child property normalizations
unset($context['force_resource_class']);
if ($outputClass = $this->getOutputClass($context)) {
if (!$this->serializer instanceof NormalizerInterface) {
throw new LogicException('Cannot normalize the output because the injected serializer is not a normalizer');
}

unset($context['output'], $context['operation'], $context['operation_name']);
$context['resource_class'] = $outputClass;
$context['api_sub_level'] = true;
$context['api_platform_output'] = true;
$context['api_platform_output_class'] = $outputClass;
$context[self::ALLOW_EXTRA_ATTRIBUTES] = false;
if ($this->isCollected($outputClass)) {
$context = $this->switchToOutputContext($context, $outputClass);
$resourceClass = $outputClass;
} else {
if (!$this->serializer instanceof NormalizerInterface) {
throw new LogicException('Cannot normalize the output because the injected serializer is not a normalizer');
}

return $this->serializer->normalize($data, $format, $context);
return $this->serializer->normalize($data, $format, $this->switchToOutputContext($context, $outputClass));
}
}

// Never remove this, with `application/json` we don't use our AbstractCollectionNormalizer and we need
Expand Down Expand Up @@ -1337,6 +1335,18 @@ protected function normalizeCollectionOfRelations(ApiProperty $propertyMetadata,
return $value;
}

protected function switchToOutputContext(array $context, string $outputClass): array
{
unset($context['output'], $context['operation'], $context['operation_name']);
$context['resource_class'] = $outputClass;
$context['api_sub_level'] = true;
$context['api_platform_output'] = true;
$context['api_platform_output_class'] = $outputClass;
$context[self::ALLOW_EXTRA_ATTRIBUTES] = false;

return $context;
}

protected function isCollected(string $class): bool
{
return $this->resourceClassResolver->isResourceClass($class) && ($this->resourceMetadataCollectionFactory?->create($class)->isCollected() ?? false);
Expand Down
21 changes: 21 additions & 0 deletions src/Serializer/Tests/Fixtures/ApiResource/CollectedOutputDto.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
<?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\Serializer\Tests\Fixtures\ApiResource;

final class CollectedOutputDto
{
public function __construct(public string $name = '')
{
}
}
Loading