Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix(hydra): use correctly enable_docs #7062

Merged
merged 1 commit into from
Apr 10, 2025
Merged
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
33 changes: 19 additions & 14 deletions src/Hydra/Serializer/DocumentationNormalizer.php
Original file line number Diff line number Diff line change
Expand Up @@ -54,6 +54,7 @@ public function __construct(
private readonly UrlGeneratorInterface $urlGenerator,
private readonly ?NameConverterInterface $nameConverter = null,
private readonly ?array $defaultContext = [],
private readonly ?bool $entrypointEnabled = true,
) {
}

Expand Down Expand Up @@ -443,19 +444,21 @@ private function isSingleRelation(ApiProperty $propertyMetadata): bool
*/
private function getClasses(array $entrypointProperties, array $classes, string $hydraPrefix = ContextBuilder::HYDRA_PREFIX): array
{
$classes[] = [
'@id' => '#Entrypoint',
'@type' => $hydraPrefix.'Class',
$hydraPrefix.'title' => 'Entrypoint',
$hydraPrefix.'supportedProperty' => $entrypointProperties,
$hydraPrefix.'supportedOperation' => [
'@type' => $hydraPrefix.'Operation',
$hydraPrefix.'method' => 'GET',
$hydraPrefix.'title' => 'index',
$hydraPrefix.'description' => 'The API Entrypoint.',
$hydraPrefix.'returns' => 'Entrypoint',
],
];
if ($this->entrypointEnabled) {
$classes[] = [
'@id' => '#Entrypoint',
'@type' => $hydraPrefix.'Class',
$hydraPrefix.'title' => 'Entrypoint',
$hydraPrefix.'supportedProperty' => $entrypointProperties,
$hydraPrefix.'supportedOperation' => [
'@type' => $hydraPrefix.'Operation',
$hydraPrefix.'method' => 'GET',
$hydraPrefix.'title' => 'index',
$hydraPrefix.'description' => 'The API Entrypoint.',
$hydraPrefix.'returns' => 'Entrypoint',
],
];
}

$classes[] = [
'@id' => '#ConstraintViolationList',
Expand Down Expand Up @@ -560,7 +563,9 @@ private function computeDoc(Documentation $object, array $classes, string $hydra
$doc[$hydraPrefix.'description'] = $object->getDescription();
}

$doc[$hydraPrefix.'entrypoint'] = $this->urlGenerator->generate('api_entrypoint');
if ($this->entrypointEnabled) {
$doc[$hydraPrefix.'entrypoint'] = $this->urlGenerator->generate('api_entrypoint');
}
$doc[$hydraPrefix.'supportedClass'] = $classes;

return $doc;
Expand Down
102 changes: 102 additions & 0 deletions src/Hydra/Tests/Serializer/DocumentationNormalizerTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -824,4 +824,106 @@ public function testNormalizeWithoutPrefix(): void

$this->assertEquals($expected, $documentationNormalizer->normalize($documentation, null, [ContextBuilder::HYDRA_CONTEXT_HAS_PREFIX => false]));
}

public function testNormalizeNoEntrypointAndHideHydraOperation(): void
{
$title = 'Test Api';
$desc = 'test ApiGerard';
$version = '0.0.0';
$documentation = new Documentation(new ResourceNameCollection(['dummy' => 'dummy']), $title, $desc, $version);

$resourceMetadataFactoryProphecy = $this->prophesize(ResourceMetadataCollectionFactoryInterface::class);
$resourceMetadataFactoryProphecy->create('dummy')->willReturn(new ResourceMetadataCollection('dummy', [
(new ApiResource())->withHideHydraOperation(true)->withOperations(new Operations([
'get' => new Get(),
])),
]));
$propertyNameCollectionFactoryProphecy = $this->prophesize(PropertyNameCollectionFactoryInterface::class);
$propertyMetadataFactoryProphecy = $this->prophesize(PropertyMetadataFactoryInterface::class);
$resourceClassResolverProphecy = $this->prophesize(ResourceClassResolverInterface::class);
$urlGenerator = $this->prophesize(UrlGeneratorInterface::class);
$urlGenerator->generate('api_doc', ['_format' => 'jsonld'], Argument::any())->willReturn('/doc');

$documentationNormalizer = new DocumentationNormalizer(
$resourceMetadataFactoryProphecy->reveal(),
$propertyNameCollectionFactoryProphecy->reveal(),
$propertyMetadataFactoryProphecy->reveal(),
$resourceClassResolverProphecy->reveal(),
$urlGenerator->reveal(),
new CustomConverter(),
[],
false,
);

$expected = [
'@context' => [
HYDRA_CONTEXT,
[
'@vocab' => '/doc#',
'hydra' => 'http://www.w3.org/ns/hydra/core#',
'rdf' => 'http://www.w3.org/1999/02/22-rdf-syntax-ns#',
'rdfs' => 'http://www.w3.org/2000/01/rdf-schema#',
'xmls' => 'http://www.w3.org/2001/XMLSchema#',
'owl' => 'http://www.w3.org/2002/07/owl#',
'schema' => 'https://schema.org/',
'domain' => [
'@id' => 'rdfs:domain',
'@type' => '@id',
],
'range' => [
'@id' => 'rdfs:range',
'@type' => '@id',
],
'subClassOf' => [
'@id' => 'rdfs:subClassOf',
'@type' => '@id',
],
],
],
'@id' => '/doc',
'@type' => 'ApiDocumentation',
'title' => 'Test Api',
'description' => 'test ApiGerard',
'supportedClass' => [
[
'@id' => '#ConstraintViolationList',
'@type' => 'Class',
'title' => 'ConstraintViolationList',
'description' => 'A constraint violation List.',
'supportedProperty' => [
[
'@type' => 'SupportedProperty',
'property' => [
'@id' => '#ConstraintViolationList/propertyPath',
'@type' => 'rdf:Property',
'rdfs:label' => 'propertyPath',
'domain' => '#ConstraintViolationList',
'range' => 'xmls:string',
],
'title' => 'propertyPath',
'description' => 'The property path of the violation',
'readable' => true,
'writeable' => false,
],
[
'@type' => 'SupportedProperty',
'property' => [
'@id' => '#ConstraintViolationList/message',
'@type' => 'rdf:Property',
'rdfs:label' => 'message',
'domain' => '#ConstraintViolationList',
'range' => 'xmls:string',
],
'title' => 'message',
'description' => 'The message associated with the violation',
'readable' => true,
'writeable' => false,
],
],
],
],
];

$this->assertEquals($expected, $documentationNormalizer->normalize($documentation, null, [ContextBuilder::HYDRA_CONTEXT_HAS_PREFIX => false]));
}
}
4 changes: 3 additions & 1 deletion src/Laravel/ApiPlatformProvider.php
Original file line number Diff line number Diff line change
Expand Up @@ -731,6 +731,7 @@ public function register(): void
$this->app->singleton(HydraDocumentationNormalizer::class, function (Application $app) {
$config = $app['config'];
$defaultContext = $config->get('api-platform.serializer', []);
$entrypointEnabled = $config->get('api-platform.enable_entrypoint', true);

return new HydraDocumentationNormalizer(
$app->make(ResourceMetadataCollectionFactoryInterface::class),
Expand All @@ -739,7 +740,8 @@ public function register(): void
$app->make(ResourceClassResolverInterface::class),
$app->make(UrlGeneratorInterface::class),
$app->make(NameConverterInterface::class),
$defaultContext
$defaultContext,
$entrypointEnabled
);
});

