From 655d50ce808054cd69573fff87dbce93bb00144b Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?K=C3=A9vin=20Dunglas?= Date: Mon, 28 Sep 2026 13:15:18 +0200 Subject: [PATCH 1/2] fix(serializer): 400 on non-string discriminator A non-string type property value reached ClassDiscriminatorMapping::getClassForType() and raised a TypeError, turning a malformed payload into a 500. --- src/Serializer/AbstractItemNormalizer.php | 4 ++++ tests/Functional/DiscriminatedInputDtoTest.php | 13 +++++++++++++ 2 files changed, 17 insertions(+) diff --git a/src/Serializer/AbstractItemNormalizer.php b/src/Serializer/AbstractItemNormalizer.php index c08a967ad45..7048a670927 100644 --- a/src/Serializer/AbstractItemNormalizer.php +++ b/src/Serializer/AbstractItemNormalizer.php @@ -503,6 +503,10 @@ protected function getClassDiscriminatorResolvedClass(array $data, string $class } $type = $data[$mapping->getTypeProperty()] ?? $defaultType; + if (!\is_string($type)) { + throw NotNormalizableValueException::createForUnexpectedDataType(\sprintf('The type property "%s" for the abstract object "%s" must be a string.', $mapping->getTypeProperty(), $class), $type, ['string'], isset($context['deserialization_path']) ? $context['deserialization_path'].'.'.$mapping->getTypeProperty() : $mapping->getTypeProperty()); + } + if (null === ($mappedClass = $mapping->getClassForType($type))) { throw NotNormalizableValueException::createForUnexpectedDataType(\sprintf('The type "%s" is not a valid value.', $type), $type, ['string'], isset($context['deserialization_path']) ? $context['deserialization_path'].'.'.$mapping->getTypeProperty() : $mapping->getTypeProperty(), true); } diff --git a/tests/Functional/DiscriminatedInputDtoTest.php b/tests/Functional/DiscriminatedInputDtoTest.php index ce4f3449a48..b597aa119de 100644 --- a/tests/Functional/DiscriminatedInputDtoTest.php +++ b/tests/Functional/DiscriminatedInputDtoTest.php @@ -49,6 +49,19 @@ public function testObjectTypedSubclassOnlyConstructorArgumentIsDenormalized(): ]); } + public function testNonStringTypePropertyIsRejected(): void + { + self::createClient()->request('POST', '/discriminated_notification_channels', [ + 'headers' => ['Content-Type' => 'application/ld+json'], + 'json' => [ + 'type' => ['webhook'], + 'config' => ['url' => 'https://example.com/hook'], + ], + ]); + + $this->assertResponseStatusCodeSame(400); + } + public function testObjectTypedSubclassOnlyPropertyIsDenormalizedOnPatch(): void { self::createClient()->request('PATCH', '/discriminated_notification_channels/1', [ From 6fba4a3e2c4e4900c0165d2994ae26a087be868b Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?K=C3=A9vin=20Dunglas?= Date: Mon, 28 Sep 2026 13:15:18 +0200 Subject: [PATCH 2/2] feat(jsonld): expand IRIs in @type discriminators When a #[DiscriminatorMap] uses @type as its type property, the JSON-LD denormalizer expands the payload types and the mapping keys against the request's inline @context (@vocab, prefixes and term definitions) before matching them. An array @type resolves to its first mapped value. Remote contexts are not dereferenced. Non-resource outputs now keep the @type written by the discriminator instead of the class short name. --- src/JsonLd/Serializer/ItemNormalizerTrait.php | 110 ++++++++++++++++++ src/JsonLd/Serializer/ObjectNormalizer.php | 4 + .../JsonLdTypeDiscriminator/LikeAction.php | 19 +++ .../JsonLdTypeDiscriminator/ReviewAction.php | 25 ++++ .../ReviewActionResource.php | 41 +++++++ .../JsonLdTypeDiscriminator/ShareAction.php | 21 ++++ .../JsonLd/TypeDiscriminatorTest.php | 80 +++++++++++++ 7 files changed, 300 insertions(+) create mode 100644 tests/Fixtures/TestBundle/ApiResource/JsonLdTypeDiscriminator/LikeAction.php create mode 100644 tests/Fixtures/TestBundle/ApiResource/JsonLdTypeDiscriminator/ReviewAction.php create mode 100644 tests/Fixtures/TestBundle/ApiResource/JsonLdTypeDiscriminator/ReviewActionResource.php create mode 100644 tests/Fixtures/TestBundle/ApiResource/JsonLdTypeDiscriminator/ShareAction.php create mode 100644 tests/Functional/JsonLd/TypeDiscriminatorTest.php diff --git a/src/JsonLd/Serializer/ItemNormalizerTrait.php b/src/JsonLd/Serializer/ItemNormalizerTrait.php index 6fc79042078..f9798901115 100644 --- a/src/JsonLd/Serializer/ItemNormalizerTrait.php +++ b/src/JsonLd/Serializer/ItemNormalizerTrait.php @@ -50,6 +50,8 @@ trait ItemNormalizerTrait '@vocab', ]; + private const ACTIVE_CONTEXT = 'jsonld_active_context'; + /** * @throws NotNormalizableValueException */ @@ -59,6 +61,10 @@ public function denormalize(mixed $data, string $type, ?string $format = null, a throw NotNormalizableValueException::createForUnexpectedDataType(\sprintf('The type of the "@id" attribute must be "string", "%s" given.', \gettype($data['@id'])), $data['@id'], ['string'], isset($context['deserialization_path']) ? $context['deserialization_path'].'.@id' : '@id', true); } + if (\is_array($data) && \array_key_exists('@context', $data)) { + $context[self::ACTIVE_CONTEXT] = $this->processLocalContext($context[self::ACTIVE_CONTEXT] ?? [], $data['@context']); + } + // Avoid issues with proxies if we populated the object if (isset($data['@id']) && !isset($context[AbstractItemNormalizer::OBJECT_TO_POPULATE])) { if (true !== ($context['api_allow_update'] ?? true)) { @@ -82,6 +88,110 @@ public function denormalize(mixed $data, string $type, ?string $format = null, a return parent::denormalize($data, $type, $format, $context); } + protected function getClassDiscriminatorResolvedClass(array $data, string $class, array $context = []): string + { + $mapping = $this->classDiscriminatorResolver?->getMappingForClass($class); + if ('@type' !== $mapping?->getTypeProperty() || !isset($data['@type']) || \is_string($data['@type']) && null !== $mapping->getClassForType($data['@type'])) { + return parent::getClassDiscriminatorResolvedClass($data, $class, $context); + } + + $activeContext = $context[self::ACTIVE_CONTEXT] ?? []; + $path = isset($context['deserialization_path']) ? $context['deserialization_path'].'.@type' : '@type'; + $types = \is_array($data['@type']) && array_is_list($data['@type']) ? $data['@type'] : [$data['@type']]; + + foreach ($types as $type) { + if (!\is_string($type)) { + throw NotNormalizableValueException::createForUnexpectedDataType(\sprintf('The "@type" of the abstract object "%s" must be a string or an array of strings.', $class), $data['@type'], ['string', 'array'], $path); + } + + $expandedType = $this->expandIri($type, $activeContext); + foreach ($mapping->getTypesMapping() as $mappedType => $mappedClass) { + if ($expandedType === $this->expandIri((string) $mappedType, $activeContext)) { + return $mappedClass; + } + } + } + + throw NotNormalizableValueException::createForUnexpectedDataType(\sprintf('The type "%s" is not a valid value.', implode('", "', $types)), $data['@type'], ['string'], $path, true); + } + + /** + * Folds a local @context into the active one; remote contexts are not dereferenced. + * + * @param array{'@vocab'?: string, terms?: array} $activeContext + * + * @return array{'@vocab'?: string, terms?: array} + */ + private function processLocalContext(array $activeContext, mixed $localContext): array + { + if (null === $localContext) { + return []; + } + + if (!\is_array($localContext)) { + return $activeContext; + } + + if (array_is_list($localContext)) { + foreach ($localContext as $context) { + $activeContext = $this->processLocalContext($activeContext, $context); + } + + return $activeContext; + } + + foreach ($localContext as $key => $definition) { + if ('@vocab' === $key) { + if (\is_string($definition)) { + $activeContext['@vocab'] = $this->expandIri($definition, $activeContext); + } else { + unset($activeContext['@vocab']); + } + + continue; + } + + if (str_starts_with((string) $key, '@')) { + continue; + } + + $iri = \is_array($definition) ? $definition['@id'] ?? null : $definition; + if (\is_string($iri)) { + $activeContext['terms'][$key] = $iri; + } else { + unset($activeContext['terms'][$key]); + } + } + + return $activeContext; + } + + /** + * @param array{'@vocab'?: string, terms?: array} $activeContext + */ + private function expandIri(string $value, array $activeContext, int $depth = 0): string + { + // guards against cyclic term definitions + if ($depth > 8 || str_starts_with($value, '@')) { + return $value; + } + + if (isset($activeContext['terms'][$value]) && $activeContext['terms'][$value] !== $value) { + return $this->expandIri($activeContext['terms'][$value], $activeContext, $depth + 1); + } + + if (str_contains($value, ':')) { + [$prefix, $suffix] = explode(':', $value, 2); + if ('_' === $prefix || str_starts_with($suffix, '//') || !isset($activeContext['terms'][$prefix])) { + return $value; + } + + return $this->expandIri($activeContext['terms'][$prefix], $activeContext, $depth + 1).$suffix; + } + + return isset($activeContext['@vocab']) ? $activeContext['@vocab'].$value : $value; + } + protected function getAllowedAttributes(string|object $classOrObject, array $context, bool $attributesAsString = false): array|bool { $allowedAttributes = parent::getAllowedAttributes($classOrObject, $context, $attributesAsString); diff --git a/src/JsonLd/Serializer/ObjectNormalizer.php b/src/JsonLd/Serializer/ObjectNormalizer.php index 9631ff755ea..6da3b7782f2 100644 --- a/src/JsonLd/Serializer/ObjectNormalizer.php +++ b/src/JsonLd/Serializer/ObjectNormalizer.php @@ -70,6 +70,10 @@ public function normalize(mixed $data, ?string $format = null, array $context = } $metadata = $this->createJsonLdContext($this->anonymousContextBuilder, $data, $context); + // an explicit @type, such as a discriminator map value, beats the short name + if (isset($normalizedData['@type'])) { + $metadata['@type'] = $normalizedData['@type']; + } return $metadata + $normalizedData; } diff --git a/tests/Fixtures/TestBundle/ApiResource/JsonLdTypeDiscriminator/LikeAction.php b/tests/Fixtures/TestBundle/ApiResource/JsonLdTypeDiscriminator/LikeAction.php new file mode 100644 index 00000000000..f5e607b53b6 --- /dev/null +++ b/tests/Fixtures/TestBundle/ApiResource/JsonLdTypeDiscriminator/LikeAction.php @@ -0,0 +1,19 @@ + + * + * 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\JsonLdTypeDiscriminator; + +final class LikeAction extends ReviewAction +{ + public ?string $object = null; +} diff --git a/tests/Fixtures/TestBundle/ApiResource/JsonLdTypeDiscriminator/ReviewAction.php b/tests/Fixtures/TestBundle/ApiResource/JsonLdTypeDiscriminator/ReviewAction.php new file mode 100644 index 00000000000..50e2c8f3b9f --- /dev/null +++ b/tests/Fixtures/TestBundle/ApiResource/JsonLdTypeDiscriminator/ReviewAction.php @@ -0,0 +1,25 @@ + + * + * 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\JsonLdTypeDiscriminator; + +use Symfony\Component\Serializer\Attribute\DiscriminatorMap; + +#[DiscriminatorMap(typeProperty: '@type', mapping: [ + 'https://schema.org/LikeAction' => LikeAction::class, + 'https://schema.org/ShareAction' => ShareAction::class, +])] +abstract class ReviewAction +{ + public ?string $actionStatus = null; +} diff --git a/tests/Fixtures/TestBundle/ApiResource/JsonLdTypeDiscriminator/ReviewActionResource.php b/tests/Fixtures/TestBundle/ApiResource/JsonLdTypeDiscriminator/ReviewActionResource.php new file mode 100644 index 00000000000..d412a36d569 --- /dev/null +++ b/tests/Fixtures/TestBundle/ApiResource/JsonLdTypeDiscriminator/ReviewActionResource.php @@ -0,0 +1,41 @@ + + * + * 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\JsonLdTypeDiscriminator; + +use ApiPlatform\Metadata\ApiResource; +use ApiPlatform\Metadata\Operation; +use ApiPlatform\Metadata\Post; + +#[ApiResource( + operations: [ + new Post( + uriTemplate: '/jsonld_type_discriminator_actions', + status: 200, + input: ReviewAction::class, + output: ReviewAction::class, + processor: [self::class, 'process'], + ), + ] +)] +final class ReviewActionResource +{ + public ?int $id = null; + + public static function process(ReviewAction $data, Operation $operation, array $uriVariables = [], array $context = []): ReviewAction + { + $data->actionStatus = 'CompletedActionStatus'; + + return $data; + } +} diff --git a/tests/Fixtures/TestBundle/ApiResource/JsonLdTypeDiscriminator/ShareAction.php b/tests/Fixtures/TestBundle/ApiResource/JsonLdTypeDiscriminator/ShareAction.php new file mode 100644 index 00000000000..da780bcf7df --- /dev/null +++ b/tests/Fixtures/TestBundle/ApiResource/JsonLdTypeDiscriminator/ShareAction.php @@ -0,0 +1,21 @@ + + * + * 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\JsonLdTypeDiscriminator; + +final class ShareAction extends ReviewAction +{ + public ?string $object = null; + + public ?string $recipient = null; +} diff --git a/tests/Functional/JsonLd/TypeDiscriminatorTest.php b/tests/Functional/JsonLd/TypeDiscriminatorTest.php new file mode 100644 index 00000000000..64976972b79 --- /dev/null +++ b/tests/Functional/JsonLd/TypeDiscriminatorTest.php @@ -0,0 +1,80 @@ + + * + * 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\JsonLd; + +use ApiPlatform\Test\ApiTestCase; +use ApiPlatform\Tests\Fixtures\TestBundle\ApiResource\JsonLdTypeDiscriminator\ReviewActionResource; +use ApiPlatform\Tests\SetupClassResourcesTrait; +use PHPUnit\Framework\Attributes\DataProvider; + +final class TypeDiscriminatorTest extends ApiTestCase +{ + use SetupClassResourcesTrait; + + protected static ?bool $alwaysBootKernel = false; + + /** + * @return class-string[] + */ + public static function getResources(): array + { + return [ReviewActionResource::class]; + } + + public static function equivalentTypesProvider(): iterable + { + yield 'absolute IRI' => [['@type' => 'https://schema.org/ShareAction'], 'https://schema.org/ShareAction']; + yield 'compact IRI' => [['@context' => ['schema' => 'https://schema.org/'], '@type' => 'schema:ShareAction'], 'https://schema.org/ShareAction']; + yield 'term with @vocab' => [['@context' => ['@vocab' => 'https://schema.org/'], '@type' => 'ShareAction'], 'https://schema.org/ShareAction']; + yield 'term definition' => [['@context' => ['Share' => ['@id' => 'https://schema.org/ShareAction']], '@type' => 'Share'], 'https://schema.org/ShareAction']; + yield 'context array with a remote context' => [['@context' => ['https://schema.org', ['schema' => 'https://schema.org/']], '@type' => 'schema:LikeAction'], 'https://schema.org/LikeAction']; + yield 'array, first mapped type wins' => [['@context' => ['schema' => 'https://schema.org/'], '@type' => ['https://example.com/Unknown', 'schema:LikeAction', 'schema:ShareAction']], 'https://schema.org/LikeAction']; + } + + #[DataProvider('equivalentTypesProvider')] + public function testEquivalentTypesResolveTheSameClass(array $payload, string $expectedType): void + { + self::createClient()->request('POST', '/jsonld_type_discriminator_actions', [ + 'headers' => ['Content-Type' => 'application/ld+json'], + 'json' => $payload + ['object' => '/books/1'], + ]); + + $this->assertResponseIsSuccessful(); + $this->assertJsonContains([ + '@type' => $expectedType, + 'actionStatus' => 'CompletedActionStatus', + 'object' => '/books/1', + ]); + } + + public static function invalidTypesProvider(): iterable + { + yield 'unresolvable term' => ['ShareAction']; + yield 'unmapped IRI' => ['https://schema.org/BuyAction']; + yield 'integer' => [42]; + yield 'object' => [['@id' => 'https://schema.org/ShareAction']]; + yield 'array without any mapped type' => [['https://schema.org/BuyAction', 42]]; + } + + #[DataProvider('invalidTypesProvider')] + public function testInvalidTypeIsRejected(mixed $type): void + { + self::createClient()->request('POST', '/jsonld_type_discriminator_actions', [ + 'headers' => ['Content-Type' => 'application/ld+json'], + 'json' => ['@type' => $type, 'object' => '/books/1'], + ]); + + $this->assertResponseStatusCodeSame(400); + } +}