Skip to content
Closed
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
23 changes: 22 additions & 1 deletion src/Serializer/AbstractItemNormalizer.php
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@
use ApiPlatform\Metadata\Exception\AccessDeniedException;
use ApiPlatform\Metadata\Exception\InvalidArgumentException;
use ApiPlatform\Metadata\Exception\ItemNotFoundException;
use ApiPlatform\Metadata\HttpOperation;
use ApiPlatform\Metadata\IriConverterInterface;
use ApiPlatform\Metadata\Property\Factory\PropertyMetadataFactoryInterface;
use ApiPlatform\Metadata\Property\Factory\PropertyNameCollectionFactoryInterface;
Expand Down Expand Up @@ -97,7 +98,27 @@ public function supportsNormalization(mixed $data, ?string $format = null, array
return false;
}

$class = $context['force_resource_class'] ?? $this->getObjectClass($data);
if (isset($context['force_resource_class'])) {
if (is_a($data, $context['force_resource_class'], true)) {
$class = $context['force_resource_class'];
} else {
// force_resource_class is used for the stateOptions pattern (entity/model backing a DTO resource).
// Verify the object class matches the expected entity/model class from stateOptions
// to prevent context leakage from intercepting unrelated types (e.g., DateTimeImmutable).
$objectClass = $this->getObjectClass($data);
$operation = $context['operation'] ?? $context['root_operation'] ?? null;
$stateOptions = $operation instanceof HttpOperation ? $operation->getStateOptions() : null;
$expectedClass = $stateOptions && method_exists($stateOptions, 'getEntityClass')
? $stateOptions->getEntityClass()
: ($stateOptions && method_exists($stateOptions, 'getModelClass') ? $stateOptions->getModelClass() : null);
$class = $expectedClass === $objectClass
? $context['force_resource_class']
: $objectClass;
}
} else {
$class = $this->getObjectClass($data);
}

if (($context['output']['class'] ?? null) === $class) {
return true;
}
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,45 @@
<?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\ApiResource;

use ApiPlatform\Metadata\ApiResource;
use ApiPlatform\Metadata\Get;
use ApiPlatform\Metadata\Operation;

#[ApiResource(
operations: [
new Get(
uriTemplate: '/datetime_normalization_issues/{id}',
provider: [self::class, 'provide']
),
]
)]
class DateTimeNormalizationIssue
{
public function __construct(
public ?int $id = null,
public ?string $name = null,
public ?\DateTimeImmutable $updatedAt = null,
) {
}

public static function provide(Operation $operation, array $uriVariables = [], array $context = []): self
{
return new self(
id: (int) ($uriVariables['id'] ?? 1),
name: 'Test Resource',
updatedAt: new \DateTimeImmutable('2024-01-15T10:30:00+00:00'),
);
}
}
80 changes: 80 additions & 0 deletions tests/Functional/DateTimeNormalizerPriorityTest.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,80 @@
<?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;

use ApiPlatform\Symfony\Bundle\Test\ApiTestCase;
use ApiPlatform\Tests\Fixtures\TestBundle\ApiResource\DateTimeNormalizationIssue;
use ApiPlatform\Tests\SetupClassResourcesTrait;

/**
* Tests that ItemNormalizer does not intercept DateTimeImmutable objects
* before Symfony's DateTimeNormalizer when context leaks through custom normalizers.
*
* @see https://github.com/api-platform/core/issues/7733
*/
final class DateTimeNormalizerPriorityTest extends ApiTestCase
{
use SetupClassResourcesTrait;

protected static ?bool $alwaysBootKernel = false;

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

public function testDateTimeImmutableIsNormalizedAsString(): void
{
$response = self::createClient()->request('GET', '/datetime_normalization_issues/1');

$this->assertResponseIsSuccessful();

$data = $response->toArray();

$this->assertSame(1, $data['id']);
$this->assertSame('Test Resource', $data['name']);
$this->assertArrayHasKey('updatedAt', $data);
$this->assertIsString($data['updatedAt']);
$this->assertStringContainsString('2024-01-15', $data['updatedAt']);
}

/**
* Tests that ItemNormalizer::supportsNormalization returns false for DateTimeImmutable
* even when force_resource_class leaks through context from a parent resource normalization.
*
* This reproduces the bug in https://github.com/api-platform/core/issues/7733
* where a custom normalizer delegates DateTimeImmutable normalization to the serializer
* with a context containing force_resource_class, causing ItemNormalizer to intercept it.
*/
public function testDateTimeImmutableIsNotInterceptedByItemNormalizer(): void
{
self::bootKernel();
$serializer = self::getContainer()->get('serializer');

// Simulate a custom normalizer that delegates DateTimeImmutable normalization
// with a context that still contains force_resource_class from the parent resource
$dateTime = new \DateTimeImmutable('2024-01-15T10:30:00+00:00');
$result = $serializer->normalize($dateTime, 'jsonld', [
'force_resource_class' => DateTimeNormalizationIssue::class,
]);

// DateTimeNormalizer should handle this, producing a string
// ItemNormalizer must NOT intercept it (which would throw a LogicException)
$this->assertIsString($result);
$this->assertStringContainsString('2024-01-15', $result);
}
}
Loading