From 2dee99eada2b31e3e8222caa6b6056d0a2b966e6 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?K=C3=A9vin=20Dunglas?= Date: Mon, 28 Sep 2026 14:52:02 +0200 Subject: [PATCH 1/2] feat(jsonld): operations as schema.org actions Operations flagged with extraProperties: ['potential_action' => true] are listed under potentialAction in the JSON-LD representation of the GET item (operations with URI variables) or collection (operations without) they belong to. An @type discriminated input yields one action per mapping key; other operations use their hydra @type or a default derived from the HTTP method. Required input properties are annotated with -input. The resource context scopes potentialAction to the schema.org vocabulary. --- src/JsonLd/ContextBuilder.php | 14 +- .../Serializer/PotentialActionNormalizer.php | 193 ++++++++++++++++++ src/Laravel/ApiPlatformProvider.php | 16 +- src/Symfony/Bundle/Resources/config/hydra.php | 14 ++ .../Bundle/Resources/config/jsonld.php | 14 ++ .../PotentialAction/ActionableBook.php | 88 ++++++++ .../PotentialAction/ArchiveBookInput.php | 22 ++ .../PotentialAction/BookLikeAction.php | 18 ++ .../PotentialAction/BookReviewAction.php | 24 +++ .../PotentialAction/BookShareAction.php | 22 ++ .../Functional/JsonLd/PotentialActionTest.php | 81 ++++++++ 11 files changed, 503 insertions(+), 3 deletions(-) create mode 100644 src/JsonLd/Serializer/PotentialActionNormalizer.php create mode 100644 tests/Fixtures/TestBundle/ApiResource/PotentialAction/ActionableBook.php create mode 100644 tests/Fixtures/TestBundle/ApiResource/PotentialAction/ArchiveBookInput.php create mode 100644 tests/Fixtures/TestBundle/ApiResource/PotentialAction/BookLikeAction.php create mode 100644 tests/Fixtures/TestBundle/ApiResource/PotentialAction/BookReviewAction.php create mode 100644 tests/Fixtures/TestBundle/ApiResource/PotentialAction/BookShareAction.php create mode 100644 tests/Functional/JsonLd/PotentialActionTest.php diff --git a/src/JsonLd/ContextBuilder.php b/src/JsonLd/ContextBuilder.php index 7564f1ce78..f072155143 100644 --- a/src/JsonLd/ContextBuilder.php +++ b/src/JsonLd/ContextBuilder.php @@ -14,6 +14,7 @@ namespace ApiPlatform\JsonLd; use ApiPlatform\JsonLd\Serializer\HydraPrefixTrait; +use ApiPlatform\JsonLd\Serializer\PotentialActionNormalizer; use ApiPlatform\Metadata\ApiProperty; use ApiPlatform\Metadata\Exception\RuntimeException; use ApiPlatform\Metadata\Get; @@ -92,7 +93,18 @@ public function getResourceContext(string $resourceClass, int $referenceType = U // Every operation resolves to this same /contexts/{shortName} URI, so union their groups. $sharedGroups = $this->getOperationsGroups($resourceMetadataCollection, $operation->getShortName()); - return $this->buildOperationContext($operation, $resourceClass, $referenceType, $sharedGroups); + $context = $this->buildOperationContext($operation, $resourceClass, $referenceType, $sharedGroups); + foreach ($resourceMetadataCollection as $resource) { + foreach ($resource->getOperations() ?? [] as $resourceOperation) { + if (true === ($resourceOperation->getExtraProperties()[PotentialActionNormalizer::EXTRA_PROPERTY] ?? false)) { + $context['potentialAction'] = PotentialActionNormalizer::JSONLD_CONTEXT; + + return $context; + } + } + } + + return $context; } /** diff --git a/src/JsonLd/Serializer/PotentialActionNormalizer.php b/src/JsonLd/Serializer/PotentialActionNormalizer.php new file mode 100644 index 0000000000..1eb5b6055f --- /dev/null +++ b/src/JsonLd/Serializer/PotentialActionNormalizer.php @@ -0,0 +1,193 @@ + + * + * 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\JsonLd\Serializer; + +use ApiPlatform\Metadata\HttpOperation; +use ApiPlatform\Metadata\IdentifiersExtractorInterface; +use ApiPlatform\Metadata\Property\Factory\PropertyMetadataFactoryInterface; +use ApiPlatform\Metadata\Property\Factory\PropertyNameCollectionFactoryInterface; +use ApiPlatform\Metadata\Resource\Factory\ResourceMetadataCollectionFactoryInterface; +use ApiPlatform\Metadata\UrlGeneratorInterface; +use Symfony\Component\Serializer\Mapping\ClassDiscriminatorResolverInterface; +use Symfony\Component\Serializer\NameConverter\NameConverterInterface; +use Symfony\Component\Serializer\Normalizer\NormalizerAwareInterface; +use Symfony\Component\Serializer\Normalizer\NormalizerInterface; +use Symfony\Component\Serializer\SerializerAwareInterface; +use Symfony\Component\Serializer\SerializerInterface; + +/** + * Advertises the operations flagged with the "potential_action" extra property as schema.org potential actions. + * + * @see https://schema.org/docs/actions.html + */ +final class PotentialActionNormalizer implements NormalizerInterface, NormalizerAwareInterface, SerializerAwareInterface +{ + public const EXTRA_PROPERTY = 'potential_action'; + + public const JSONLD_CONTEXT = [ + '@id' => 'https://schema.org/potentialAction', + '@context' => ['@vocab' => 'https://schema.org/', 'schema' => 'https://schema.org/'], + ]; + + private const DEFAULT_TYPES = [ + 'POST' => 'schema:CreateAction', + 'PUT' => 'schema:ReplaceAction', + 'PATCH' => 'schema:UpdateAction', + 'DELETE' => 'schema:DeleteAction', + ]; + + public function __construct( + private readonly NormalizerInterface $decorated, + private readonly ResourceMetadataCollectionFactoryInterface $resourceMetadataCollectionFactory, + private readonly PropertyNameCollectionFactoryInterface $propertyNameCollectionFactory, + private readonly PropertyMetadataFactoryInterface $propertyMetadataFactory, + private readonly IdentifiersExtractorInterface $identifiersExtractor, + private readonly UrlGeneratorInterface $urlGenerator, + private readonly ?ClassDiscriminatorResolverInterface $classDiscriminatorResolver = null, + private readonly ?NameConverterInterface $nameConverter = null, + ) { + } + + public function normalize(mixed $data, ?string $format = null, array $context = []): array|string|int|float|bool|\ArrayObject|null + { + $normalizedData = $this->decorated->normalize($data, $format, $context); + + $operation = $context['operation'] ?? null; + if (!\is_array($normalizedData) || !$operation instanceof HttpOperation || 'GET' !== $operation->getMethod() || null === $operation->getClass() || isset($context['api_sub_level']) || isset($context['api_collection_sub_level'])) { + return $normalizedData; + } + + $isCollection = is_iterable($data); + $actions = []; + foreach ($this->resourceMetadataCollectionFactory->create($operation->getClass()) as $resource) { + foreach ($resource->getOperations() ?? [] as $actionOperation) { + if (!$actionOperation instanceof HttpOperation || true !== ($actionOperation->getExtraProperties()[self::EXTRA_PROPERTY] ?? false) || $isCollection === (bool) $actionOperation->getUriVariables()) { + continue; + } + + if (null !== $target = $this->getTarget($isCollection ? null : $data, $actionOperation)) { + array_push($actions, ...$this->getActions($actionOperation, $target)); + } + } + } + + if ($actions) { + $normalizedData['potentialAction'] = $actions; + } + + return $normalizedData; + } + + public function supportsNormalization(mixed $data, ?string $format = null, array $context = []): bool + { + return $this->decorated->supportsNormalization($data, $format, $context); + } + + public function getSupportedTypes(?string $format): array + { + return $this->decorated->getSupportedTypes($format); + } + + public function setNormalizer(NormalizerInterface $normalizer): void + { + if ($this->decorated instanceof NormalizerAwareInterface) { + $this->decorated->setNormalizer($normalizer); + } + } + + public function setSerializer(SerializerInterface $serializer): void + { + if ($this->decorated instanceof SerializerAwareInterface) { + $this->decorated->setSerializer($serializer); + } + } + + private function getTarget(?object $item, HttpOperation $operation): ?array + { + try { + $identifiers = $item ? $this->identifiersExtractor->getIdentifiersFromItem($item, $operation) : []; + $url = $this->urlGenerator->generate($operation->getRouteName() ?? $operation->getName(), $identifiers, $operation->getUrlGenerationStrategy() ?? UrlGeneratorInterface::ABS_PATH); + } catch (\InvalidArgumentException|\RuntimeException) { + // the item does not carry the operation's URI variables + return null; + } + + $target = ['@type' => 'EntryPoint', 'urlTemplate' => $url, 'httpMethod' => $operation->getMethod()]; + if ($encodingType = $this->getMimeTypes($operation->getInputFormats())) { + $target['encodingType'] = $encodingType; + } + if ($contentType = $this->getMimeTypes($operation->getOutputFormats())) { + $target['contentType'] = $contentType; + } + + return $target; + } + + /** + * @return list> + */ + private function getActions(HttpOperation $operation, array $target): array + { + $inputClass = $operation->getInput()['class'] ?? $operation->getClass(); + $mapping = $inputClass ? $this->classDiscriminatorResolver?->getMappingForClass($inputClass) : null; + + if ('@type' === $mapping?->getTypeProperty()) { + $actions = []; + foreach ($mapping->getTypesMapping() as $type => $class) { + $actions[] = ['@type' => $type, 'target' => $target] + $this->getInputAnnotations($class, $operation); + } + + return $actions; + } + + $hydraTypes = array_filter((array) ($operation->getHydraContext()['@type'] ?? []), static fn ($type): bool => \is_string($type) && !str_starts_with($type, 'hydra:')); + $type = reset($hydraTypes) ?: self::DEFAULT_TYPES[$operation->getMethod()] ?? 'schema:Action'; + + return [['@type' => $type, 'target' => $target] + ($inputClass ? $this->getInputAnnotations($inputClass, $operation) : [])]; + } + + /** + * @return array + */ + private function getInputAnnotations(string $class, HttpOperation $operation): array + { + $options = ($groups = $operation->getDenormalizationContext()['groups'] ?? null) ? ['serializer_groups' => (array) $groups] : []; + + $annotations = []; + foreach ($this->propertyNameCollectionFactory->create($class, $options) as $property) { + $propertyMetadata = $this->propertyMetadataFactory->create($class, $property, $options); + if ($propertyMetadata->isRequired() && false !== $propertyMetadata->isWritable()) { + $annotations[($this->nameConverter?->normalize($property, $class, ItemNormalizer::FORMAT) ?? $property).'-input'] = 'required'; + } + } + + return $annotations; + } + + /** + * @param array>|null $formats + * + * @return string|list|null + */ + private function getMimeTypes(?array $formats): string|array|null + { + $mimeTypes = array_values(array_unique(array_merge(...array_map(static fn ($mimeTypes): array => (array) $mimeTypes, array_values($formats ?? []))))); + + return match (\count($mimeTypes)) { + 0 => null, + 1 => $mimeTypes[0], + default => $mimeTypes, + }; + } +} diff --git a/src/Laravel/ApiPlatformProvider.php b/src/Laravel/ApiPlatformProvider.php index 93cdce910b..89c3d03ef9 100644 --- a/src/Laravel/ApiPlatformProvider.php +++ b/src/Laravel/ApiPlatformProvider.php @@ -76,6 +76,7 @@ use ApiPlatform\JsonLd\Serializer\ItemDenormalizer as JsonLdItemDenormalizer; use ApiPlatform\JsonLd\Serializer\ItemNormalizer as JsonLdItemNormalizer; use ApiPlatform\JsonLd\Serializer\ObjectNormalizer as JsonLdObjectNormalizer; +use ApiPlatform\JsonLd\Serializer\PotentialActionNormalizer as JsonLdPotentialActionNormalizer; use ApiPlatform\JsonSchema\DefinitionNameFactory; use ApiPlatform\JsonSchema\DefinitionNameFactoryInterface; use ApiPlatform\JsonSchema\Metadata\Property\Factory\SchemaPropertyMetadataFactory; @@ -1167,15 +1168,26 @@ public function register(): void }); $this->app->singleton('api_platform_normalizer_list', static function (Application $app) { + $withPotentialActions = static fn (NormalizerInterface $normalizer): JsonLdPotentialActionNormalizer => new JsonLdPotentialActionNormalizer( + $normalizer, + $app->make(ResourceMetadataCollectionFactoryInterface::class), + $app->make(PropertyNameCollectionFactoryInterface::class), + $app->make(PropertyMetadataFactoryInterface::class), + $app->make(IdentifiersExtractorInterface::class), + $app->make(UrlGeneratorInterface::class), + new ClassDiscriminatorFromClassMetadata($app->make(ClassMetadataFactoryInterface::class)), + $app->make(NameConverterInterface::class), + ); + $list = new \SplPriorityQueue(); $list->insert($app->make(HydraEntrypointNormalizer::class), -800); - $list->insert($app->make(HydraPartialCollectionViewNormalizer::class), -800); + $list->insert($withPotentialActions($app->make(HydraPartialCollectionViewNormalizer::class)), -800); $list->insert($app->make(HydraCollectionObjectNormalizer::class), -984); $list->insert($app->make(HalCollectionNormalizer::class), -800); $list->insert($app->make(HalEntrypointNormalizer::class), -985); $list->insert($app->make(HalObjectNormalizer::class), -995); $list->insert($app->make(HalItemNormalizer::class), -890); - $list->insert($app->make(JsonLdItemNormalizer::class), -890); + $list->insert($withPotentialActions($app->make(JsonLdItemNormalizer::class)), -890); $list->insert($app->make(JsonLdItemDenormalizer::class), -889); $list->insert($app->make(JsonLdObjectNormalizer::class), -995); $list->insert($app->make(ArrayDenormalizer::class), -990); diff --git a/src/Symfony/Bundle/Resources/config/hydra.php b/src/Symfony/Bundle/Resources/config/hydra.php index d58cec024d..f2ce486c68 100644 --- a/src/Symfony/Bundle/Resources/config/hydra.php +++ b/src/Symfony/Bundle/Resources/config/hydra.php @@ -22,6 +22,7 @@ use ApiPlatform\Hydra\Serializer\EntrypointNormalizer; use ApiPlatform\Hydra\Serializer\HydraPrefixNameConverter; use ApiPlatform\Hydra\Serializer\PartialCollectionViewNormalizer; +use ApiPlatform\JsonLd\Serializer\PotentialActionNormalizer; return static function (ContainerConfigurator $container) { $services = $container->services(); @@ -105,6 +106,19 @@ '%api_platform.serializer.default_context%', ]); + $services->set('api_platform.hydra.normalizer.collection.potential_action', PotentialActionNormalizer::class) + ->decorate('api_platform.hydra.normalizer.collection', null, 0) + ->args([ + service('api_platform.hydra.normalizer.collection.potential_action.inner'), + service('api_platform.metadata.resource.metadata_collection_factory'), + service('api_platform.metadata.property.name_collection_factory'), + service('api_platform.metadata.property.metadata_factory'), + service('api_platform.api.identifiers_extractor'), + service('api_platform.router'), + service('serializer.mapping.class_discriminator_resolver')->ignoreOnInvalid(), + service('api_platform.name_converter')->ignoreOnInvalid(), + ]); + $services->set('api_platform.hydra.name_converter.hydra_prefix', HydraPrefixNameConverter::class) ->decorate('api_platform.name_converter', null, 0) ->args([ diff --git a/src/Symfony/Bundle/Resources/config/jsonld.php b/src/Symfony/Bundle/Resources/config/jsonld.php index ac34b50c59..3d173a1895 100644 --- a/src/Symfony/Bundle/Resources/config/jsonld.php +++ b/src/Symfony/Bundle/Resources/config/jsonld.php @@ -18,6 +18,7 @@ use ApiPlatform\JsonLd\Serializer\ItemDenormalizer; use ApiPlatform\JsonLd\Serializer\ItemNormalizer; use ApiPlatform\JsonLd\Serializer\ObjectNormalizer; +use ApiPlatform\JsonLd\Serializer\PotentialActionNormalizer; use ApiPlatform\Serializer\JsonEncoder; use ApiPlatform\Symfony\Validator\Serializer\ValidationExceptionNormalizer; @@ -58,6 +59,19 @@ ->tag('serializer.normalizer', ['priority' => -890]) ->tag('kernel.reset', ['method' => '?reset']); + $services->set('api_platform.jsonld.normalizer.item.potential_action', PotentialActionNormalizer::class) + ->decorate('api_platform.jsonld.normalizer.item', null, 0) + ->args([ + service('api_platform.jsonld.normalizer.item.potential_action.inner'), + service('api_platform.metadata.resource.metadata_collection_factory'), + service('api_platform.metadata.property.name_collection_factory'), + service('api_platform.metadata.property.metadata_factory'), + service('api_platform.api.identifiers_extractor'), + service('api_platform.router'), + service('serializer.mapping.class_discriminator_resolver')->ignoreOnInvalid(), + service('api_platform.name_converter')->ignoreOnInvalid(), + ]); + $services->set('api_platform.jsonld.denormalizer.item', ItemDenormalizer::class) ->args([ service('api_platform.metadata.resource.metadata_collection_factory'), diff --git a/tests/Fixtures/TestBundle/ApiResource/PotentialAction/ActionableBook.php b/tests/Fixtures/TestBundle/ApiResource/PotentialAction/ActionableBook.php new file mode 100644 index 0000000000..d82e120fef --- /dev/null +++ b/tests/Fixtures/TestBundle/ApiResource/PotentialAction/ActionableBook.php @@ -0,0 +1,88 @@ + + * + * 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\PotentialAction; + +use ApiPlatform\Metadata\ApiProperty; +use ApiPlatform\Metadata\ApiResource; +use ApiPlatform\Metadata\Get; +use ApiPlatform\Metadata\GetCollection; +use ApiPlatform\Metadata\Link; +use ApiPlatform\Metadata\Operation; +use ApiPlatform\Metadata\Post; +use Symfony\Component\Validator\Constraints as Assert; + +#[ApiResource( + operations: [ + new Get(uriTemplate: '/actionable_books/{id}', provider: [self::class, 'provide']), + new GetCollection(uriTemplate: '/actionable_books', provider: [self::class, 'provideCollection']), + new Post(uriTemplate: '/actionable_books', processor: [self::class, 'process'], extraProperties: ['potential_action' => true]), + new Post( + uriTemplate: '/actionable_books/{id}/reviews', + uriVariables: ['id' => new Link(fromClass: self::class)], + input: BookReviewAction::class, + output: false, + provider: [self::class, 'provide'], + processor: [self::class, 'process'], + extraProperties: ['potential_action' => true], + ), + new Post( + uriTemplate: '/actionable_books/{id}/archive', + uriVariables: ['id' => new Link(fromClass: self::class)], + input: ArchiveBookInput::class, + output: false, + hydraContext: ['@type' => ['hydra:Operation', 'schema:ArchiveAction']], + provider: [self::class, 'provide'], + processor: [self::class, 'process'], + extraProperties: ['potential_action' => true], + ), + new Post( + uriTemplate: '/actionable_books/{id}/restore', + uriVariables: ['id' => new Link(fromClass: self::class)], + input: ArchiveBookInput::class, + output: false, + provider: [self::class, 'provide'], + processor: [self::class, 'process'], + ), + ] +)] +final class ActionableBook +{ + #[ApiProperty(identifier: true)] + public ?int $id = null; + + #[Assert\NotBlank] + public ?string $title = null; + + public static function provide(Operation $operation, array $uriVariables = [], array $context = []): self + { + $book = new self(); + $book->id = (int) $uriVariables['id']; + $book->title = 'Candide'; + + return $book; + } + + /** + * @return list + */ + public static function provideCollection(Operation $operation, array $uriVariables = [], array $context = []): array + { + return [self::provide($operation, ['id' => 1])]; + } + + public static function process(mixed $data, Operation $operation, array $uriVariables = [], array $context = []): mixed + { + return $data; + } +} diff --git a/tests/Fixtures/TestBundle/ApiResource/PotentialAction/ArchiveBookInput.php b/tests/Fixtures/TestBundle/ApiResource/PotentialAction/ArchiveBookInput.php new file mode 100644 index 0000000000..68063aa907 --- /dev/null +++ b/tests/Fixtures/TestBundle/ApiResource/PotentialAction/ArchiveBookInput.php @@ -0,0 +1,22 @@ + + * + * 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\PotentialAction; + +use Symfony\Component\Validator\Constraints as Assert; + +final class ArchiveBookInput +{ + #[Assert\NotBlank] + public ?string $reason = null; +} diff --git a/tests/Fixtures/TestBundle/ApiResource/PotentialAction/BookLikeAction.php b/tests/Fixtures/TestBundle/ApiResource/PotentialAction/BookLikeAction.php new file mode 100644 index 0000000000..36cf59a29c --- /dev/null +++ b/tests/Fixtures/TestBundle/ApiResource/PotentialAction/BookLikeAction.php @@ -0,0 +1,18 @@ + + * + * 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\PotentialAction; + +final class BookLikeAction extends BookReviewAction +{ +} diff --git a/tests/Fixtures/TestBundle/ApiResource/PotentialAction/BookReviewAction.php b/tests/Fixtures/TestBundle/ApiResource/PotentialAction/BookReviewAction.php new file mode 100644 index 0000000000..b7bfb946c7 --- /dev/null +++ b/tests/Fixtures/TestBundle/ApiResource/PotentialAction/BookReviewAction.php @@ -0,0 +1,24 @@ + + * + * 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\PotentialAction; + +use Symfony\Component\Serializer\Attribute\DiscriminatorMap; + +#[DiscriminatorMap(typeProperty: '@type', mapping: [ + 'LikeAction' => BookLikeAction::class, + 'ShareAction' => BookShareAction::class, +])] +abstract class BookReviewAction +{ +} diff --git a/tests/Fixtures/TestBundle/ApiResource/PotentialAction/BookShareAction.php b/tests/Fixtures/TestBundle/ApiResource/PotentialAction/BookShareAction.php new file mode 100644 index 0000000000..09dcb0d554 --- /dev/null +++ b/tests/Fixtures/TestBundle/ApiResource/PotentialAction/BookShareAction.php @@ -0,0 +1,22 @@ + + * + * 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\PotentialAction; + +use Symfony\Component\Validator\Constraints as Assert; + +final class BookShareAction extends BookReviewAction +{ + #[Assert\NotBlank] + public ?string $recipient = null; +} diff --git a/tests/Functional/JsonLd/PotentialActionTest.php b/tests/Functional/JsonLd/PotentialActionTest.php new file mode 100644 index 0000000000..9343cef4f1 --- /dev/null +++ b/tests/Functional/JsonLd/PotentialActionTest.php @@ -0,0 +1,81 @@ + + * + * 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\PotentialAction\ActionableBook; +use ApiPlatform\Tests\SetupClassResourcesTrait; + +final class PotentialActionTest extends ApiTestCase +{ + use SetupClassResourcesTrait; + + protected static ?bool $alwaysBootKernel = false; + + /** + * @return class-string[] + */ + public static function getResources(): array + { + return [ActionableBook::class]; + } + + public function testItemAdvertisesItemLevelActions(): void + { + $response = self::createClient()->request('GET', '/actionable_books/1', ['headers' => ['Accept' => 'application/ld+json']]); + $this->assertResponseIsSuccessful(); + + $actions = $response->toArray()['potentialAction']; + $this->assertSame(['LikeAction', 'ShareAction', 'schema:ArchiveAction'], array_column($actions, '@type')); + + $this->assertSame('EntryPoint', $actions[0]['target']['@type']); + $this->assertSame('/actionable_books/1/reviews', $actions[0]['target']['urlTemplate']); + $this->assertSame('POST', $actions[0]['target']['httpMethod']); + $this->assertContains('application/ld+json', (array) $actions[0]['target']['encodingType']); + $this->assertContains('application/ld+json', (array) $actions[0]['target']['contentType']); + $this->assertArrayNotHasKey('recipient-input', $actions[0]); + + $this->assertSame('/actionable_books/1/reviews', $actions[1]['target']['urlTemplate']); + $this->assertSame('required', $actions[1]['recipient-input']); + + $this->assertSame('/actionable_books/1/archive', $actions[2]['target']['urlTemplate']); + $this->assertSame('required', $actions[2]['reason-input']); + } + + public function testCollectionAdvertisesCollectionLevelActions(): void + { + $response = self::createClient()->request('GET', '/actionable_books', ['headers' => ['Accept' => 'application/ld+json']]); + $this->assertResponseIsSuccessful(); + + $json = $response->toArray(); + $this->assertCount(1, $json['potentialAction']); + $this->assertSame('schema:CreateAction', $json['potentialAction'][0]['@type']); + $this->assertSame('/actionable_books', $json['potentialAction'][0]['target']['urlTemplate']); + $this->assertSame('POST', $json['potentialAction'][0]['target']['httpMethod']); + $this->assertSame('required', $json['potentialAction'][0]['title-input']); + + $this->assertArrayNotHasKey('potentialAction', $json['hydra:member'][0]); + } + + public function testContextScopesActionsToSchemaOrg(): void + { + $response = self::createClient()->request('GET', '/contexts/ActionableBook', ['headers' => ['Accept' => 'application/ld+json']]); + $this->assertResponseIsSuccessful(); + + $this->assertSame([ + '@id' => 'https://schema.org/potentialAction', + '@context' => ['@vocab' => 'https://schema.org/', 'schema' => 'https://schema.org/'], + ], $response->toArray()['@context']['potentialAction']); + } +} From 9a4c3b49b74eca714047980bc8d3999b16d5147d Mon Sep 17 00:00:00 2001 From: soyuka Date: Fri, 27 Nov 2026 16:41:15 +0100 Subject: [PATCH 2/2] feat(jsonld): potentialAction operation option Replace the potential_action extra property with a first-class potentialAction option (bool|string|array) and stop reading the action type from hydraContext. Nest -input annotations under result/object when the input is the resource, skip them for PATCH/DELETE, evaluate operation security, support subresource collections and forward reset() to the decorated normalizer. --- src/JsonLd/ContextBuilder.php | 30 ++-- .../Serializer/PotentialActionNormalizer.php | 160 ++++++++++++++---- src/Laravel/ApiPlatformProvider.php | 1 + src/Metadata/Delete.php | 4 +- .../Extractor/XmlResourceExtractor.php | 4 + .../Extractor/YamlResourceExtractor.php | 4 + src/Metadata/Extractor/schema/resources.xsd | 1 + src/Metadata/Get.php | 4 +- src/Metadata/GetCollection.php | 4 +- src/Metadata/HttpOperation.php | 21 ++- src/Metadata/Patch.php | 4 +- src/Metadata/Post.php | 4 +- src/Metadata/Put.php | 4 +- src/Symfony/Bundle/Resources/config/hydra.php | 1 + .../Bundle/Resources/config/jsonld.php | 1 + .../PotentialAction/ActionableBook.php | 21 ++- .../PotentialAction/ActionableBookNote.php | 79 +++++++++ .../Functional/JsonLd/PotentialActionTest.php | 85 +++++++++- 18 files changed, 369 insertions(+), 63 deletions(-) create mode 100644 tests/Fixtures/TestBundle/ApiResource/PotentialAction/ActionableBookNote.php diff --git a/src/JsonLd/ContextBuilder.php b/src/JsonLd/ContextBuilder.php index f072155143..64f90a1a9a 100644 --- a/src/JsonLd/ContextBuilder.php +++ b/src/JsonLd/ContextBuilder.php @@ -93,18 +93,7 @@ public function getResourceContext(string $resourceClass, int $referenceType = U // Every operation resolves to this same /contexts/{shortName} URI, so union their groups. $sharedGroups = $this->getOperationsGroups($resourceMetadataCollection, $operation->getShortName()); - $context = $this->buildOperationContext($operation, $resourceClass, $referenceType, $sharedGroups); - foreach ($resourceMetadataCollection as $resource) { - foreach ($resource->getOperations() ?? [] as $resourceOperation) { - if (true === ($resourceOperation->getExtraProperties()[PotentialActionNormalizer::EXTRA_PROPERTY] ?? false)) { - $context['potentialAction'] = PotentialActionNormalizer::JSONLD_CONTEXT; - - return $context; - } - } - } - - return $context; + return $this->addPotentialAction($this->buildOperationContext($operation, $resourceClass, $referenceType, $sharedGroups), $resourceMetadataCollection); } /** @@ -177,7 +166,22 @@ public function getResourceContextUriFromOperation(HttpOperation $operation, ?in */ public function getResourceContextFromOperation(HttpOperation $operation, string $resourceClass, int $referenceType = UrlGeneratorInterface::ABS_PATH): array { - return $this->buildOperationContext($operation, $resourceClass, $referenceType); + return $this->addPotentialAction($this->buildOperationContext($operation, $resourceClass, $referenceType), $this->resourceMetadataFactory->create($resourceClass)); + } + + private function addPotentialAction(array $context, ResourceMetadataCollection $resourceMetadataCollection): array + { + foreach ($resourceMetadataCollection as $resource) { + foreach ($resource->getOperations() ?? [] as $operation) { + if ($operation instanceof HttpOperation && $operation->getPotentialAction()) { + $context['potentialAction'] = PotentialActionNormalizer::JSONLD_CONTEXT; + + return $context; + } + } + } + + return $context; } private function buildOperationContext(HttpOperation $operation, string $resourceClass, int $referenceType, ?array $additionalGroups = []): array diff --git a/src/JsonLd/Serializer/PotentialActionNormalizer.php b/src/JsonLd/Serializer/PotentialActionNormalizer.php index 1eb5b6055f..7a78c0c003 100644 --- a/src/JsonLd/Serializer/PotentialActionNormalizer.php +++ b/src/JsonLd/Serializer/PotentialActionNormalizer.php @@ -13,11 +13,13 @@ namespace ApiPlatform\JsonLd\Serializer; +use ApiPlatform\Metadata\CollectionOperationInterface; use ApiPlatform\Metadata\HttpOperation; use ApiPlatform\Metadata\IdentifiersExtractorInterface; use ApiPlatform\Metadata\Property\Factory\PropertyMetadataFactoryInterface; use ApiPlatform\Metadata\Property\Factory\PropertyNameCollectionFactoryInterface; use ApiPlatform\Metadata\Resource\Factory\ResourceMetadataCollectionFactoryInterface; +use ApiPlatform\Metadata\ResourceAccessCheckerInterface; use ApiPlatform\Metadata\UrlGeneratorInterface; use Symfony\Component\Serializer\Mapping\ClassDiscriminatorResolverInterface; use Symfony\Component\Serializer\NameConverter\NameConverterInterface; @@ -25,26 +27,25 @@ use Symfony\Component\Serializer\Normalizer\NormalizerInterface; use Symfony\Component\Serializer\SerializerAwareInterface; use Symfony\Component\Serializer\SerializerInterface; +use Symfony\Contracts\Service\ResetInterface; /** - * Advertises the operations flagged with the "potential_action" extra property as schema.org potential actions. + * Advertises the operations declaring a "potentialAction" as schema.org potential actions. * * @see https://schema.org/docs/actions.html */ -final class PotentialActionNormalizer implements NormalizerInterface, NormalizerAwareInterface, SerializerAwareInterface +final class PotentialActionNormalizer implements NormalizerInterface, NormalizerAwareInterface, SerializerAwareInterface, ResetInterface { - public const EXTRA_PROPERTY = 'potential_action'; - public const JSONLD_CONTEXT = [ '@id' => 'https://schema.org/potentialAction', '@context' => ['@vocab' => 'https://schema.org/', 'schema' => 'https://schema.org/'], ]; private const DEFAULT_TYPES = [ - 'POST' => 'schema:CreateAction', - 'PUT' => 'schema:ReplaceAction', - 'PATCH' => 'schema:UpdateAction', - 'DELETE' => 'schema:DeleteAction', + 'POST' => 'CreateAction', + 'PUT' => 'ReplaceAction', + 'PATCH' => 'UpdateAction', + 'DELETE' => 'DeleteAction', ]; public function __construct( @@ -56,6 +57,7 @@ public function __construct( private readonly UrlGeneratorInterface $urlGenerator, private readonly ?ClassDiscriminatorResolverInterface $classDiscriminatorResolver = null, private readonly ?NameConverterInterface $nameConverter = null, + private readonly ?ResourceAccessCheckerInterface $resourceAccessChecker = null, ) { } @@ -64,20 +66,32 @@ public function normalize(mixed $data, ?string $format = null, array $context = $normalizedData = $this->decorated->normalize($data, $format, $context); $operation = $context['operation'] ?? null; - if (!\is_array($normalizedData) || !$operation instanceof HttpOperation || 'GET' !== $operation->getMethod() || null === $operation->getClass() || isset($context['api_sub_level']) || isset($context['api_collection_sub_level'])) { + if (!\is_array($normalizedData) || !$operation instanceof HttpOperation || 'GET' !== $operation->getMethod() || isset($context['api_sub_level']) || isset($context['api_collection_sub_level'])) { + return $normalizedData; + } + + if (null === $resourceClass = $operation->getClass()) { return $normalizedData; } - $isCollection = is_iterable($data); + $isCollection = $operation instanceof CollectionOperationInterface; + $item = $isCollection ? null : $data; $actions = []; - foreach ($this->resourceMetadataCollectionFactory->create($operation->getClass()) as $resource) { + foreach ($this->resourceMetadataCollectionFactory->create($resourceClass) as $resource) { foreach ($resource->getOperations() ?? [] as $actionOperation) { - if (!$actionOperation instanceof HttpOperation || true !== ($actionOperation->getExtraProperties()[self::EXTRA_PROPERTY] ?? false) || $isCollection === (bool) $actionOperation->getUriVariables()) { + if (!$actionOperation instanceof HttpOperation || !$potentialAction = $actionOperation->getPotentialAction()) { + continue; + } + + if (!$this->isEligible($actionOperation, $operation, $resourceClass, $isCollection) || !$this->isGranted($actionOperation, $item, $context)) { continue; } - if (null !== $target = $this->getTarget($isCollection ? null : $data, $actionOperation)) { - array_push($actions, ...$this->getActions($actionOperation, $target)); + $uriVariables = $isCollection ? ($context['uri_variables'] ?? []) : $this->identifiersExtractor->getIdentifiersFromItem($item, $actionOperation); + $inputClass = $this->getInputClass($actionOperation); + $target = $this->getTarget($actionOperation, $uriVariables, null !== $inputClass); + foreach ($this->getActions($actionOperation, $potentialAction, $target, $inputClass, $resourceClass) as $action) { + $actions[] = $action; } } } @@ -113,18 +127,60 @@ public function setSerializer(SerializerInterface $serializer): void } } - private function getTarget(?object $item, HttpOperation $operation): ?array + public function reset(): void + { + if ($this->decorated instanceof ResetInterface) { + $this->decorated->reset(); + } + } + + private function isEligible(HttpOperation $actionOperation, HttpOperation $operation, string $resourceClass, bool $isCollection): bool + { + $uriVariables = $actionOperation->getUriVariables() ?? []; + + if ($isCollection) { + return array_keys($uriVariables) === array_keys($operation->getUriVariables() ?? []); + } + + if (!$uriVariables) { + return false; + } + + foreach ($uriVariables as $link) { + if ($link->getFromClass() !== $resourceClass) { + return false; + } + } + + return true; + } + + private function isGranted(HttpOperation $actionOperation, ?object $item, array $context): bool { - try { - $identifiers = $item ? $this->identifiersExtractor->getIdentifiersFromItem($item, $operation) : []; - $url = $this->urlGenerator->generate($operation->getRouteName() ?? $operation->getName(), $identifiers, $operation->getUrlGenerationStrategy() ?? UrlGeneratorInterface::ABS_PATH); - } catch (\InvalidArgumentException|\RuntimeException) { - // the item does not carry the operation's URI variables + if (null === $this->resourceAccessChecker || null === $security = $actionOperation->getSecurity()) { + return true; + } + + return $this->resourceAccessChecker->isGranted($actionOperation->getClass(), $security, ['object' => $item, 'previous_object' => $item, 'request' => $context['request'] ?? null]); + } + + private function getInputClass(HttpOperation $operation): ?string + { + if ('DELETE' === $operation->getMethod()) { return null; } + $input = $operation->getInput(); + + return null === $input ? $operation->getClass() : ($input['class'] ?? null); + } + + private function getTarget(HttpOperation $operation, array $uriVariables, bool $hasInput): array + { + $url = $this->urlGenerator->generate($operation->getRouteName() ?? $operation->getName(), $uriVariables, $operation->getUrlGenerationStrategy() ?? UrlGeneratorInterface::ABS_PATH); + $target = ['@type' => 'EntryPoint', 'urlTemplate' => $url, 'httpMethod' => $operation->getMethod()]; - if ($encodingType = $this->getMimeTypes($operation->getInputFormats())) { + if ($hasInput && $encodingType = $this->getMimeTypes($operation->getInputFormats())) { $target['encodingType'] = $encodingType; } if ($contentType = $this->getMimeTypes($operation->getOutputFormats())) { @@ -135,26 +191,55 @@ private function getTarget(?object $item, HttpOperation $operation): ?array } /** + * @param array|bool|string $potentialAction + * * @return list> */ - private function getActions(HttpOperation $operation, array $target): array + private function getActions(HttpOperation $operation, bool|string|array $potentialAction, array $target, ?string $inputClass, string $resourceClass): array { - $inputClass = $operation->getInput()['class'] ?? $operation->getClass(); - $mapping = $inputClass ? $this->classDiscriminatorResolver?->getMappingForClass($inputClass) : null; + if (true === $potentialAction && $inputClass) { + $mapping = $this->classDiscriminatorResolver?->getMappingForClass($inputClass); - if ('@type' === $mapping?->getTypeProperty()) { - $actions = []; - foreach ($mapping->getTypesMapping() as $type => $class) { - $actions[] = ['@type' => $type, 'target' => $target] + $this->getInputAnnotations($class, $operation); + if ('@type' === $mapping?->getTypeProperty()) { + $actions = []; + foreach ($mapping->getTypesMapping() as $type => $class) { + $actions[] = ['@type' => $type, 'target' => $target] + $this->getInputAnnotations($class, $operation); + } + + return $actions; } + } - return $actions; + $extra = \is_array($potentialAction) ? $potentialAction : []; + $type = \is_string($potentialAction) ? $potentialAction : ($extra['@type'] ?? self::DEFAULT_TYPES[$operation->getMethod()] ?? 'Action'); + $action = ['@type' => $type, 'target' => $target] + $extra; + + if (null === $inputClass) { + return [$action]; + } + + $annotations = $this->getInputAnnotations($inputClass, $operation); + if ($inputClass !== $resourceClass) { + return [$action + $annotations]; } - $hydraTypes = array_filter((array) ($operation->getHydraContext()['@type'] ?? []), static fn ($type): bool => \is_string($type) && !str_starts_with($type, 'hydra:')); - $type = reset($hydraTypes) ?: self::DEFAULT_TYPES[$operation->getMethod()] ?? 'schema:Action'; + $property = match ($operation->getMethod()) { + 'POST' => 'result', + 'PUT' => 'object', + default => null, + }; + + if (null === $property) { + return [$action]; + } - return [['@type' => $type, 'target' => $target] + ($inputClass ? $this->getInputAnnotations($inputClass, $operation) : [])]; + $node = []; + if ($types = $operation->getTypes()) { + $node['@type'] = reset($types); + } + $node += $annotations; + + return [$node ? $action + [$property => $node] : $action]; } /** @@ -182,7 +267,16 @@ private function getInputAnnotations(string $class, HttpOperation $operation): a */ private function getMimeTypes(?array $formats): string|array|null { - $mimeTypes = array_values(array_unique(array_merge(...array_map(static fn ($mimeTypes): array => (array) $mimeTypes, array_values($formats ?? []))))); + $seen = []; + $mimeTypes = []; + foreach ($formats ?? [] as $formatMimeTypes) { + foreach ((array) $formatMimeTypes as $mimeType) { + if (!isset($seen[$mimeType])) { + $seen[$mimeType] = true; + $mimeTypes[] = $mimeType; + } + } + } return match (\count($mimeTypes)) { 0 => null, diff --git a/src/Laravel/ApiPlatformProvider.php b/src/Laravel/ApiPlatformProvider.php index 89c3d03ef9..d214c9e2c7 100644 --- a/src/Laravel/ApiPlatformProvider.php +++ b/src/Laravel/ApiPlatformProvider.php @@ -1177,6 +1177,7 @@ public function register(): void $app->make(UrlGeneratorInterface::class), new ClassDiscriminatorFromClassMetadata($app->make(ClassMetadataFactoryInterface::class)), $app->make(NameConverterInterface::class), + $app->make(ResourceAccessCheckerInterface::class), ); $list = new \SplPriorityQueue(); diff --git a/src/Metadata/Delete.php b/src/Metadata/Delete.php index 1c62cb5cdc..0defa0ef98 100644 --- a/src/Metadata/Delete.php +++ b/src/Metadata/Delete.php @@ -108,6 +108,7 @@ public function __construct( array $extraProperties = [], ?bool $map = null, ?string $canonicalUriTemplate = null, + bool|string|array|null $potentialAction = null, ) { parent::__construct( method: 'DELETE', @@ -196,7 +197,8 @@ class: $class, throwOnNotFound: $throwOnNotFound, stateOptions: $stateOptions, map: $map, - canonicalUriTemplate: $canonicalUriTemplate + canonicalUriTemplate: $canonicalUriTemplate, + potentialAction: $potentialAction, ); } } diff --git a/src/Metadata/Extractor/XmlResourceExtractor.php b/src/Metadata/Extractor/XmlResourceExtractor.php index 4c8029e396..539cad55be 100644 --- a/src/Metadata/Extractor/XmlResourceExtractor.php +++ b/src/Metadata/Extractor/XmlResourceExtractor.php @@ -418,6 +418,10 @@ private function buildOperations(\SimpleXMLElement $resource, array $root): ?arr throw new InvalidArgumentException(\sprintf('"itemUriTemplate" option is not allowed on a %s operation.', $operation['class'])); } + if (isset($operation['potentialAction'])) { + $datum['potentialAction'] = $this->phpize($operation, 'potentialAction', 'bool|string'); + } + $data[] = array_merge($datum, [ 'class' => (string) $operation['class'], 'method' => $this->phpize($operation, 'method', 'string'), diff --git a/src/Metadata/Extractor/YamlResourceExtractor.php b/src/Metadata/Extractor/YamlResourceExtractor.php index ce42daaf42..2b814489b6 100644 --- a/src/Metadata/Extractor/YamlResourceExtractor.php +++ b/src/Metadata/Extractor/YamlResourceExtractor.php @@ -370,6 +370,10 @@ private function buildOperations(array $resource, array $root): ?array throw new InvalidArgumentException(\sprintf('"itemUriTemplate" option is not allowed on a %s operation.', $class)); } + if (isset($operation['potentialAction'])) { + $datum['potentialAction'] = \is_array($operation['potentialAction']) ? $operation['potentialAction'] : $this->phpize($operation, 'potentialAction', 'bool|string'); + } + if (isset($operation['queryParameterValidate'])) { trigger_deprecation('api-platform/core', '5.1', 'The "queryParameterValidate" option has no effect, it is deprecated and will be removed in 6.0. Use "queryParameterValidationEnabled" instead.'); } diff --git a/src/Metadata/Extractor/schema/resources.xsd b/src/Metadata/Extractor/schema/resources.xsd index ed045e2dfc..a8c2b806fb 100644 --- a/src/Metadata/Extractor/schema/resources.xsd +++ b/src/Metadata/Extractor/schema/resources.xsd @@ -51,6 +51,7 @@ + diff --git a/src/Metadata/Get.php b/src/Metadata/Get.php index bb03da14a8..180b2bf540 100644 --- a/src/Metadata/Get.php +++ b/src/Metadata/Get.php @@ -108,6 +108,7 @@ public function __construct( array $extraProperties = [], ?bool $map = null, ?string $canonicalUriTemplate = null, + bool|string|array|null $potentialAction = null, ) { parent::__construct( uriTemplate: $uriTemplate, @@ -195,7 +196,8 @@ class: $class, throwOnNotFound: $throwOnNotFound, extraProperties: $extraProperties, map: $map, - canonicalUriTemplate: $canonicalUriTemplate + canonicalUriTemplate: $canonicalUriTemplate, + potentialAction: $potentialAction, ); } } diff --git a/src/Metadata/GetCollection.php b/src/Metadata/GetCollection.php index 30349e6d8e..cebc46bdf3 100644 --- a/src/Metadata/GetCollection.php +++ b/src/Metadata/GetCollection.php @@ -112,6 +112,7 @@ public function __construct( private ?string $itemUriTemplate = null, ?bool $map = null, ?string $canonicalUriTemplate = null, + bool|string|array|null $potentialAction = null, ) { parent::__construct( uriTemplate: $uriTemplate, @@ -199,7 +200,8 @@ class: $class, hideHydraOperation: $hideHydraOperation, stateOptions: $stateOptions, map: $map, - canonicalUriTemplate: $canonicalUriTemplate + canonicalUriTemplate: $canonicalUriTemplate, + potentialAction: $potentialAction, ); } diff --git a/src/Metadata/HttpOperation.php b/src/Metadata/HttpOperation.php index 62ed934c5a..29922ce9a0 100644 --- a/src/Metadata/HttpOperation.php +++ b/src/Metadata/HttpOperation.php @@ -77,9 +77,10 @@ class HttpOperation extends Operation * field: string, * direction: string, * }>|null $paginationViaCursor {@see https://api-platform.com/docs/core/pagination/#cursor-based-pagination} - * @param array|null $normalizationContext {@see https://api-platform.com/docs/core/serialization/#using-serialization-groups} - * @param array|null $denormalizationContext {@see https://api-platform.com/docs/core/serialization/#using-serialization-groups} - * @param array|null $hydraContext {@see https://api-platform.com/docs/core/extending-jsonld-context/#hydra} + * @param array|null $normalizationContext {@see https://api-platform.com/docs/core/serialization/#using-serialization-groups} + * @param array|null $denormalizationContext {@see https://api-platform.com/docs/core/serialization/#using-serialization-groups} + * @param array|null $hydraContext {@see https://api-platform.com/docs/core/extending-jsonld-context/#hydra} + * @param bool|string|array|null $potentialAction advertise this operation as a schema.org potential action in JSON-LD: true uses the default type of the HTTP method, a string sets the action type, an array is merged into the action node * @param array{ * class?: string|null, * name?: string, @@ -230,6 +231,7 @@ public function __construct( array $extraProperties = [], ?bool $map = null, protected ?string $canonicalUriTemplate = null, + protected bool|string|array|null $potentialAction = null, ) { $this->formats = (null === $formats || \is_array($formats)) ? $formats : [$formats]; $this->inputFormats = (null === $inputFormats || \is_array($inputFormats)) ? $inputFormats : [$inputFormats]; @@ -674,6 +676,19 @@ public function withHydraContext(array $hydraContext): static return $self; } + public function getPotentialAction(): bool|string|array|null + { + return $this->potentialAction; + } + + public function withPotentialAction(bool|string|array|null $potentialAction): static + { + $self = clone $this; + $self->potentialAction = $potentialAction; + + return $self; + } + public function getJsonldContext(): ?array { return $this->jsonldContext; diff --git a/src/Metadata/Patch.php b/src/Metadata/Patch.php index 266cdd5e57..0b8616a8fa 100644 --- a/src/Metadata/Patch.php +++ b/src/Metadata/Patch.php @@ -108,6 +108,7 @@ public function __construct( array $extraProperties = [], ?bool $map = null, ?string $canonicalUriTemplate = null, + bool|string|array|null $potentialAction = null, ) { parent::__construct( method: 'PATCH', @@ -196,7 +197,8 @@ class: $class, throwOnNotFound: $throwOnNotFound, extraProperties: $extraProperties, map: $map, - canonicalUriTemplate: $canonicalUriTemplate + canonicalUriTemplate: $canonicalUriTemplate, + potentialAction: $potentialAction, ); } } diff --git a/src/Metadata/Post.php b/src/Metadata/Post.php index 0c8d4ddef0..88e2074746 100644 --- a/src/Metadata/Post.php +++ b/src/Metadata/Post.php @@ -109,6 +109,7 @@ public function __construct( ?bool $hideHydraOperation = null, ?bool $map = null, ?string $canonicalUriTemplate = null, + bool|string|array|null $potentialAction = null, ) { parent::__construct( method: 'POST', @@ -197,7 +198,8 @@ class: $class, throwOnNotFound: $throwOnNotFound, extraProperties: $extraProperties, map: $map, - canonicalUriTemplate: $canonicalUriTemplate + canonicalUriTemplate: $canonicalUriTemplate, + potentialAction: $potentialAction, ); } diff --git a/src/Metadata/Put.php b/src/Metadata/Put.php index 28c3ffbc44..5ff88ddb5a 100644 --- a/src/Metadata/Put.php +++ b/src/Metadata/Put.php @@ -109,6 +109,7 @@ public function __construct( private ?bool $allowCreate = null, ?bool $map = null, ?string $canonicalUriTemplate = null, + bool|string|array|null $potentialAction = null, ) { parent::__construct( method: 'PUT', @@ -197,7 +198,8 @@ class: $class, throwOnNotFound: $throwOnNotFound, extraProperties: $extraProperties, map: $map, - canonicalUriTemplate: $canonicalUriTemplate + canonicalUriTemplate: $canonicalUriTemplate, + potentialAction: $potentialAction, ); } diff --git a/src/Symfony/Bundle/Resources/config/hydra.php b/src/Symfony/Bundle/Resources/config/hydra.php index f2ce486c68..526bc9fd3b 100644 --- a/src/Symfony/Bundle/Resources/config/hydra.php +++ b/src/Symfony/Bundle/Resources/config/hydra.php @@ -117,6 +117,7 @@ service('api_platform.router'), service('serializer.mapping.class_discriminator_resolver')->ignoreOnInvalid(), service('api_platform.name_converter')->ignoreOnInvalid(), + service('api_platform.security.resource_access_checker')->ignoreOnInvalid(), ]); $services->set('api_platform.hydra.name_converter.hydra_prefix', HydraPrefixNameConverter::class) diff --git a/src/Symfony/Bundle/Resources/config/jsonld.php b/src/Symfony/Bundle/Resources/config/jsonld.php index 3d173a1895..5f7262eaaf 100644 --- a/src/Symfony/Bundle/Resources/config/jsonld.php +++ b/src/Symfony/Bundle/Resources/config/jsonld.php @@ -70,6 +70,7 @@ service('api_platform.router'), service('serializer.mapping.class_discriminator_resolver')->ignoreOnInvalid(), service('api_platform.name_converter')->ignoreOnInvalid(), + service('api_platform.security.resource_access_checker')->ignoreOnInvalid(), ]); $services->set('api_platform.jsonld.denormalizer.item', ItemDenormalizer::class) diff --git a/tests/Fixtures/TestBundle/ApiResource/PotentialAction/ActionableBook.php b/tests/Fixtures/TestBundle/ApiResource/PotentialAction/ActionableBook.php index d82e120fef..b8b8578e24 100644 --- a/tests/Fixtures/TestBundle/ApiResource/PotentialAction/ActionableBook.php +++ b/tests/Fixtures/TestBundle/ApiResource/PotentialAction/ActionableBook.php @@ -15,10 +15,12 @@ use ApiPlatform\Metadata\ApiProperty; use ApiPlatform\Metadata\ApiResource; +use ApiPlatform\Metadata\Delete; use ApiPlatform\Metadata\Get; use ApiPlatform\Metadata\GetCollection; use ApiPlatform\Metadata\Link; use ApiPlatform\Metadata\Operation; +use ApiPlatform\Metadata\Patch; use ApiPlatform\Metadata\Post; use Symfony\Component\Validator\Constraints as Assert; @@ -26,7 +28,7 @@ operations: [ new Get(uriTemplate: '/actionable_books/{id}', provider: [self::class, 'provide']), new GetCollection(uriTemplate: '/actionable_books', provider: [self::class, 'provideCollection']), - new Post(uriTemplate: '/actionable_books', processor: [self::class, 'process'], extraProperties: ['potential_action' => true]), + new Post(uriTemplate: '/actionable_books', processor: [self::class, 'process'], potentialAction: true), new Post( uriTemplate: '/actionable_books/{id}/reviews', uriVariables: ['id' => new Link(fromClass: self::class)], @@ -34,17 +36,28 @@ output: false, provider: [self::class, 'provide'], processor: [self::class, 'process'], - extraProperties: ['potential_action' => true], + potentialAction: true, ), new Post( uriTemplate: '/actionable_books/{id}/archive', uriVariables: ['id' => new Link(fromClass: self::class)], input: ArchiveBookInput::class, output: false, - hydraContext: ['@type' => ['hydra:Operation', 'schema:ArchiveAction']], provider: [self::class, 'provide'], processor: [self::class, 'process'], - extraProperties: ['potential_action' => true], + potentialAction: 'ArchiveAction', + ), + new Patch(uriTemplate: '/actionable_books/{id}', provider: [self::class, 'provide'], processor: [self::class, 'process'], potentialAction: true), + new Delete(uriTemplate: '/actionable_books/{id}', provider: [self::class, 'provide'], processor: [self::class, 'process'], potentialAction: true), + new Post( + uriTemplate: '/actionable_books/{id}/lock', + uriVariables: ['id' => new Link(fromClass: self::class)], + input: ArchiveBookInput::class, + output: false, + security: 'false', + provider: [self::class, 'provide'], + processor: [self::class, 'process'], + potentialAction: true, ), new Post( uriTemplate: '/actionable_books/{id}/restore', diff --git a/tests/Fixtures/TestBundle/ApiResource/PotentialAction/ActionableBookNote.php b/tests/Fixtures/TestBundle/ApiResource/PotentialAction/ActionableBookNote.php new file mode 100644 index 0000000000..2093fa05b6 --- /dev/null +++ b/tests/Fixtures/TestBundle/ApiResource/PotentialAction/ActionableBookNote.php @@ -0,0 +1,79 @@ + + * + * 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\PotentialAction; + +use ApiPlatform\Metadata\ApiProperty; +use ApiPlatform\Metadata\ApiResource; +use ApiPlatform\Metadata\Get; +use ApiPlatform\Metadata\GetCollection; +use ApiPlatform\Metadata\Link; +use ApiPlatform\Metadata\Operation; +use ApiPlatform\Metadata\Post; +use Symfony\Component\Validator\Constraints as Assert; + +#[ApiResource( + operations: [ + new Get( + uriTemplate: '/actionable_books/{bookId}/notes/{id}', + uriVariables: [ + 'bookId' => new Link(fromClass: ActionableBook::class, toProperty: 'book'), + 'id' => new Link(fromClass: self::class), + ], + provider: [self::class, 'provide'], + ), + new GetCollection( + uriTemplate: '/actionable_books/{bookId}/notes', + uriVariables: ['bookId' => new Link(fromClass: ActionableBook::class, toProperty: 'book')], + provider: [self::class, 'provideCollection'], + ), + new Post( + uriTemplate: '/actionable_books/{bookId}/notes', + uriVariables: ['bookId' => new Link(fromClass: ActionableBook::class, toProperty: 'book')], + processor: [self::class, 'process'], + potentialAction: true, + ), + ] +)] +final class ActionableBookNote +{ + #[ApiProperty(identifier: true)] + public ?int $id = null; + + public ?ActionableBook $book = null; + + #[Assert\NotBlank] + public ?string $body = null; + + public static function provide(Operation $operation, array $uriVariables = [], array $context = []): self + { + $note = new self(); + $note->id = (int) $uriVariables['id']; + $note->body = 'Noted'; + + return $note; + } + + /** + * @return list + */ + public static function provideCollection(Operation $operation, array $uriVariables = [], array $context = []): array + { + return []; + } + + public static function process(mixed $data, Operation $operation, array $uriVariables = [], array $context = []): mixed + { + return $data; + } +} diff --git a/tests/Functional/JsonLd/PotentialActionTest.php b/tests/Functional/JsonLd/PotentialActionTest.php index 9343cef4f1..503d0596a6 100644 --- a/tests/Functional/JsonLd/PotentialActionTest.php +++ b/tests/Functional/JsonLd/PotentialActionTest.php @@ -15,6 +15,7 @@ use ApiPlatform\Test\ApiTestCase; use ApiPlatform\Tests\Fixtures\TestBundle\ApiResource\PotentialAction\ActionableBook; +use ApiPlatform\Tests\Fixtures\TestBundle\ApiResource\PotentialAction\ActionableBookNote; use ApiPlatform\Tests\SetupClassResourcesTrait; final class PotentialActionTest extends ApiTestCase @@ -28,7 +29,7 @@ final class PotentialActionTest extends ApiTestCase */ public static function getResources(): array { - return [ActionableBook::class]; + return [ActionableBook::class, ActionableBookNote::class]; } public function testItemAdvertisesItemLevelActions(): void @@ -37,7 +38,7 @@ public function testItemAdvertisesItemLevelActions(): void $this->assertResponseIsSuccessful(); $actions = $response->toArray()['potentialAction']; - $this->assertSame(['LikeAction', 'ShareAction', 'schema:ArchiveAction'], array_column($actions, '@type')); + $this->assertSame(['LikeAction', 'ShareAction', 'ArchiveAction', 'UpdateAction', 'DeleteAction'], array_column($actions, '@type')); $this->assertSame('EntryPoint', $actions[0]['target']['@type']); $this->assertSame('/actionable_books/1/reviews', $actions[0]['target']['urlTemplate']); @@ -53,6 +54,36 @@ public function testItemAdvertisesItemLevelActions(): void $this->assertSame('required', $actions[2]['reason-input']); } + public function testItemAdvertisesPatchWithoutInput(): void + { + $response = self::createClient()->request('GET', '/actionable_books/1', ['headers' => ['Accept' => 'application/ld+json']]); + + $action = $this->findAction($response->toArray()['potentialAction'], 'UpdateAction'); + $this->assertSame('PATCH', $action['target']['httpMethod']); + $this->assertSame('/actionable_books/1', $action['target']['urlTemplate']); + $this->assertArrayNotHasKey('object', $action); + $this->assertSame([], $this->getInputKeys($action)); + } + + public function testItemAdvertisesDeleteWithoutInput(): void + { + $response = self::createClient()->request('GET', '/actionable_books/1', ['headers' => ['Accept' => 'application/ld+json']]); + + $action = $this->findAction($response->toArray()['potentialAction'], 'DeleteAction'); + $this->assertSame('DELETE', $action['target']['httpMethod']); + $this->assertSame('/actionable_books/1', $action['target']['urlTemplate']); + $this->assertArrayNotHasKey('encodingType', $action['target']); + $this->assertSame([], $this->getInputKeys($action)); + } + + public function testItemDoesNotAdvertiseDeniedAction(): void + { + $response = self::createClient()->request('GET', '/actionable_books/1', ['headers' => ['Accept' => 'application/ld+json']]); + + $urlTemplates = array_column(array_column($response->toArray()['potentialAction'], 'target'), 'urlTemplate'); + $this->assertNotContains('/actionable_books/1/lock', $urlTemplates); + } + public function testCollectionAdvertisesCollectionLevelActions(): void { $response = self::createClient()->request('GET', '/actionable_books', ['headers' => ['Accept' => 'application/ld+json']]); @@ -60,14 +91,27 @@ public function testCollectionAdvertisesCollectionLevelActions(): void $json = $response->toArray(); $this->assertCount(1, $json['potentialAction']); - $this->assertSame('schema:CreateAction', $json['potentialAction'][0]['@type']); + $this->assertSame('CreateAction', $json['potentialAction'][0]['@type']); $this->assertSame('/actionable_books', $json['potentialAction'][0]['target']['urlTemplate']); $this->assertSame('POST', $json['potentialAction'][0]['target']['httpMethod']); - $this->assertSame('required', $json['potentialAction'][0]['title-input']); + $this->assertSame('required', $json['potentialAction'][0]['result']['title-input']); + $this->assertArrayNotHasKey('title-input', $json['potentialAction'][0]); $this->assertArrayNotHasKey('potentialAction', $json['hydra:member'][0]); } + public function testSubresourceCollectionAdvertisesCollectionLevelActions(): void + { + $response = self::createClient()->request('GET', '/actionable_books/1/notes', ['headers' => ['Accept' => 'application/ld+json']]); + $this->assertResponseIsSuccessful(); + + $json = $response->toArray(); + $this->assertCount(1, $json['potentialAction']); + $this->assertSame('CreateAction', $json['potentialAction'][0]['@type']); + $this->assertSame('/actionable_books/1/notes', $json['potentialAction'][0]['target']['urlTemplate']); + $this->assertSame('required', $json['potentialAction'][0]['result']['body-input']); + } + public function testContextScopesActionsToSchemaOrg(): void { $response = self::createClient()->request('GET', '/contexts/ActionableBook', ['headers' => ['Accept' => 'application/ld+json']]); @@ -78,4 +122,37 @@ public function testContextScopesActionsToSchemaOrg(): void '@context' => ['@vocab' => 'https://schema.org/', 'schema' => 'https://schema.org/'], ], $response->toArray()['@context']['potentialAction']); } + + /** + * @param list> $actions + * + * @return array + */ + private function findAction(array $actions, string $type): array + { + foreach ($actions as $action) { + if ($type === $action['@type']) { + return $action; + } + } + + $this->fail(\sprintf('No "%s" action found.', $type)); + } + + /** + * @param array $action + * + * @return list + */ + private function getInputKeys(array $action): array + { + $keys = []; + foreach (new \RecursiveIteratorIterator(new \RecursiveArrayIterator($action)) as $key => $value) { + if (\is_string($key) && str_ends_with($key, '-input')) { + $keys[] = $key; + } + } + + return $keys; + } }