diff --git a/src/JsonLd/ContextBuilder.php b/src/JsonLd/ContextBuilder.php index 7564f1ce782..64f90a1a9a6 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,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()); - return $this->buildOperationContext($operation, $resourceClass, $referenceType, $sharedGroups); + return $this->addPotentialAction($this->buildOperationContext($operation, $resourceClass, $referenceType, $sharedGroups), $resourceMetadataCollection); } /** @@ -165,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 new file mode 100644 index 00000000000..7a78c0c0036 --- /dev/null +++ b/src/JsonLd/Serializer/PotentialActionNormalizer.php @@ -0,0 +1,287 @@ + + * + * 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\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; +use Symfony\Component\Serializer\Normalizer\NormalizerAwareInterface; +use Symfony\Component\Serializer\Normalizer\NormalizerInterface; +use Symfony\Component\Serializer\SerializerAwareInterface; +use Symfony\Component\Serializer\SerializerInterface; +use Symfony\Contracts\Service\ResetInterface; + +/** + * 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, ResetInterface +{ + public const JSONLD_CONTEXT = [ + '@id' => 'https://schema.org/potentialAction', + '@context' => ['@vocab' => 'https://schema.org/', 'schema' => 'https://schema.org/'], + ]; + + private const DEFAULT_TYPES = [ + 'POST' => 'CreateAction', + 'PUT' => 'ReplaceAction', + 'PATCH' => 'UpdateAction', + 'DELETE' => '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, + private readonly ?ResourceAccessCheckerInterface $resourceAccessChecker = 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() || isset($context['api_sub_level']) || isset($context['api_collection_sub_level'])) { + return $normalizedData; + } + + if (null === $resourceClass = $operation->getClass()) { + return $normalizedData; + } + + $isCollection = $operation instanceof CollectionOperationInterface; + $item = $isCollection ? null : $data; + $actions = []; + foreach ($this->resourceMetadataCollectionFactory->create($resourceClass) as $resource) { + foreach ($resource->getOperations() ?? [] as $actionOperation) { + if (!$actionOperation instanceof HttpOperation || !$potentialAction = $actionOperation->getPotentialAction()) { + continue; + } + + if (!$this->isEligible($actionOperation, $operation, $resourceClass, $isCollection) || !$this->isGranted($actionOperation, $item, $context)) { + continue; + } + + $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; + } + } + } + + 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); + } + } + + 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 + { + 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 ($hasInput && $encodingType = $this->getMimeTypes($operation->getInputFormats())) { + $target['encodingType'] = $encodingType; + } + if ($contentType = $this->getMimeTypes($operation->getOutputFormats())) { + $target['contentType'] = $contentType; + } + + return $target; + } + + /** + * @param array|bool|string $potentialAction + * + * @return list> + */ + private function getActions(HttpOperation $operation, bool|string|array $potentialAction, array $target, ?string $inputClass, string $resourceClass): array + { + 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); + } + + 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]; + } + + $property = match ($operation->getMethod()) { + 'POST' => 'result', + 'PUT' => 'object', + default => null, + }; + + if (null === $property) { + return [$action]; + } + + $node = []; + if ($types = $operation->getTypes()) { + $node['@type'] = reset($types); + } + $node += $annotations; + + return [$node ? $action + [$property => $node] : $action]; + } + + /** + * @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 + { + $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, + 1 => $mimeTypes[0], + default => $mimeTypes, + }; + } +} diff --git a/src/Laravel/ApiPlatformProvider.php b/src/Laravel/ApiPlatformProvider.php index 93cdce910b7..d214c9e2c79 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,27 @@ 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), + $app->make(ResourceAccessCheckerInterface::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/Metadata/Delete.php b/src/Metadata/Delete.php index 1c62cb5cdc1..0defa0ef981 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 4c8029e396e..539cad55be9 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 ce42daaf421..2b814489b69 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 ed045e2dfc2..a8c2b806fb5 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 bb03da14a83..180b2bf5405 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 30349e6d8e5..cebc46bdf38 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 62ed934c5a3..29922ce9a0b 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 266cdd5e57f..0b8616a8fa1 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 0c8d4ddef03..88e2074746d 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 28c3ffbc440..5ff88ddb5a8 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 d58cec024d4..526bc9fd3b8 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,20 @@ '%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(), + service('api_platform.security.resource_access_checker')->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 ac34b50c59f..5f7262eaaf7 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,20 @@ ->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(), + service('api_platform.security.resource_access_checker')->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 00000000000..b8b8578e243 --- /dev/null +++ b/tests/Fixtures/TestBundle/ApiResource/PotentialAction/ActionableBook.php @@ -0,0 +1,101 @@ + + * + * 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\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; + +#[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'], potentialAction: 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'], + potentialAction: true, + ), + new Post( + uriTemplate: '/actionable_books/{id}/archive', + uriVariables: ['id' => new Link(fromClass: self::class)], + input: ArchiveBookInput::class, + output: false, + provider: [self::class, 'provide'], + processor: [self::class, 'process'], + 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', + 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/ActionableBookNote.php b/tests/Fixtures/TestBundle/ApiResource/PotentialAction/ActionableBookNote.php new file mode 100644 index 00000000000..2093fa05b68 --- /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/Fixtures/TestBundle/ApiResource/PotentialAction/ArchiveBookInput.php b/tests/Fixtures/TestBundle/ApiResource/PotentialAction/ArchiveBookInput.php new file mode 100644 index 00000000000..68063aa9073 --- /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 00000000000..36cf59a29c1 --- /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 00000000000..b7bfb946c77 --- /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 00000000000..09dcb0d5545 --- /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 00000000000..503d0596a67 --- /dev/null +++ b/tests/Functional/JsonLd/PotentialActionTest.php @@ -0,0 +1,158 @@ + + * + * 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\Fixtures\TestBundle\ApiResource\PotentialAction\ActionableBookNote; +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, ActionableBookNote::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', 'ArchiveAction', 'UpdateAction', 'DeleteAction'], 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 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']]); + $this->assertResponseIsSuccessful(); + + $json = $response->toArray(); + $this->assertCount(1, $json['potentialAction']); + $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]['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']]); + $this->assertResponseIsSuccessful(); + + $this->assertSame([ + '@id' => 'https://schema.org/potentialAction', + '@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; + } +}