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
110 changes: 110 additions & 0 deletions src/JsonLd/Serializer/ItemNormalizerTrait.php
Original file line number Diff line number Diff line change
Expand Up @@ -50,6 +50,8 @@ trait ItemNormalizerTrait
'@vocab',
];

private const ACTIVE_CONTEXT = 'jsonld_active_context';

/**
* @throws NotNormalizableValueException
*/
Expand All @@ -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)) {
Expand All @@ -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<string, string>} $activeContext
*
* @return array{'@vocab'?: string, terms?: array<string, string>}
*/
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<string, string>} $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);
Expand Down
4 changes: 4 additions & 0 deletions src/JsonLd/Serializer/ObjectNormalizer.php
Original file line number Diff line number Diff line change
Expand Up @@ -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;
}
Expand Down
4 changes: 4 additions & 0 deletions src/Serializer/AbstractItemNormalizer.php
Original file line number Diff line number Diff line change
Expand Up @@ -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);
}
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
<?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\JsonLdTypeDiscriminator;

final class LikeAction extends ReviewAction
{
public ?string $object = null;
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
<?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\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;
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,41 @@
<?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\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;
}
}
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\Tests\Fixtures\TestBundle\ApiResource\JsonLdTypeDiscriminator;

final class ShareAction extends ReviewAction
{
public ?string $object = null;

public ?string $recipient = null;
}
13 changes: 13 additions & 0 deletions tests/Functional/DiscriminatedInputDtoTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -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', [
Expand Down
80 changes: 80 additions & 0 deletions tests/Functional/JsonLd/TypeDiscriminatorTest.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\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);
}
}
Loading