From d1a7256ae1bf0377ae452bba82f87f63a773e8e7 Mon Sep 17 00:00:00 2001 From: soyuka Date: Thu, 26 Nov 2026 08:58:20 +0100 Subject: [PATCH 1/2] fix(hydra): document sub-resource operations on parent link A property with an ApiProperty uriTemplate serializes as the IRI of a sub-resource collection. Expose that collection's POST and GET operations as supportedOperation on the hydra:Link, and stop listing the sub-resource as a phantom #Entrypoint property when they are attached. --- .../Serializer/DocumentationNormalizer.php | 97 +++++++++++-- .../DocumentationNormalizerTest.php | 127 ++++++++++++++++++ 2 files changed, 212 insertions(+), 12 deletions(-) diff --git a/src/Hydra/Serializer/DocumentationNormalizer.php b/src/Hydra/Serializer/DocumentationNormalizer.php index 3492403a94d..cb0f5596774 100644 --- a/src/Hydra/Serializer/DocumentationNormalizer.php +++ b/src/Hydra/Serializer/DocumentationNormalizer.php @@ -30,6 +30,7 @@ use ApiPlatform\Metadata\ResourceClassResolverInterface; use ApiPlatform\Metadata\UrlGeneratorInterface; use ApiPlatform\Metadata\Util\TypeHelper; +use ApiPlatform\Metadata\Util\UriTemplateHelper; use Symfony\Component\Serializer\NameConverter\NameConverterInterface; use Symfony\Component\Serializer\Normalizer\AbstractNormalizer; use Symfony\Component\Serializer\Normalizer\NormalizerInterface; @@ -71,19 +72,31 @@ public function normalize(mixed $data, ?string $format = null, array $context = $entrypointProperties = []; $hydraPrefix = $this->getHydraPrefix($context + $this->defaultContext); + $resourceMetadataCollections = []; foreach ($data->getResourceNameCollection() as $resourceClass) { - $resourceMetadataCollection = $this->resourceMetadataFactory->create($resourceClass); + $resourceMetadataCollections[$resourceClass] = $this->resourceMetadataFactory->create($resourceClass); + } + $attachedUriTemplates = []; + foreach ($resourceMetadataCollections as $resourceClass => $resourceMetadataCollection) { foreach ($resourceMetadataCollection as $resourceMetadata) { if (true === $resourceMetadata->getHideHydraOperation()) { continue; } $shortName = $resourceMetadata->getShortName(); - $prefixedShortName = "#$shortName"; + $classes[] = $this->getClass($resourceClass, $resourceMetadata, $shortName, "#$shortName", $context, $hydraPrefix, $attachedUriTemplates); + } + } + + foreach ($resourceMetadataCollections as $resourceMetadataCollection) { + foreach ($resourceMetadataCollection as $resourceMetadata) { + if (true === $resourceMetadata->getHideHydraOperation()) { + continue; + } - $this->populateEntrypointProperties($resourceMetadata, $shortName, $prefixedShortName, $entrypointProperties, $hydraPrefix); - $classes[] = $this->getClass($resourceClass, $resourceMetadata, $shortName, $prefixedShortName, $context, $hydraPrefix); + $shortName = $resourceMetadata->getShortName(); + $this->populateEntrypointProperties($resourceMetadata, $shortName, "#$shortName", $entrypointProperties, $hydraPrefix, $attachedUriTemplates); } } @@ -93,9 +106,9 @@ public function normalize(mixed $data, ?string $format = null, array $context = /** * Populates entrypoint properties. */ - private function populateEntrypointProperties(ApiResource $resourceMetadata, string $shortName, string $prefixedShortName, array &$entrypointProperties, string $hydraPrefix): void + private function populateEntrypointProperties(ApiResource $resourceMetadata, string $shortName, string $prefixedShortName, array &$entrypointProperties, string $hydraPrefix, array $attachedUriTemplates): void { - $hydraCollectionOperations = $this->getHydraOperations(true, $resourceMetadata, $hydraPrefix); + $hydraCollectionOperations = $this->getHydraOperations(true, $resourceMetadata, $hydraPrefix, $attachedUriTemplates); if (empty($hydraCollectionOperations)) { return; } @@ -130,7 +143,7 @@ private function populateEntrypointProperties(ApiResource $resourceMetadata, str /** * Gets a Hydra class. */ - private function getClass(string $resourceClass, ApiResource $resourceMetadata, string $shortName, string $prefixedShortName, array $context, string $hydraPrefix): array + private function getClass(string $resourceClass, ApiResource $resourceMetadata, string $shortName, string $prefixedShortName, array $context, string $hydraPrefix, array &$attachedUriTemplates = []): array { $description = $resourceMetadata->getDescription(); $isDeprecated = $resourceMetadata->getDeprecationReason(); @@ -139,7 +152,7 @@ private function getClass(string $resourceClass, ApiResource $resourceMetadata, '@id' => $prefixedShortName, '@type' => $hydraPrefix.'Class', $hydraPrefix.'title' => $shortName, - $hydraPrefix.'supportedProperty' => $this->getHydraProperties($resourceClass, $resourceMetadata, $shortName, $prefixedShortName, $context, $hydraPrefix), + $hydraPrefix.'supportedProperty' => $this->getHydraProperties($resourceClass, $resourceMetadata, $shortName, $prefixedShortName, $context, $hydraPrefix, $attachedUriTemplates), $hydraPrefix.'supportedOperation' => $this->getHydraOperations(false, $resourceMetadata, $hydraPrefix), ]; @@ -208,7 +221,7 @@ private function getPropertyMetadataFactoryContext(ApiResource $resourceMetadata /** * Gets Hydra properties. */ - private function getHydraProperties(string $resourceClass, ApiResource $resourceMetadata, string $shortName, string $prefixedShortName, array $context, string $hydraPrefix = ContextBuilder::HYDRA_PREFIX): array + private function getHydraProperties(string $resourceClass, ApiResource $resourceMetadata, string $shortName, string $prefixedShortName, array $context, string $hydraPrefix = ContextBuilder::HYDRA_PREFIX, array &$attachedUriTemplates = []): array { $classes = []; @@ -250,7 +263,12 @@ private function getHydraProperties(string $resourceClass, ApiResource $resource continue; } - $properties[] = $this->getProperty($propertyMetadata, $propertyName, $prefixedShortName, $shortName, $hydraPrefix); + $operations = $this->getUriTemplateOperations($propertyMetadata, $hydraPrefix); + if ($operations) { + $attachedUriTemplates[UriTemplateHelper::withoutFormatSuffix($propertyMetadata->getUriTemplate())] = true; + } + + $properties[] = $this->getProperty($propertyMetadata, $propertyName, $prefixedShortName, $shortName, $hydraPrefix, $operations); } } @@ -260,7 +278,7 @@ private function getHydraProperties(string $resourceClass, ApiResource $resource /** * Gets Hydra operations. */ - private function getHydraOperations(bool $collection, ApiResource $resourceMetadata, string $hydraPrefix = ContextBuilder::HYDRA_PREFIX): array + private function getHydraOperations(bool $collection, ApiResource $resourceMetadata, string $hydraPrefix = ContextBuilder::HYDRA_PREFIX, array $attachedUriTemplates = []): array { $hydraOperations = []; foreach ($resourceMetadata->getOperations() as $operation) { @@ -268,6 +286,10 @@ private function getHydraOperations(bool $collection, ApiResource $resourceMetad continue; } + if (null !== $operation->getUriTemplate() && isset($attachedUriTemplates[UriTemplateHelper::withoutFormatSuffix($operation->getUriTemplate())])) { + continue; + } + if (('POST' === $operation->getMethod() || $operation instanceof CollectionOperationInterface) !== $collection) { continue; } @@ -278,6 +300,52 @@ private function getHydraOperations(bool $collection, ApiResource $resourceMetad return $hydraOperations; } + /** + * Gets the collection operations a property exposes through its URI template, as AbstractItemNormalizer resolves them. + * + * @return list> + */ + private function getUriTemplateOperations(ApiProperty $propertyMetadata, string $hydraPrefix): array + { + if (null === $uriTemplate = $propertyMetadata->getUriTemplate()) { + return []; + } + + $nativeType = $propertyMetadata->getNativeType(); + if ($nativeType?->isSatisfiedBy(static fn ($t) => $t instanceof CollectionType)) { + $nativeType = TypeHelper::getCollectionValueType($nativeType); + } + + $className = null; + if (!$nativeType?->isSatisfiedBy(function (Type $type) use (&$className): bool { + return $type instanceof ObjectType && $this->resourceClassResolver->isResourceClass($className = $type->getClassName()); + }) || null === $className) { + return []; + } + + $strippedUriTemplate = UriTemplateHelper::withoutFormatSuffix($uriTemplate); + $hydraOperations = []; + foreach ($this->resourceMetadataFactory->create($className) as $resourceMetadata) { + foreach ($resourceMetadata->getOperations() ?? [] as $operation) { + if (true === $operation->getHideHydraOperation() || $operation instanceof NotExposed) { + continue; + } + + if (null === $operation->getUriTemplate() || UriTemplateHelper::withoutFormatSuffix($operation->getUriTemplate()) !== $strippedUriTemplate) { + continue; + } + + if ('POST' !== $operation->getMethod() && !$operation instanceof CollectionOperationInterface) { + continue; + } + + $hydraOperations[] = $this->getHydraOperation($operation, $operation->getShortName(), $hydraPrefix); + } + } + + return $hydraOperations; + } + /** * Gets and populates if applicable a Hydra operation. */ @@ -511,7 +579,7 @@ private function getClasses(array $entrypointProperties, array $classes, string /** * Gets a property definition. */ - private function getProperty(ApiProperty $propertyMetadata, string $propertyName, string $prefixedShortName, string $shortName, string $hydraPrefix): array + private function getProperty(ApiProperty $propertyMetadata, string $propertyName, string $prefixedShortName, string $shortName, string $hydraPrefix, array $operations = []): array { if ($iri = $propertyMetadata->getIris()) { $iri = 1 === (is_countable($iri) ? \count($iri) : 0) ? $iri[0] : $iri; @@ -528,6 +596,11 @@ private function getProperty(ApiProperty $propertyMetadata, string $propertyName 'label' => $propertyName, ]; + if ($operations) { + $propertyData['@type'] = $hydraPrefix.'Link'; + $propertyData[$hydraPrefix.'supportedOperation'] = $operations; + } + if (!isset($propertyData['owl:deprecated']) && $propertyMetadata->getDeprecationReason()) { $propertyData['owl:deprecated'] = true; } diff --git a/src/Hydra/Tests/Serializer/DocumentationNormalizerTest.php b/src/Hydra/Tests/Serializer/DocumentationNormalizerTest.php index b83dbdcd8e2..6e0b6ce6a50 100644 --- a/src/Hydra/Tests/Serializer/DocumentationNormalizerTest.php +++ b/src/Hydra/Tests/Serializer/DocumentationNormalizerTest.php @@ -21,6 +21,7 @@ use ApiPlatform\Metadata\ApiResource; use ApiPlatform\Metadata\Get; use ApiPlatform\Metadata\GetCollection; +use ApiPlatform\Metadata\Link; use ApiPlatform\Metadata\Operations; use ApiPlatform\Metadata\Post; use ApiPlatform\Metadata\Property\Factory\PropertyMetadataFactoryInterface; @@ -1066,6 +1067,132 @@ public function testNormalizeSubClassOfWithMultipleTypes(): void $this->assertSame(['https://schema.org/Product', 'https://schema.org/Offer'], $class['subClassOf']); } + public function testNormalizeSubresourceCollectionIsLinkedFromParentPropertyUriTemplate(): void + { + $documentation = new Documentation(new ResourceNameCollection(['Book' => 'Book', 'Review' => 'Review']), 'Test Api', 'test', '0.0.0'); + + $resourceMetadataFactoryProphecy = $this->prophesize(ResourceMetadataCollectionFactoryInterface::class); + $resourceMetadataFactoryProphecy->create('Book')->willReturn(new ResourceMetadataCollection('Book', [ + (new ApiResource())->withShortName('Book')->withOperations(new Operations([ + 'get_collection' => (new GetCollection())->withShortName('Book'), + ])), + ])); + $resourceMetadataFactoryProphecy->create('Review')->willReturn(new ResourceMetadataCollection('Review', [ + (new ApiResource())->withShortName('Review')->withOperations(new Operations([ + 'get' => (new Get())->withShortName('Review'), + 'get_collection' => (new GetCollection(uriTemplate: '/books/{bookId}/reviews{._format}', uriVariables: ['bookId' => new Link(fromClass: 'Book', toProperty: 'book')]))->withShortName('Review'), + 'post' => (new Post(uriTemplate: '/books/{bookId}/reviews{._format}', uriVariables: ['bookId' => new Link(fromClass: 'Book', toProperty: 'book')]))->withShortName('Review'), + ])), + ])); + + $propertyNameCollectionFactoryProphecy = $this->prophesize(PropertyNameCollectionFactoryInterface::class); + $propertyNameCollectionFactoryProphecy->create('Book', [])->willReturn(new PropertyNameCollection(['reviews'])); + $propertyNameCollectionFactoryProphecy->create('Review', [])->willReturn(new PropertyNameCollection([])); + + $propertyMetadataFactoryProphecy = $this->prophesize(PropertyMetadataFactoryInterface::class); + $propertyMetadataFactoryProphecy->create('Book', 'reviews', Argument::type('array'))->willReturn( + (new ApiProperty())->withNativeType(Type::collection(Type::object('Book'), Type::object('Review')))->withUriTemplate('/books/{bookId}/reviews{._format}')->withReadable(true)->withWritable(false)->withReadableLink(false) // @phpstan-ignore-line + ); + + $resourceClassResolverProphecy = $this->prophesize(ResourceClassResolverInterface::class); + $resourceClassResolverProphecy->isResourceClass(Argument::type('string'))->willReturn(true); + + $urlGenerator = $this->prophesize(UrlGeneratorInterface::class); + $urlGenerator->generate('api_entrypoint')->willReturn('/'); + $urlGenerator->generate('api_doc', ['_format' => 'jsonld'])->willReturn('/doc'); + $urlGenerator->generate('api_doc', ['_format' => 'jsonld'], 0)->willReturn('/doc'); + + $documentationNormalizer = new DocumentationNormalizer( + $resourceMetadataFactoryProphecy->reveal(), + $propertyNameCollectionFactoryProphecy->reveal(), + $propertyMetadataFactoryProphecy->reveal(), + $resourceClassResolverProphecy->reveal(), + $urlGenerator->reveal(), + ); + + $classes = []; + foreach ($documentationNormalizer->normalize($documentation)['hydra:supportedClass'] as $class) { + $classes[$class['@id']] = $class; + } + + $entrypointProperties = array_map(static fn (array $property): string => $property['hydra:property']['@id'], $classes['#Entrypoint']['hydra:supportedProperty']); + $this->assertSame(['#Entrypoint/book'], $entrypointProperties); + + $reviews = $classes['#Book']['hydra:supportedProperty'][0]['hydra:property']; + $this->assertSame('#Book/reviews', $reviews['@id']); + $this->assertSame('hydra:Link', $reviews['@type']); + $this->assertEquals([ + [ + '@type' => ['hydra:Operation', 'schema:FindAction'], + 'hydra:method' => 'GET', + 'hydra:title' => 'getReviewCollection', + 'hydra:description' => 'Retrieves the collection of Review resources.', + 'returns' => 'hydra:Collection', + ], + [ + '@type' => ['hydra:Operation', 'schema:CreateAction'], + 'expects' => 'Review', + 'hydra:method' => 'POST', + 'hydra:title' => 'postReview', + 'hydra:description' => 'Creates a Review resource.', + 'returns' => 'Review', + ], + ], $reviews['hydra:supportedOperation']); + } + + public function testNormalizeSubresourceCollectionStaysInEntrypointWithoutPropertyUriTemplate(): void + { + $documentation = new Documentation(new ResourceNameCollection(['Book' => 'Book', 'Review' => 'Review']), 'Test Api', 'test', '0.0.0'); + + $resourceMetadataFactoryProphecy = $this->prophesize(ResourceMetadataCollectionFactoryInterface::class); + $resourceMetadataFactoryProphecy->create('Book')->willReturn(new ResourceMetadataCollection('Book', [ + (new ApiResource())->withShortName('Book')->withOperations(new Operations([ + 'get_collection' => (new GetCollection())->withShortName('Book'), + ])), + ])); + $resourceMetadataFactoryProphecy->create('Review')->willReturn(new ResourceMetadataCollection('Review', [ + (new ApiResource())->withShortName('Review')->withOperations(new Operations([ + 'get' => (new Get())->withShortName('Review'), + 'get_collection' => (new GetCollection(uriTemplate: '/books/{bookId}/reviews{._format}', uriVariables: ['bookId' => new Link(fromClass: 'Book', toProperty: 'book')]))->withShortName('Review'), + 'post' => (new Post(uriTemplate: '/books/{bookId}/reviews{._format}', uriVariables: ['bookId' => new Link(fromClass: 'Book', toProperty: 'book')]))->withShortName('Review'), + ])), + ])); + + $propertyNameCollectionFactoryProphecy = $this->prophesize(PropertyNameCollectionFactoryInterface::class); + $propertyNameCollectionFactoryProphecy->create('Book', [])->willReturn(new PropertyNameCollection(['reviews'])); + $propertyNameCollectionFactoryProphecy->create('Review', [])->willReturn(new PropertyNameCollection([])); + + $propertyMetadataFactoryProphecy = $this->prophesize(PropertyMetadataFactoryInterface::class); + $propertyMetadataFactoryProphecy->create('Book', 'reviews', Argument::type('array'))->willReturn( + (new ApiProperty())->withNativeType(Type::collection(Type::object('Book'), Type::object('Review')))->withReadable(true)->withWritable(false)->withReadableLink(false) // @phpstan-ignore-line + ); + + $resourceClassResolverProphecy = $this->prophesize(ResourceClassResolverInterface::class); + $resourceClassResolverProphecy->isResourceClass(Argument::type('string'))->willReturn(true); + + $urlGenerator = $this->prophesize(UrlGeneratorInterface::class); + $urlGenerator->generate('api_entrypoint')->willReturn('/'); + $urlGenerator->generate('api_doc', ['_format' => 'jsonld'])->willReturn('/doc'); + $urlGenerator->generate('api_doc', ['_format' => 'jsonld'], 0)->willReturn('/doc'); + + $documentationNormalizer = new DocumentationNormalizer( + $resourceMetadataFactoryProphecy->reveal(), + $propertyNameCollectionFactoryProphecy->reveal(), + $propertyMetadataFactoryProphecy->reveal(), + $resourceClassResolverProphecy->reveal(), + $urlGenerator->reveal(), + ); + + $classes = []; + foreach ($documentationNormalizer->normalize($documentation)['hydra:supportedClass'] as $class) { + $classes[$class['@id']] = $class; + } + + $entrypointProperties = array_map(static fn (array $property): string => $property['hydra:property']['@id'], $classes['#Entrypoint']['hydra:supportedProperty']); + $this->assertSame(['#Entrypoint/book', '#Entrypoint/review'], $entrypointProperties); + $this->assertArrayNotHasKey('hydra:supportedOperation', $classes['#Book']['hydra:supportedProperty'][0]['hydra:property']); + } + public function testNormalizeNoEntrypointAndHideHydraOperation(): void { $title = 'Test Api'; From 21b903e1682466e3b27e53a9321bb32a4e04995a Mon Sep 17 00:00:00 2001 From: soyuka Date: Thu, 26 Nov 2026 10:30:58 +0100 Subject: [PATCH 2/2] fix(hydra): keep entrypoint-reachable link operations Only drop an operation from #Entrypoint when a property links to it and its URI template has variables, keyed by short name, method and template. Skip unreadable properties, keep a jsonldContext @type, and require api-platform/metadata ^5.0.1 for UriTemplateHelper. --- .../Serializer/DocumentationNormalizer.php | 43 +++-- .../DocumentationNormalizerTest.php | 172 +++++++++++------- src/Hydra/composer.json | 2 +- .../JsonLd/PropertyCollectionIriOnlyTest.php | 29 +++ 4 files changed, 168 insertions(+), 78 deletions(-) diff --git a/src/Hydra/Serializer/DocumentationNormalizer.php b/src/Hydra/Serializer/DocumentationNormalizer.php index cb0f5596774..7eb896f47ed 100644 --- a/src/Hydra/Serializer/DocumentationNormalizer.php +++ b/src/Hydra/Serializer/DocumentationNormalizer.php @@ -77,7 +77,7 @@ public function normalize(mixed $data, ?string $format = null, array $context = $resourceMetadataCollections[$resourceClass] = $this->resourceMetadataFactory->create($resourceClass); } - $attachedUriTemplates = []; + $attachedOperations = []; foreach ($resourceMetadataCollections as $resourceClass => $resourceMetadataCollection) { foreach ($resourceMetadataCollection as $resourceMetadata) { if (true === $resourceMetadata->getHideHydraOperation()) { @@ -85,7 +85,7 @@ public function normalize(mixed $data, ?string $format = null, array $context = } $shortName = $resourceMetadata->getShortName(); - $classes[] = $this->getClass($resourceClass, $resourceMetadata, $shortName, "#$shortName", $context, $hydraPrefix, $attachedUriTemplates); + $classes[] = $this->getClass($resourceClass, $resourceMetadata, $shortName, "#$shortName", $context, $hydraPrefix, $attachedOperations); } } @@ -96,7 +96,7 @@ public function normalize(mixed $data, ?string $format = null, array $context = } $shortName = $resourceMetadata->getShortName(); - $this->populateEntrypointProperties($resourceMetadata, $shortName, "#$shortName", $entrypointProperties, $hydraPrefix, $attachedUriTemplates); + $this->populateEntrypointProperties($resourceMetadata, $shortName, "#$shortName", $entrypointProperties, $hydraPrefix, $attachedOperations); } } @@ -106,9 +106,9 @@ public function normalize(mixed $data, ?string $format = null, array $context = /** * Populates entrypoint properties. */ - private function populateEntrypointProperties(ApiResource $resourceMetadata, string $shortName, string $prefixedShortName, array &$entrypointProperties, string $hydraPrefix, array $attachedUriTemplates): void + private function populateEntrypointProperties(ApiResource $resourceMetadata, string $shortName, string $prefixedShortName, array &$entrypointProperties, string $hydraPrefix, array $attachedOperations): void { - $hydraCollectionOperations = $this->getHydraOperations(true, $resourceMetadata, $hydraPrefix, $attachedUriTemplates); + $hydraCollectionOperations = $this->getHydraOperations(true, $resourceMetadata, $hydraPrefix, $attachedOperations); if (empty($hydraCollectionOperations)) { return; } @@ -143,7 +143,7 @@ private function populateEntrypointProperties(ApiResource $resourceMetadata, str /** * Gets a Hydra class. */ - private function getClass(string $resourceClass, ApiResource $resourceMetadata, string $shortName, string $prefixedShortName, array $context, string $hydraPrefix, array &$attachedUriTemplates = []): array + private function getClass(string $resourceClass, ApiResource $resourceMetadata, string $shortName, string $prefixedShortName, array $context, string $hydraPrefix, array &$attachedOperations = []): array { $description = $resourceMetadata->getDescription(); $isDeprecated = $resourceMetadata->getDeprecationReason(); @@ -152,7 +152,7 @@ private function getClass(string $resourceClass, ApiResource $resourceMetadata, '@id' => $prefixedShortName, '@type' => $hydraPrefix.'Class', $hydraPrefix.'title' => $shortName, - $hydraPrefix.'supportedProperty' => $this->getHydraProperties($resourceClass, $resourceMetadata, $shortName, $prefixedShortName, $context, $hydraPrefix, $attachedUriTemplates), + $hydraPrefix.'supportedProperty' => $this->getHydraProperties($resourceClass, $resourceMetadata, $shortName, $prefixedShortName, $context, $hydraPrefix, $attachedOperations), $hydraPrefix.'supportedOperation' => $this->getHydraOperations(false, $resourceMetadata, $hydraPrefix), ]; @@ -221,7 +221,7 @@ private function getPropertyMetadataFactoryContext(ApiResource $resourceMetadata /** * Gets Hydra properties. */ - private function getHydraProperties(string $resourceClass, ApiResource $resourceMetadata, string $shortName, string $prefixedShortName, array $context, string $hydraPrefix = ContextBuilder::HYDRA_PREFIX, array &$attachedUriTemplates = []): array + private function getHydraProperties(string $resourceClass, ApiResource $resourceMetadata, string $shortName, string $prefixedShortName, array $context, string $hydraPrefix = ContextBuilder::HYDRA_PREFIX, array &$attachedOperations = []): array { $classes = []; @@ -263,10 +263,7 @@ private function getHydraProperties(string $resourceClass, ApiResource $resource continue; } - $operations = $this->getUriTemplateOperations($propertyMetadata, $hydraPrefix); - if ($operations) { - $attachedUriTemplates[UriTemplateHelper::withoutFormatSuffix($propertyMetadata->getUriTemplate())] = true; - } + $operations = false === $propertyMetadata->isReadable() ? [] : $this->getUriTemplateOperations($propertyMetadata, $hydraPrefix, $attachedOperations); $properties[] = $this->getProperty($propertyMetadata, $propertyName, $prefixedShortName, $shortName, $hydraPrefix, $operations); } @@ -278,7 +275,7 @@ private function getHydraProperties(string $resourceClass, ApiResource $resource /** * Gets Hydra operations. */ - private function getHydraOperations(bool $collection, ApiResource $resourceMetadata, string $hydraPrefix = ContextBuilder::HYDRA_PREFIX, array $attachedUriTemplates = []): array + private function getHydraOperations(bool $collection, ApiResource $resourceMetadata, string $hydraPrefix = ContextBuilder::HYDRA_PREFIX, array $attachedOperations = []): array { $hydraOperations = []; foreach ($resourceMetadata->getOperations() as $operation) { @@ -286,7 +283,7 @@ private function getHydraOperations(bool $collection, ApiResource $resourceMetad continue; } - if (null !== $operation->getUriTemplate() && isset($attachedUriTemplates[UriTemplateHelper::withoutFormatSuffix($operation->getUriTemplate())])) { + if (isset($attachedOperations[$this->getAttachedOperationKey($operation)])) { continue; } @@ -303,9 +300,11 @@ private function getHydraOperations(bool $collection, ApiResource $resourceMetad /** * Gets the collection operations a property exposes through its URI template, as AbstractItemNormalizer resolves them. * + * Operations with URI variables are not reachable from the entrypoint, they are recorded in $attachedOperations to be documented only on the link. + * * @return list> */ - private function getUriTemplateOperations(ApiProperty $propertyMetadata, string $hydraPrefix): array + private function getUriTemplateOperations(ApiProperty $propertyMetadata, string $hydraPrefix, array &$attachedOperations): array { if (null === $uriTemplate = $propertyMetadata->getUriTemplate()) { return []; @@ -339,6 +338,10 @@ private function getUriTemplateOperations(ApiProperty $propertyMetadata, string continue; } + if ($operation->getUriVariables()) { + $attachedOperations[$this->getAttachedOperationKey($operation)] = true; + } + $hydraOperations[] = $this->getHydraOperation($operation, $operation->getShortName(), $hydraPrefix); } } @@ -346,6 +349,11 @@ private function getUriTemplateOperations(ApiProperty $propertyMetadata, string return $hydraOperations; } + private function getAttachedOperationKey(HttpOperation $operation): string + { + return $operation->getShortName().' '.$operation->getMethod().' '.UriTemplateHelper::withoutFormatSuffix($operation->getUriTemplate() ?? ''); + } + /** * Gets and populates if applicable a Hydra operation. */ @@ -597,7 +605,10 @@ private function getProperty(ApiProperty $propertyMetadata, string $propertyName ]; if ($operations) { - $propertyData['@type'] = $hydraPrefix.'Link'; + if (!isset($propertyMetadata->getJsonldContext()[$hydraPrefix.'property']['@type'])) { + $propertyData['@type'] = $hydraPrefix.'Link'; + } + $propertyData[$hydraPrefix.'supportedOperation'] = $operations; } diff --git a/src/Hydra/Tests/Serializer/DocumentationNormalizerTest.php b/src/Hydra/Tests/Serializer/DocumentationNormalizerTest.php index 6e0b6ce6a50..14772a1eb7f 100644 --- a/src/Hydra/Tests/Serializer/DocumentationNormalizerTest.php +++ b/src/Hydra/Tests/Serializer/DocumentationNormalizerTest.php @@ -22,6 +22,7 @@ use ApiPlatform\Metadata\Get; use ApiPlatform\Metadata\GetCollection; use ApiPlatform\Metadata\Link; +use ApiPlatform\Metadata\Operation; use ApiPlatform\Metadata\Operations; use ApiPlatform\Metadata\Post; use ApiPlatform\Metadata\Property\Factory\PropertyMetadataFactoryInterface; @@ -1069,54 +1070,12 @@ public function testNormalizeSubClassOfWithMultipleTypes(): void public function testNormalizeSubresourceCollectionIsLinkedFromParentPropertyUriTemplate(): void { - $documentation = new Documentation(new ResourceNameCollection(['Book' => 'Book', 'Review' => 'Review']), 'Test Api', 'test', '0.0.0'); - - $resourceMetadataFactoryProphecy = $this->prophesize(ResourceMetadataCollectionFactoryInterface::class); - $resourceMetadataFactoryProphecy->create('Book')->willReturn(new ResourceMetadataCollection('Book', [ - (new ApiResource())->withShortName('Book')->withOperations(new Operations([ - 'get_collection' => (new GetCollection())->withShortName('Book'), - ])), - ])); - $resourceMetadataFactoryProphecy->create('Review')->willReturn(new ResourceMetadataCollection('Review', [ - (new ApiResource())->withShortName('Review')->withOperations(new Operations([ - 'get' => (new Get())->withShortName('Review'), - 'get_collection' => (new GetCollection(uriTemplate: '/books/{bookId}/reviews{._format}', uriVariables: ['bookId' => new Link(fromClass: 'Book', toProperty: 'book')]))->withShortName('Review'), - 'post' => (new Post(uriTemplate: '/books/{bookId}/reviews{._format}', uriVariables: ['bookId' => new Link(fromClass: 'Book', toProperty: 'book')]))->withShortName('Review'), - ])), - ])); - - $propertyNameCollectionFactoryProphecy = $this->prophesize(PropertyNameCollectionFactoryInterface::class); - $propertyNameCollectionFactoryProphecy->create('Book', [])->willReturn(new PropertyNameCollection(['reviews'])); - $propertyNameCollectionFactoryProphecy->create('Review', [])->willReturn(new PropertyNameCollection([])); - - $propertyMetadataFactoryProphecy = $this->prophesize(PropertyMetadataFactoryInterface::class); - $propertyMetadataFactoryProphecy->create('Book', 'reviews', Argument::type('array'))->willReturn( - (new ApiProperty())->withNativeType(Type::collection(Type::object('Book'), Type::object('Review')))->withUriTemplate('/books/{bookId}/reviews{._format}')->withReadable(true)->withWritable(false)->withReadableLink(false) // @phpstan-ignore-line - ); - - $resourceClassResolverProphecy = $this->prophesize(ResourceClassResolverInterface::class); - $resourceClassResolverProphecy->isResourceClass(Argument::type('string'))->willReturn(true); - - $urlGenerator = $this->prophesize(UrlGeneratorInterface::class); - $urlGenerator->generate('api_entrypoint')->willReturn('/'); - $urlGenerator->generate('api_doc', ['_format' => 'jsonld'])->willReturn('/doc'); - $urlGenerator->generate('api_doc', ['_format' => 'jsonld'], 0)->willReturn('/doc'); - - $documentationNormalizer = new DocumentationNormalizer( - $resourceMetadataFactoryProphecy->reveal(), - $propertyNameCollectionFactoryProphecy->reveal(), - $propertyMetadataFactoryProphecy->reveal(), - $resourceClassResolverProphecy->reveal(), - $urlGenerator->reveal(), + $classes = $this->normalizeBookReviewsDocumentation( + (new ApiProperty())->withNativeType(Type::collection(Type::object('Book'), Type::object('Review')))->withUriTemplate('/books/{bookId}/reviews{._format}')->withReadable(true)->withWritable(false)->withReadableLink(false), // @phpstan-ignore-line + ['Review' => self::bookReviewsOperations()], ); - $classes = []; - foreach ($documentationNormalizer->normalize($documentation)['hydra:supportedClass'] as $class) { - $classes[$class['@id']] = $class; - } - - $entrypointProperties = array_map(static fn (array $property): string => $property['hydra:property']['@id'], $classes['#Entrypoint']['hydra:supportedProperty']); - $this->assertSame(['#Entrypoint/book'], $entrypointProperties); + $this->assertSame(['#Entrypoint/book'], $this->entrypointPropertyIds($classes)); $reviews = $classes['#Book']['hydra:supportedProperty'][0]['hydra:property']; $this->assertSame('#Book/reviews', $reviews['@id']); @@ -1142,7 +1101,93 @@ public function testNormalizeSubresourceCollectionIsLinkedFromParentPropertyUriT public function testNormalizeSubresourceCollectionStaysInEntrypointWithoutPropertyUriTemplate(): void { - $documentation = new Documentation(new ResourceNameCollection(['Book' => 'Book', 'Review' => 'Review']), 'Test Api', 'test', '0.0.0'); + $classes = $this->normalizeBookReviewsDocumentation( + (new ApiProperty())->withNativeType(Type::collection(Type::object('Book'), Type::object('Review')))->withReadable(true)->withWritable(false)->withReadableLink(false), // @phpstan-ignore-line + ['Review' => self::bookReviewsOperations()], + ); + + $this->assertSame(['#Entrypoint/book', '#Entrypoint/review'], $this->entrypointPropertyIds($classes)); + $this->assertArrayNotHasKey('hydra:supportedOperation', $classes['#Book']['hydra:supportedProperty'][0]['hydra:property']); + } + + public function testNormalizeTopLevelCollectionLinkedFromPropertyStaysInEntrypoint(): void + { + $classes = $this->normalizeBookReviewsDocumentation( + (new ApiProperty())->withNativeType(Type::collection(Type::object('Book'), Type::object('Review')))->withUriTemplate('/reviews{._format}')->withReadable(true)->withWritable(false)->withReadableLink(false), // @phpstan-ignore-line + ['Review' => [ + 'get' => (new Get())->withShortName('Review'), + 'get_collection' => (new GetCollection(uriTemplate: '/reviews{._format}'))->withShortName('Review'), + ]], + ); + + $this->assertSame(['#Entrypoint/book', '#Entrypoint/review'], $this->entrypointPropertyIds($classes)); + $this->assertSame(['GET'], array_column($classes['#Entrypoint']['hydra:supportedProperty'][1]['hydra:property']['hydra:supportedOperation'], 'hydra:method')); + $this->assertSame(['GET'], array_column($classes['#Book']['hydra:supportedProperty'][0]['hydra:property']['hydra:supportedOperation'], 'hydra:method')); + } + + public function testNormalizeSubresourceOperationOfAnotherResourceStaysInEntrypoint(): void + { + $classes = $this->normalizeBookReviewsDocumentation( + (new ApiProperty())->withNativeType(Type::collection(Type::object('Book'), Type::object('Review')))->withUriTemplate('/books/{bookId}/reviews{._format}')->withReadable(true)->withWritable(false)->withReadableLink(false), // @phpstan-ignore-line + [ + 'Review' => [ + 'get' => (new Get())->withShortName('Review'), + 'get_collection' => (new GetCollection(uriTemplate: '/books/{bookId}/reviews{._format}', uriVariables: ['bookId' => new Link(fromClass: 'Book', toProperty: 'book')]))->withShortName('Review'), + ], + 'ReviewInput' => [ + 'post' => (new Post(uriTemplate: '/books/{bookId}/reviews{._format}', uriVariables: ['bookId' => new Link(fromClass: 'Book', toProperty: 'book')]))->withShortName('ReviewInput'), + ], + ], + ); + + $this->assertSame(['#Entrypoint/book', '#Entrypoint/reviewInput'], $this->entrypointPropertyIds($classes)); + $this->assertSame(['GET'], array_column($classes['#Book']['hydra:supportedProperty'][0]['hydra:property']['hydra:supportedOperation'], 'hydra:method')); + } + + public function testNormalizeUnreadablePropertyUriTemplateIsNotLinked(): void + { + $classes = $this->normalizeBookReviewsDocumentation( + (new ApiProperty())->withNativeType(Type::collection(Type::object('Book'), Type::object('Review')))->withUriTemplate('/books/{bookId}/reviews{._format}')->withReadable(false)->withWritable(true)->withReadableLink(false), // @phpstan-ignore-line + ['Review' => self::bookReviewsOperations()], + ); + + $this->assertSame(['#Entrypoint/book', '#Entrypoint/review'], $this->entrypointPropertyIds($classes)); + $this->assertArrayNotHasKey('hydra:supportedOperation', $classes['#Book']['hydra:supportedProperty'][0]['hydra:property']); + } + + public function testNormalizePropertyUriTemplateKeepsJsonldContextType(): void + { + $classes = $this->normalizeBookReviewsDocumentation( + (new ApiProperty())->withNativeType(Type::collection(Type::object('Book'), Type::object('Review')))->withUriTemplate('/books/{bookId}/reviews{._format}')->withJsonldContext(['hydra:property' => ['@type' => 'rdf:Property']])->withReadable(true)->withWritable(false)->withReadableLink(false), // @phpstan-ignore-line + ['Review' => self::bookReviewsOperations()], + ); + + $reviews = $classes['#Book']['hydra:supportedProperty'][0]['hydra:property']; + $this->assertSame('rdf:Property', $reviews['@type']); + $this->assertSame(['GET', 'POST'], array_column($reviews['hydra:supportedOperation'], 'hydra:method')); + } + + /** + * @return array + */ + private static function bookReviewsOperations(): array + { + return [ + 'get' => (new Get())->withShortName('Review'), + 'get_collection' => (new GetCollection(uriTemplate: '/books/{bookId}/reviews{._format}', uriVariables: ['bookId' => new Link(fromClass: 'Book', toProperty: 'book')]))->withShortName('Review'), + 'post' => (new Post(uriTemplate: '/books/{bookId}/reviews{._format}', uriVariables: ['bookId' => new Link(fromClass: 'Book', toProperty: 'book')]))->withShortName('Review'), + ]; + } + + /** + * @param array> $resources + * + * @return array> + */ + private function normalizeBookReviewsDocumentation(ApiProperty $reviews, array $resources): array + { + $resourceNames = ['Book' => 'Book'] + array_combine(array_keys($resources), array_keys($resources)); + $documentation = new Documentation(new ResourceNameCollection($resourceNames), 'Test Api', 'test', '0.0.0'); $resourceMetadataFactoryProphecy = $this->prophesize(ResourceMetadataCollectionFactoryInterface::class); $resourceMetadataFactoryProphecy->create('Book')->willReturn(new ResourceMetadataCollection('Book', [ @@ -1150,22 +1195,19 @@ public function testNormalizeSubresourceCollectionStaysInEntrypointWithoutProper 'get_collection' => (new GetCollection())->withShortName('Book'), ])), ])); - $resourceMetadataFactoryProphecy->create('Review')->willReturn(new ResourceMetadataCollection('Review', [ - (new ApiResource())->withShortName('Review')->withOperations(new Operations([ - 'get' => (new Get())->withShortName('Review'), - 'get_collection' => (new GetCollection(uriTemplate: '/books/{bookId}/reviews{._format}', uriVariables: ['bookId' => new Link(fromClass: 'Book', toProperty: 'book')]))->withShortName('Review'), - 'post' => (new Post(uriTemplate: '/books/{bookId}/reviews{._format}', uriVariables: ['bookId' => new Link(fromClass: 'Book', toProperty: 'book')]))->withShortName('Review'), - ])), - ])); $propertyNameCollectionFactoryProphecy = $this->prophesize(PropertyNameCollectionFactoryInterface::class); $propertyNameCollectionFactoryProphecy->create('Book', [])->willReturn(new PropertyNameCollection(['reviews'])); - $propertyNameCollectionFactoryProphecy->create('Review', [])->willReturn(new PropertyNameCollection([])); + + foreach ($resources as $shortName => $operations) { + $resourceMetadataFactoryProphecy->create($shortName)->willReturn(new ResourceMetadataCollection($shortName, [ + (new ApiResource())->withShortName($shortName)->withOperations(new Operations($operations)), + ])); + $propertyNameCollectionFactoryProphecy->create($shortName, [])->willReturn(new PropertyNameCollection([])); + } $propertyMetadataFactoryProphecy = $this->prophesize(PropertyMetadataFactoryInterface::class); - $propertyMetadataFactoryProphecy->create('Book', 'reviews', Argument::type('array'))->willReturn( - (new ApiProperty())->withNativeType(Type::collection(Type::object('Book'), Type::object('Review')))->withReadable(true)->withWritable(false)->withReadableLink(false) // @phpstan-ignore-line - ); + $propertyMetadataFactoryProphecy->create('Book', 'reviews', Argument::type('array'))->willReturn($reviews); $resourceClassResolverProphecy = $this->prophesize(ResourceClassResolverInterface::class); $resourceClassResolverProphecy->isResourceClass(Argument::type('string'))->willReturn(true); @@ -1188,9 +1230,17 @@ public function testNormalizeSubresourceCollectionStaysInEntrypointWithoutProper $classes[$class['@id']] = $class; } - $entrypointProperties = array_map(static fn (array $property): string => $property['hydra:property']['@id'], $classes['#Entrypoint']['hydra:supportedProperty']); - $this->assertSame(['#Entrypoint/book', '#Entrypoint/review'], $entrypointProperties); - $this->assertArrayNotHasKey('hydra:supportedOperation', $classes['#Book']['hydra:supportedProperty'][0]['hydra:property']); + return $classes; + } + + /** + * @param array> $classes + * + * @return list + */ + private function entrypointPropertyIds(array $classes): array + { + return array_map(static fn (array $property): string => $property['hydra:property']['@id'], $classes['#Entrypoint']['hydra:supportedProperty']); } public function testNormalizeNoEntrypointAndHideHydraOperation(): void diff --git a/src/Hydra/composer.json b/src/Hydra/composer.json index f7b66761dbb..31f240e4261 100644 --- a/src/Hydra/composer.json +++ b/src/Hydra/composer.json @@ -27,7 +27,7 @@ "php": ">=8.2", "api-platform/state": "^5.0", "api-platform/documentation": "^5.0", - "api-platform/metadata": "^5.0", + "api-platform/metadata": "^5.0.1", "api-platform/jsonld": "^5.0", "api-platform/json-schema": "^5.0", "api-platform/serializer": "^5.0", diff --git a/tests/Functional/JsonLd/PropertyCollectionIriOnlyTest.php b/tests/Functional/JsonLd/PropertyCollectionIriOnlyTest.php index d4f160e179a..a3d232ed245 100644 --- a/tests/Functional/JsonLd/PropertyCollectionIriOnlyTest.php +++ b/tests/Functional/JsonLd/PropertyCollectionIriOnlyTest.php @@ -95,4 +95,33 @@ public function testPropertyUriTemplatesRenderAsIris(): void 'toOneRelation' => '/parent/1/property-uri-template/one-to-ones/1', ]); } + + public function testDocumentationAttachesUriTemplateOperationsToLinks(): void + { + $classes = []; + foreach (self::createClient()->request('GET', '/docs.jsonld')->toArray()['hydra:supportedClass'] as $class) { + $classes[$class['@id']] = $class; + } + + $entrypointProperties = []; + foreach ($classes['#Entrypoint']['hydra:supportedProperty'] as $supportedProperty) { + $entrypointProperties[$supportedProperty['hydra:property']['@id']] = $supportedProperty['hydra:property']; + } + + $entrypointOperations = array_column($entrypointProperties['#Entrypoint/propertyCollectionIriOnlyRelation']['hydra:supportedOperation'], 'hydra:method'); + sort($entrypointOperations); + $this->assertSame(['GET', 'POST'], $entrypointOperations); + + $properties = []; + foreach ($classes['#PropertyCollectionIriOnly']['hydra:supportedProperty'] as $supportedProperty) { + $properties[$supportedProperty['hydra:property']['@id']] = $supportedProperty['hydra:property']; + } + + foreach (['#PropertyCollectionIriOnly/propertyCollectionIriOnlyRelation', '#PropertyCollectionIriOnly/iterableIri'] as $link) { + $this->assertSame('hydra:Link', $properties[$link]['@type']); + $this->assertSame(['GET'], array_column($properties[$link]['hydra:supportedOperation'], 'hydra:method')); + } + + $this->assertArrayNotHasKey('hydra:supportedOperation', $properties['#PropertyCollectionIriOnly/toOneRelation']); + } }