diff --git a/src/Hydra/Serializer/DocumentationNormalizer.php b/src/Hydra/Serializer/DocumentationNormalizer.php index 3492403a94d..7eb896f47ed 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); + } + $attachedOperations = []; + 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, $attachedOperations); + } + } - $this->populateEntrypointProperties($resourceMetadata, $shortName, $prefixedShortName, $entrypointProperties, $hydraPrefix); - $classes[] = $this->getClass($resourceClass, $resourceMetadata, $shortName, $prefixedShortName, $context, $hydraPrefix); + foreach ($resourceMetadataCollections as $resourceMetadataCollection) { + foreach ($resourceMetadataCollection as $resourceMetadata) { + if (true === $resourceMetadata->getHideHydraOperation()) { + continue; + } + + $shortName = $resourceMetadata->getShortName(); + $this->populateEntrypointProperties($resourceMetadata, $shortName, "#$shortName", $entrypointProperties, $hydraPrefix, $attachedOperations); } } @@ -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 $attachedOperations): void { - $hydraCollectionOperations = $this->getHydraOperations(true, $resourceMetadata, $hydraPrefix); + $hydraCollectionOperations = $this->getHydraOperations(true, $resourceMetadata, $hydraPrefix, $attachedOperations); 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 &$attachedOperations = []): 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, $attachedOperations), $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 &$attachedOperations = []): array { $classes = []; @@ -250,7 +263,9 @@ private function getHydraProperties(string $resourceClass, ApiResource $resource continue; } - $properties[] = $this->getProperty($propertyMetadata, $propertyName, $prefixedShortName, $shortName, $hydraPrefix); + $operations = false === $propertyMetadata->isReadable() ? [] : $this->getUriTemplateOperations($propertyMetadata, $hydraPrefix, $attachedOperations); + + $properties[] = $this->getProperty($propertyMetadata, $propertyName, $prefixedShortName, $shortName, $hydraPrefix, $operations); } } @@ -260,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 + private function getHydraOperations(bool $collection, ApiResource $resourceMetadata, string $hydraPrefix = ContextBuilder::HYDRA_PREFIX, array $attachedOperations = []): array { $hydraOperations = []; foreach ($resourceMetadata->getOperations() as $operation) { @@ -268,6 +283,10 @@ private function getHydraOperations(bool $collection, ApiResource $resourceMetad continue; } + if (isset($attachedOperations[$this->getAttachedOperationKey($operation)])) { + continue; + } + if (('POST' === $operation->getMethod() || $operation instanceof CollectionOperationInterface) !== $collection) { continue; } @@ -278,6 +297,63 @@ private function getHydraOperations(bool $collection, ApiResource $resourceMetad return $hydraOperations; } + /** + * 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 &$attachedOperations): 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; + } + + if ($operation->getUriVariables()) { + $attachedOperations[$this->getAttachedOperationKey($operation)] = true; + } + + $hydraOperations[] = $this->getHydraOperation($operation, $operation->getShortName(), $hydraPrefix); + } + } + + 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. */ @@ -511,7 +587,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 +604,14 @@ private function getProperty(ApiProperty $propertyMetadata, string $propertyName 'label' => $propertyName, ]; + if ($operations) { + if (!isset($propertyMetadata->getJsonldContext()[$hydraPrefix.'property']['@type'])) { + $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..14772a1eb7f 100644 --- a/src/Hydra/Tests/Serializer/DocumentationNormalizerTest.php +++ b/src/Hydra/Tests/Serializer/DocumentationNormalizerTest.php @@ -21,6 +21,8 @@ use ApiPlatform\Metadata\ApiResource; 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; @@ -1066,6 +1068,181 @@ public function testNormalizeSubClassOfWithMultipleTypes(): void $this->assertSame(['https://schema.org/Product', 'https://schema.org/Offer'], $class['subClassOf']); } + public function testNormalizeSubresourceCollectionIsLinkedFromParentPropertyUriTemplate(): 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' => self::bookReviewsOperations()], + ); + + $this->assertSame(['#Entrypoint/book'], $this->entrypointPropertyIds($classes)); + + $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 + { + $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', [ + (new ApiResource())->withShortName('Book')->withOperations(new Operations([ + 'get_collection' => (new GetCollection())->withShortName('Book'), + ])), + ])); + + $propertyNameCollectionFactoryProphecy = $this->prophesize(PropertyNameCollectionFactoryInterface::class); + $propertyNameCollectionFactoryProphecy->create('Book', [])->willReturn(new PropertyNameCollection(['reviews'])); + + 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($reviews); + + $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; + } + + 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 { $title = 'Test Api'; 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']); + } }