Skip to content

WIP - Makes url generation strategy default value configurable #2708

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

Closed
Closed
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
5 changes: 5 additions & 0 deletions src/Api/UrlGeneratorInterface.php
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,11 @@
*/
interface UrlGeneratorInterface
{
/**
* Allow to generate url using the globally configured strategy.
*/
public const DEFAULT_STRATEGY = -1;

/**
* Generates an absolute URL, e.g. "http://example.com/dir/file".
*/
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -139,6 +139,7 @@ private function registerCommonConfiguration(ContainerBuilder $container, array
$container->setParameter('api_platform.description', $config['description']);
$container->setParameter('api_platform.version', $config['version']);
$container->setParameter('api_platform.show_webby', $config['show_webby']);
$container->setParameter('api_platform.url_generation_strategy', $config['url_generation_strategy']);
$container->setParameter('api_platform.exception_to_status', $config['exception_to_status']);
$container->setParameter('api_platform.formats', $formats);
$container->setParameter('api_platform.error_formats', $errorFormats);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@

namespace ApiPlatform\Core\Bridge\Symfony\Bundle\DependencyInjection;

use ApiPlatform\Core\Api\UrlGeneratorInterface;
use ApiPlatform\Core\Bridge\Elasticsearch\Metadata\Document\DocumentMetadata;
use ApiPlatform\Core\Exception\FilterValidationException;
use ApiPlatform\Core\Exception\InvalidArgumentException;
Expand Down Expand Up @@ -80,6 +81,7 @@ public function getConfigTreeBuilder()
->end()
->scalarNode('name_converter')->defaultNull()->info('Specify a name converter to use.')->end()
->scalarNode('path_segment_name_generator')->defaultValue('api_platform.path_segment_name_generator.underscore')->info('Specify a path name generator to use.')->end()
->integerNode('url_generation_strategy')->defaultValue(UrlGeneratorInterface::ABS_PATH)->info('The default URL generation strategy')->end()
->booleanNode('allow_plain_identifiers')->defaultFalse()->info('Allow plain identifiers, for example "id" instead of "@id" when denormalizing a relation.')->end()
->arrayNode('validator')
->addDefaultsIfNotSet()
Expand Down
1 change: 1 addition & 0 deletions src/Bridge/Symfony/Bundle/Resources/config/api.xml
Original file line number Diff line number Diff line change
Expand Up @@ -61,6 +61,7 @@
<argument type="service" id="api_platform.identifiers_extractor.cached" />
<argument type="service" id="api_platform.subresource_data_provider" on-invalid="ignore" />
<argument type="service" id="api_platform.identifier.converter" on-invalid="ignore" />
<argument>%api_platform.url_generation_strategy%</argument>
</service>
<service id="ApiPlatform\Core\Api\IriConverterInterface" alias="api_platform.iri_converter" />

Expand Down
1 change: 1 addition & 0 deletions src/Bridge/Symfony/Bundle/Resources/config/hal.xml
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@
<argument type="service" id="api_platform.metadata.resource.metadata_factory" />
<argument type="service" id="api_platform.iri_converter" />
<argument type="service" id="api_platform.router" />
<argument>%api_platform.url_generation_strategy%</argument>

<tag name="serializer.normalizer" priority="-800" />
</service>
Expand Down
4 changes: 4 additions & 0 deletions src/Bridge/Symfony/Bundle/Resources/config/hydra.xml
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@
<argument type="service" id="api_platform.router" />
<argument type="service" id="api_platform.subresource_operation_factory" />
<argument type="service" id="api_platform.name_converter" on-invalid="ignore" />
<argument>%api_platform.url_generation_strategy%</argument>

<tag name="serializer.normalizer" priority="-800" />
</service>
Expand All @@ -33,6 +34,7 @@
<argument type="service" id="api_platform.router" />
<argument>%api_platform.validator.serialize_payload_fields%</argument>
<argument type="service" id="api_platform.name_converter" on-invalid="ignore" />
<argument>%api_platform.url_generation_strategy%</argument>

<tag name="serializer.normalizer" priority="-780" />
</service>
Expand All @@ -48,6 +50,8 @@
<service id="api_platform.hydra.normalizer.error" class="ApiPlatform\Core\Hydra\Serializer\ErrorNormalizer" public="false">
<argument type="service" id="api_platform.router" />
<argument>%kernel.debug%</argument>
<argument type="collection" />
<argument>%api_platform.url_generation_strategy%</argument>

<tag name="serializer.normalizer" priority="-800" />
</service>
Expand Down
20 changes: 11 additions & 9 deletions src/Bridge/Symfony/Routing/IriConverter.php
Original file line number Diff line number Diff line change
Expand Up @@ -48,15 +48,17 @@ final class IriConverter implements IriConverterInterface
private $routeNameResolver;
private $router;
private $identifiersExtractor;
private $urlGenerationStrategy;

public function __construct(PropertyNameCollectionFactoryInterface $propertyNameCollectionFactory, PropertyMetadataFactoryInterface $propertyMetadataFactory, ItemDataProviderInterface $itemDataProvider, RouteNameResolverInterface $routeNameResolver, RouterInterface $router, PropertyAccessorInterface $propertyAccessor = null, IdentifiersExtractorInterface $identifiersExtractor = null, SubresourceDataProviderInterface $subresourceDataProvider = null, IdentifierConverterInterface $identifierConverter = null)
public function __construct(PropertyNameCollectionFactoryInterface $propertyNameCollectionFactory, PropertyMetadataFactoryInterface $propertyMetadataFactory, ItemDataProviderInterface $itemDataProvider, RouteNameResolverInterface $routeNameResolver, RouterInterface $router, PropertyAccessorInterface $propertyAccessor = null, IdentifiersExtractorInterface $identifiersExtractor = null, SubresourceDataProviderInterface $subresourceDataProvider = null, IdentifierConverterInterface $identifierConverter = null, int $urlGenerationStrategy = UrlGeneratorInterface::ABS_PATH)
{
$this->itemDataProvider = $itemDataProvider;
$this->routeNameResolver = $routeNameResolver;
$this->router = $router;
$this->identifiersExtractor = $identifiersExtractor;
$this->subresourceDataProvider = $subresourceDataProvider;
$this->identifierConverter = $identifierConverter;
$this->urlGenerationStrategy = $urlGenerationStrategy;

if (null === $identifiersExtractor) {
@trigger_error(sprintf('Not injecting "%s" is deprecated since API Platform 2.1 and will not be possible anymore in API Platform 3', IdentifiersExtractorInterface::class), E_USER_DEPRECATED);
Expand Down Expand Up @@ -113,7 +115,7 @@ public function getItemFromIri(string $iri, array $context = [])
/**
* {@inheritdoc}
*/
public function getIriFromItem($item, int $referenceType = UrlGeneratorInterface::ABS_PATH): string
public function getIriFromItem($item, int $referenceType = UrlGeneratorInterface::DEFAULT_STRATEGY): string
{
$resourceClass = $this->getObjectClass($item);

Expand All @@ -126,16 +128,16 @@ public function getIriFromItem($item, int $referenceType = UrlGeneratorInterface
), $e->getCode(), $e);
}

return $this->getItemIriFromResourceClass($resourceClass, $identifiers, $referenceType);
return $this->getItemIriFromResourceClass($resourceClass, $identifiers, UrlGeneratorInterface::DEFAULT_STRATEGY === $referenceType ? $this->urlGenerationStrategy : $referenceType);
}

/**
* {@inheritdoc}
*/
public function getIriFromResourceClass(string $resourceClass, int $referenceType = UrlGeneratorInterface::ABS_PATH): string
public function getIriFromResourceClass(string $resourceClass, int $referenceType = UrlGeneratorInterface::DEFAULT_STRATEGY): string
{
try {
return $this->router->generate($this->routeNameResolver->getRouteName($resourceClass, OperationType::COLLECTION), [], $referenceType);
return $this->router->generate($this->routeNameResolver->getRouteName($resourceClass, OperationType::COLLECTION), [], UrlGeneratorInterface::DEFAULT_STRATEGY === $referenceType ? $this->urlGenerationStrategy : $referenceType);
} catch (RoutingExceptionInterface $e) {
throw new InvalidArgumentException(sprintf('Unable to generate an IRI for "%s".', $resourceClass), $e->getCode(), $e);
}
Expand All @@ -144,14 +146,14 @@ public function getIriFromResourceClass(string $resourceClass, int $referenceTyp
/**
* {@inheritdoc}
*/
public function getItemIriFromResourceClass(string $resourceClass, array $identifiers, int $referenceType = UrlGeneratorInterface::ABS_PATH): string
public function getItemIriFromResourceClass(string $resourceClass, array $identifiers, int $referenceType = UrlGeneratorInterface::DEFAULT_STRATEGY): string
{
$routeName = $this->routeNameResolver->getRouteName($resourceClass, OperationType::ITEM);

try {
$identifiers = $this->generateIdentifiersUrl($identifiers, $resourceClass);

return $this->router->generate($routeName, ['id' => implode(';', $identifiers)], $referenceType);
return $this->router->generate($routeName, ['id' => implode(';', $identifiers)], UrlGeneratorInterface::DEFAULT_STRATEGY === $referenceType ? $this->urlGenerationStrategy : $referenceType);
} catch (RoutingExceptionInterface $e) {
throw new InvalidArgumentException(sprintf(
'Unable to generate an IRI for "%s".',
Expand All @@ -163,10 +165,10 @@ public function getItemIriFromResourceClass(string $resourceClass, array $identi
/**
* {@inheritdoc}
*/
public function getSubresourceIriFromResourceClass(string $resourceClass, array $context, int $referenceType = UrlGeneratorInterface::ABS_PATH): string
public function getSubresourceIriFromResourceClass(string $resourceClass, array $context, int $referenceType = UrlGeneratorInterface::DEFAULT_STRATEGY): string
{
try {
return $this->router->generate($this->routeNameResolver->getRouteName($resourceClass, OperationType::SUBRESOURCE, $context), $context['subresource_identifiers'], $referenceType);
return $this->router->generate($this->routeNameResolver->getRouteName($resourceClass, OperationType::SUBRESOURCE, $context), $context['subresource_identifiers'], UrlGeneratorInterface::DEFAULT_STRATEGY === $referenceType ? $this->urlGenerationStrategy : $referenceType);
} catch (RoutingExceptionInterface $e) {
throw new InvalidArgumentException(sprintf('Unable to generate an IRI for "%s".', $resourceClass), $e->getCode(), $e);
}
Expand Down
6 changes: 4 additions & 2 deletions src/Hal/Serializer/EntrypointNormalizer.php
Original file line number Diff line number Diff line change
Expand Up @@ -33,20 +33,22 @@ final class EntrypointNormalizer implements NormalizerInterface, CacheableSuppor
private $resourceMetadataFactory;
private $iriConverter;
private $urlGenerator;
private $urlGenerationStrategy;

public function __construct(ResourceMetadataFactoryInterface $resourceMetadataFactory, IriConverterInterface $iriConverter, UrlGeneratorInterface $urlGenerator)
public function __construct(ResourceMetadataFactoryInterface $resourceMetadataFactory, IriConverterInterface $iriConverter, UrlGeneratorInterface $urlGenerator, int $urlGenerationStrategy = UrlGeneratorInterface::ABS_PATH)
{
$this->resourceMetadataFactory = $resourceMetadataFactory;
$this->iriConverter = $iriConverter;
$this->urlGenerator = $urlGenerator;
$this->urlGenerationStrategy = $urlGenerationStrategy;
}

/**
* {@inheritdoc}
*/
public function normalize($object, $format = null, array $context = [])
{
$entrypoint = ['_links' => ['self' => ['href' => $this->urlGenerator->generate('api_entrypoint')]]];
$entrypoint = ['_links' => ['self' => ['href' => $this->urlGenerator->generate('api_entrypoint', [], $this->urlGenerationStrategy)]]];

foreach ($object->getResourceNameCollection() as $resourceClass) {
$resourceMetadata = $this->resourceMetadataFactory->create($resourceClass);
Expand Down
6 changes: 4 additions & 2 deletions src/Hydra/Serializer/ConstraintViolationListNormalizer.php
Original file line number Diff line number Diff line change
Expand Up @@ -27,12 +27,14 @@ final class ConstraintViolationListNormalizer extends AbstractConstraintViolatio
public const FORMAT = 'jsonld';

private $urlGenerator;
private $urlGenerationStrategy;

public function __construct(UrlGeneratorInterface $urlGenerator, array $serializePayloadFields = null, NameConverterInterface $nameConverter = null)
public function __construct(UrlGeneratorInterface $urlGenerator, array $serializePayloadFields = null, NameConverterInterface $nameConverter = null, int $urlGenerationStrategy = UrlGeneratorInterface::ABS_PATH)
{
parent::__construct($serializePayloadFields, $nameConverter);

$this->urlGenerator = $urlGenerator;
$this->urlGenerationStrategy = $urlGenerationStrategy;
}

/**
Expand All @@ -43,7 +45,7 @@ public function normalize($object, $format = null, array $context = [])
[$messages, $violations] = $this->getMessagesAndViolations($object);

return [
'@context' => $this->urlGenerator->generate('api_jsonld_context', ['shortName' => 'ConstraintViolationList']),
'@context' => $this->urlGenerator->generate('api_jsonld_context', ['shortName' => 'ConstraintViolationList'], $this->urlGenerationStrategy),
'@type' => 'ConstraintViolationList',
'hydra:title' => $context['title'] ?? 'An error occurred',
'hydra:description' => $messages ? implode("\n", $messages) : (string) $object,
Expand Down
8 changes: 5 additions & 3 deletions src/Hydra/Serializer/DocumentationNormalizer.php
Original file line number Diff line number Diff line change
Expand Up @@ -49,8 +49,9 @@ final class DocumentationNormalizer implements NormalizerInterface, CacheableSup
private $urlGenerator;
private $subresourceOperationFactory;
private $nameConverter;
private $urlGenerationStrategy;

public function __construct(ResourceMetadataFactoryInterface $resourceMetadataFactory, PropertyNameCollectionFactoryInterface $propertyNameCollectionFactory, PropertyMetadataFactoryInterface $propertyMetadataFactory, ResourceClassResolverInterface $resourceClassResolver, OperationMethodResolverInterface $operationMethodResolver, UrlGeneratorInterface $urlGenerator, SubresourceOperationFactoryInterface $subresourceOperationFactory = null, NameConverterInterface $nameConverter = null)
public function __construct(ResourceMetadataFactoryInterface $resourceMetadataFactory, PropertyNameCollectionFactoryInterface $propertyNameCollectionFactory, PropertyMetadataFactoryInterface $propertyMetadataFactory, ResourceClassResolverInterface $resourceClassResolver, OperationMethodResolverInterface $operationMethodResolver, UrlGeneratorInterface $urlGenerator, SubresourceOperationFactoryInterface $subresourceOperationFactory = null, NameConverterInterface $nameConverter = null, int $urlGenerationStrategy = UrlGeneratorInterface::ABS_PATH)
{
$this->resourceMetadataFactory = $resourceMetadataFactory;
$this->propertyNameCollectionFactory = $propertyNameCollectionFactory;
Expand All @@ -60,6 +61,7 @@ public function __construct(ResourceMetadataFactoryInterface $resourceMetadataFa
$this->urlGenerator = $urlGenerator;
$this->subresourceOperationFactory = $subresourceOperationFactory;
$this->nameConverter = $nameConverter;
$this->urlGenerationStrategy = $urlGenerationStrategy;
}

/**
Expand Down Expand Up @@ -499,7 +501,7 @@ private function getProperty(PropertyMetadata $propertyMetadata, string $propert
*/
private function computeDoc(Documentation $object, array $classes): array
{
$doc = ['@context' => $this->getContext(), '@id' => $this->urlGenerator->generate('api_doc', ['_format' => self::FORMAT]), '@type' => 'hydra:ApiDocumentation'];
$doc = ['@context' => $this->getContext(), '@id' => $this->urlGenerator->generate('api_doc', ['_format' => self::FORMAT], $this->urlGenerationStrategy), '@type' => 'hydra:ApiDocumentation'];

if ('' !== $object->getTitle()) {
$doc['hydra:title'] = $object->getTitle();
Expand All @@ -509,7 +511,7 @@ private function computeDoc(Documentation $object, array $classes): array
$doc['hydra:description'] = $object->getDescription();
}

$doc['hydra:entrypoint'] = $this->urlGenerator->generate('api_entrypoint');
$doc['hydra:entrypoint'] = $this->urlGenerator->generate('api_entrypoint', [], $this->urlGenerationStrategy);
$doc['hydra:supportedClass'] = $classes;

return $doc;
Expand Down
8 changes: 5 additions & 3 deletions src/Hydra/Serializer/EntrypointNormalizer.php
Original file line number Diff line number Diff line change
Expand Up @@ -33,12 +33,14 @@ final class EntrypointNormalizer implements NormalizerInterface, CacheableSuppor
private $resourceMetadataFactory;
private $iriConverter;
private $urlGenerator;
private $urlGenerationStrategy;

public function __construct(ResourceMetadataFactoryInterface $resourceMetadataFactory, IriConverterInterface $iriConverter, UrlGeneratorInterface $urlGenerator)
public function __construct(ResourceMetadataFactoryInterface $resourceMetadataFactory, IriConverterInterface $iriConverter, UrlGeneratorInterface $urlGenerator, int $urlGenerationStrategy = UrlGeneratorInterface::ABS_PATH)
{
$this->resourceMetadataFactory = $resourceMetadataFactory;
$this->iriConverter = $iriConverter;
$this->urlGenerator = $urlGenerator;
$this->urlGenerationStrategy = $urlGenerationStrategy;
}

/**
Expand All @@ -47,8 +49,8 @@ public function __construct(ResourceMetadataFactoryInterface $resourceMetadataFa
public function normalize($object, $format = null, array $context = [])
{
$entrypoint = [
'@context' => $this->urlGenerator->generate('api_jsonld_context', ['shortName' => 'Entrypoint']),
'@id' => $this->urlGenerator->generate('api_entrypoint'),
'@context' => $this->urlGenerator->generate('api_jsonld_context', ['shortName' => 'Entrypoint'], $this->urlGenerationStrategy),
'@id' => $this->urlGenerator->generate('api_entrypoint', [], $this->urlGenerationStrategy),
'@type' => 'Entrypoint',
];

Expand Down
6 changes: 4 additions & 2 deletions src/Hydra/Serializer/ErrorNormalizer.php
Original file line number Diff line number Diff line change
Expand Up @@ -35,12 +35,14 @@ final class ErrorNormalizer implements NormalizerInterface, CacheableSupportsMet
private $urlGenerator;
private $debug;
private $defaultContext = [self::TITLE => 'An error occurred'];
private $urlGenerationStrategy;

public function __construct(UrlGeneratorInterface $urlGenerator, bool $debug = false, array $defaultContext = [])
public function __construct(UrlGeneratorInterface $urlGenerator, bool $debug = false, array $defaultContext = [], int $urlGenerationStrategy = UrlGeneratorInterface::ABS_PATH)
{
$this->urlGenerator = $urlGenerator;
$this->debug = $debug;
$this->defaultContext = array_merge($this->defaultContext, $defaultContext);
$this->urlGenerationStrategy = $urlGenerationStrategy;
}

/**
Expand All @@ -49,7 +51,7 @@ public function __construct(UrlGeneratorInterface $urlGenerator, bool $debug = f
public function normalize($object, $format = null, array $context = [])
{
$data = [
'@context' => $this->urlGenerator->generate('api_jsonld_context', ['shortName' => 'Error']),
'@context' => $this->urlGenerator->generate('api_jsonld_context', ['shortName' => 'Error'], $this->urlGenerationStrategy),
'@type' => 'hydra:Error',
'hydra:title' => $context[self::TITLE] ?? $this->defaultContext[self::TITLE],
'hydra:description' => $this->getErrorMessage($object, $context, $this->debug),
Expand Down
Loading