Expand Down
13 changes: 8 additions & 5 deletions src/Symfony/Bundle/DependencyInjection/ApiPlatformExtension.php
Original file line number Diff line number Diff line change
Expand Up @@ -112,6 +112,14 @@ public function load(array $configs, ContainerBuilder $container): void
$patchFormats = $this->getFormats($config['patch_formats']);
$errorFormats = $this->getFormats($config['error_formats']);
$docsFormats = $this->getFormats($config['docs_formats']);
if (!$config['enable_docs']) {
// JSON-LD documentation format is mandatory, even if documentation is disabled.
$docsFormats = isset($formats['jsonld']) ? ['jsonld' => ['application/ld+json']] : [];
// If documentation is disabled, the Hydra documentation for all the resources is hidden by default.
if (!isset($config['defaults']['hideHydraOperation']) && !isset($config['defaults']['hide_hydra_operation'])) {
$config['defaults']['hideHydraOperation'] = true;
}
}
$jsonSchemaFormats = $config['jsonschema_formats'];

if (!$jsonSchemaFormats) {
Expand Down Expand Up @@ -538,11 +546,6 @@ private function registerJsonLdHydraConfiguration(ContainerBuilder $container, a
if (!$container->has('api_platform.json_schema.schema_factory')) {
$container->removeDefinition('api_platform.hydra.json_schema.schema_factory');
}

if (!$config['enable_docs']) {
$container->removeDefinition('api_platform.hydra.listener.response.add_link_header');
$container->removeDefinition('api_platform.hydra.processor.link');
}
}

private function registerJsonHalConfiguration(array $formats, XmlFileLoader $loader): void
Expand Down
1 change: 1 addition & 0 deletions src/Symfony/Bundle/Resources/config/hydra.xml
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@
<argument type="service" id="api_platform.router" />
<argument type="service" id="api_platform.name_converter" on-invalid="ignore" />
<argument>%api_platform.serializer.default_context%</argument>
<argument>%api_platform.enable_entrypoint%</argument>

<tag name="serializer.normalizer" priority="-800" />
</service>
Expand Down
7 changes: 2 additions & 5 deletions src/Symfony/Routing/ApiLoader.php
Original file line number Diff line number Diff line change
Expand Up @@ -36,7 +36,7 @@ final class ApiLoader extends Loader

private readonly XmlFileLoader $fileLoader;

public function __construct(KernelInterface $kernel, private readonly ResourceNameCollectionFactoryInterface $resourceNameCollectionFactory, private readonly ResourceMetadataCollectionFactoryInterface $resourceMetadataFactory, private readonly ContainerInterface $container, private readonly array $formats, private readonly array $resourceClassDirectories = [], private readonly bool $graphqlEnabled = false, private readonly bool $entrypointEnabled = true, private readonly bool $docsEnabled = true, private readonly bool $graphiQlEnabled = false, private readonly bool $graphQlPlaygroundEnabled = false)
public function __construct(KernelInterface $kernel, private readonly ResourceNameCollectionFactoryInterface $resourceNameCollectionFactory, private readonly ResourceMetadataCollectionFactoryInterface $resourceMetadataFactory, private readonly ContainerInterface $container, private readonly array $formats, private readonly array $resourceClassDirectories = [], private readonly bool $graphqlEnabled = false, private readonly bool $entrypointEnabled = true, readonly bool $docsEnabled = true, private readonly bool $graphiQlEnabled = false, private readonly bool $graphQlPlaygroundEnabled = false)
{
/** @var string[]|string $paths */
$paths = $kernel->locateResource('@ApiPlatformBundle/Resources/config/routing');
Expand Down Expand Up @@ -124,17 +124,14 @@ public function supports(mixed $resource, ?string $type = null): bool
*/
private function loadExternalFiles(RouteCollection $routeCollection): void
{
$routeCollection->addCollection($this->fileLoader->load('docs.xml'));
$routeCollection->addCollection($this->fileLoader->load('genid.xml'));
$routeCollection->addCollection($this->fileLoader->load('errors.xml'));

if ($this->entrypointEnabled) {
$routeCollection->addCollection($this->fileLoader->load('api.xml'));
}

if ($this->docsEnabled) {
$routeCollection->addCollection($this->fileLoader->load('docs.xml'));
}

if ($this->graphqlEnabled) {
$graphqlCollection = $this->fileLoader->load('graphql/graphql.xml');
$graphqlCollection->addDefaults(['_graphql' => true]);
Expand Down
Loading