Skip to content
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
14 changes: 13 additions & 1 deletion src/JsonLd/ContextBuilder.php
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@
namespace ApiPlatform\JsonLd;

use ApiPlatform\JsonLd\Serializer\HydraPrefixTrait;
use ApiPlatform\JsonLd\Serializer\PotentialActionNormalizer;
use ApiPlatform\Metadata\Get;
use ApiPlatform\Metadata\HttpOperation;
use ApiPlatform\Metadata\IriConverterInterface;
Expand Down Expand Up @@ -88,7 +89,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;
}

/**
Expand Down
193 changes: 193 additions & 0 deletions src/JsonLd/Serializer/PotentialActionNormalizer.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,193 @@
<?php

/*
* This file is part of the API Platform project.
*
* (c) Kévin Dunglas <dunglas@gmail.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/

declare(strict_types=1);

namespace ApiPlatform\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<array<string, mixed>>
*/
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<string, string>
*/
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<string, string|list<string>>|null $formats
*
* @return string|list<string>|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,
};
}
}
17 changes: 15 additions & 2 deletions src/Laravel/ApiPlatformProvider.php
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down Expand Up @@ -217,6 +218,7 @@
use Symfony\Component\PropertyInfo\PropertyInfoExtractorInterface;
use Symfony\Component\Routing\RequestContext;
use Symfony\Component\Serializer\Encoder\CsvEncoder;
use Symfony\Component\Serializer\Mapping\ClassDiscriminatorFromClassMetadata;
use Symfony\Component\Serializer\Mapping\Factory\ClassMetadataFactory;
use Symfony\Component\Serializer\Mapping\Factory\ClassMetadataFactoryInterface;
use Symfony\Component\Serializer\Mapping\Loader\AttributeLoader;
Expand Down Expand Up @@ -1146,15 +1148,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);
Expand Down
14 changes: 14 additions & 0 deletions src/Symfony/Bundle/Resources/config/hydra.php
Original file line number Diff line number Diff line change
Expand Up @@ -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();
Expand Down Expand Up @@ -104,6 +105,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([
Expand Down
14 changes: 14 additions & 0 deletions src/Symfony/Bundle/Resources/config/jsonld.php
Original file line number Diff line number Diff line change
Expand Up @@ -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;

Expand Down Expand Up @@ -56,6 +57,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'),
Expand Down
Loading
Loading