Skip to content
Open
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
7 changes: 6 additions & 1 deletion src/Laravel/ApiPlatformProvider.php
Original file line number Diff line number Diff line change
Expand Up @@ -177,6 +177,7 @@
use ApiPlatform\State\Provider\DeserializeProvider;
use ApiPlatform\State\Provider\ObjectMapperProvider;
use ApiPlatform\State\Provider\ParameterProvider;
use ApiPlatform\State\Provider\RangeHeaderProvider;
use ApiPlatform\State\Provider\ReadProvider;
use ApiPlatform\State\ProviderInterface;
use ApiPlatform\State\SerializerContextBuilderInterface;
Expand Down Expand Up @@ -451,12 +452,16 @@ public function register(): void
return new ReadProvider($app->make(CallableProvider::class));
});

$this->app->singleton(RangeHeaderProvider::class, static function (Application $app) {
return new RangeHeaderProvider($app->make(ReadProvider::class), $app->make(Pagination::class));
});

$this->app->singleton(SwaggerUiProvider::class, static function (Application $app) {
/** @var ConfigRepository */
$config = $app['config'];

return new SwaggerUiProvider(
decorated: $app->make(ReadProvider::class),
decorated: $app->make(RangeHeaderProvider::class),
openApiFactory: $app->make(OpenApiFactoryInterface::class),
swaggerUiEnabled: $config->get('api-platform.swagger_ui.enabled', false),
scalarEnabled: $config->get('api-platform.scalar.enabled', false),
Expand Down
1 change: 1 addition & 0 deletions src/Metadata/Extractor/XmlResourceExtractor.php
Original file line number Diff line number Diff line change
Expand Up @@ -429,6 +429,7 @@ private function buildOperations(\SimpleXMLElement $resource, array $root): ?arr
'queryParameterValidate' => $this->phpize($operation, 'queryParameterValidate', 'bool'),
'priority' => $this->phpize($operation, 'priority', 'integer'),
'routePriority' => $this->phpize($operation, 'routePriority', 'integer'),
'rangeUnit' => $this->phpize($operation, 'rangeUnit', 'string'),
'name' => $this->phpize($operation, 'name', 'string'),
'routeName' => $this->phpize($operation, 'routeName', 'string'),
]);
Expand Down
1 change: 1 addition & 0 deletions src/Metadata/Extractor/YamlResourceExtractor.php
Original file line number Diff line number Diff line change
Expand Up @@ -366,6 +366,7 @@ private function buildOperations(array $resource, array $root): ?array
'hideHydraOperation' => $this->phpize($resource, 'hideHydraOperation', 'bool'),
'priority' => $this->phpize($operation, 'priority', 'integer'),
'routePriority' => $this->phpize($operation, 'routePriority', 'integer'),
'rangeUnit' => $this->phpize($operation, 'rangeUnit', 'string'),
'name' => $this->phpize($operation, 'name', 'string'),
'class' => (string) $class,
]);
Expand Down
1 change: 1 addition & 0 deletions src/Metadata/Extractor/schema/resources.xsd
Original file line number Diff line number Diff line change
Expand Up @@ -47,6 +47,7 @@
<xsd:attribute type="xsd:boolean" name="openapi"/>
<xsd:attribute type="xsd:positiveInteger" name="priority"/>
<xsd:attribute type="xsd:integer" name="routePriority"/>
<xsd:attribute type="xsd:string" name="rangeUnit"/>
<xsd:attribute type="xsd:string" name="name"/>
<xsd:attribute type="xsd:string" name="itemUriTemplate"/>
<xsd:attribute type="xsd:string" name="routeName"/>
Expand Down
4 changes: 3 additions & 1 deletion src/Metadata/GetCollection.php
Original file line number Diff line number Diff line change
Expand Up @@ -107,6 +107,7 @@ public function __construct(
?bool $throwOnNotFound = null,
private ?string $itemUriTemplate = null,
?bool $map = null,
?string $rangeUnit = null,
) {
parent::__construct(
uriTemplate: $uriTemplate,
Expand Down Expand Up @@ -192,7 +193,8 @@ class: $class,
strictQueryParameterValidation: $strictQueryParameterValidation,
hideHydraOperation: $hideHydraOperation,
stateOptions: $stateOptions,
map: $map
map: $map,
rangeUnit: $rangeUnit
);
}

Expand Down
14 changes: 14 additions & 0 deletions src/Metadata/HttpOperation.php
Original file line number Diff line number Diff line change
Expand Up @@ -226,6 +226,7 @@ public function __construct(
?bool $throwOnNotFound = null,
array $extraProperties = [],
?bool $map = null,
protected ?string $rangeUnit = null,
) {
$this->formats = (null === $formats || \is_array($formats)) ? $formats : [$formats];
$this->inputFormats = (null === $inputFormats || \is_array($inputFormats)) ? $inputFormats : [$inputFormats];
Expand Down Expand Up @@ -517,6 +518,19 @@ public function withAcceptPatch(string $acceptPatch): static
return $self;
}

public function getRangeUnit(): ?string
{
return $this->rangeUnit;
}

public function withRangeUnit(?string $rangeUnit): static
{
$self = clone $this;
$self->rangeUnit = $rangeUnit;

return $self;
}

public function getStatus(): ?int
{
return $this->status;
Expand Down
2 changes: 2 additions & 0 deletions src/Metadata/Tests/Extractor/XmlExtractorTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -280,6 +280,7 @@ public function testValidXML(): void
'method' => null,
'priority' => null,
'routePriority' => null,
'rangeUnit' => null,
'processor' => null,
'provider' => null,
'itemUriTemplate' => null,
Expand Down Expand Up @@ -390,6 +391,7 @@ public function testValidXML(): void
'method' => null,
'priority' => null,
'routePriority' => null,
'rangeUnit' => null,
'processor' => null,
'provider' => null,
'stateOptions' => null,
Expand Down
2 changes: 2 additions & 0 deletions src/Metadata/Tests/Extractor/YamlExtractorTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -321,6 +321,7 @@ public function testValidYaml(): void
'queryParameterValidate' => null,
'priority' => null,
'routePriority' => null,
'rangeUnit' => null,
'processor' => null,
'provider' => null,
'itemUriTemplate' => null,
Expand Down Expand Up @@ -413,6 +414,7 @@ public function testValidYaml(): void
'queryParameterValidate' => null,
'priority' => null,
'routePriority' => null,
'rangeUnit' => null,
'processor' => null,
'provider' => null,
'stateOptions' => null,
Expand Down
128 changes: 128 additions & 0 deletions src/State/Provider/RangeHeaderProvider.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,128 @@
<?php

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

declare(strict_types=1);

namespace ApiPlatform\State\Provider;

use ApiPlatform\Metadata\CollectionOperationInterface;
use ApiPlatform\Metadata\HttpOperation;
use ApiPlatform\Metadata\Operation;
use ApiPlatform\State\Pagination\Pagination;
use ApiPlatform\State\Pagination\PaginatorInterface;
use ApiPlatform\State\Pagination\PartialPaginatorInterface;
use ApiPlatform\State\ProviderInterface;
use ApiPlatform\State\Util\RequestParser;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpKernel\Exception\HttpException;

/**
* Serves paginated collections as HTTP range requests (RFC 9110 §14), opt-in per operation
* through {@see HttpOperation::getRangeUnit()}.
*
* A range applies to a would-be 200 only (§14.2): it is ignored on other methods, other
* units, unparseable specifiers and whenever the request fails before reading. Choices the
* RFC leaves open: If-Range counts as a mismatch, collections carrying no validator
* (§13.1.5); the 206 is promised only once a paginator came back, every 206 having to
* carry a Content-Range (§15.3.7); a range pagination cannot serve as a page (misaligned,
* wider than the maximum) gets a 416 rather than being silently ignored, so that clients
* learn it.
*
* @see https://datatracker.ietf.org/doc/html/rfc9110#section-14
*
* @author Julien Robic <nayte91@gmail.com>
*/
final class RangeHeaderProvider implements ProviderInterface
{
/** Int-range "<first>-<last>" only (§14.1.2): pagination can serve neither an open-ended nor a suffix range. */
private const RANGE_PATTERN = '/^(?<unit>[A-Za-z0-9!#$%&\'*+\-.^_`|~]+)=(?<first>\d+)-(?<last>\d+)$/';

public function __construct(
private readonly ProviderInterface $decorated,
private readonly Pagination $pagination,
) {
}

public function provide(Operation $operation, array $uriVariables = [], array $context = []): object|array|null
{
$request = $context['request'] ?? null;

if (
!$request instanceof Request
|| !$operation instanceof HttpOperation
|| !$operation instanceof CollectionOperationInterface
|| null === ($unit = $operation->getRangeUnit())
|| !$request->isMethod('GET')
|| !$request->headers->has('Range')
|| $request->headers->has('If-Range')
|| !\in_array($operation->getStatus(), [null, Response::HTTP_OK], true)
|| !preg_match(self::RANGE_PATTERN, $request->headers->get('Range', ''), $range)
|| strtolower($range['unit']) !== strtolower($unit)
) {
return $this->decorated->provide($operation, $uriVariables, $context);
}

$first = (int) $range['first'];
$last = (int) $range['last'];

if ($first > $last) {
throw new HttpException(Response::HTTP_REQUESTED_RANGE_NOT_SATISFIABLE, \sprintf('The range first position (%d) must not exceed its last position (%d).', $first, $last));
}

$length = $last - $first + 1;
$maximumItemsPerPage = $operation->getPaginationMaximumItemsPerPage() ?? $this->pagination->getOptions()['maximum_items_per_page'];

if (null !== $maximumItemsPerPage && $length > $maximumItemsPerPage) {
throw new HttpException(Response::HTTP_REQUESTED_RANGE_NOT_SATISFIABLE, \sprintf('A range must not span more than %d %s.', $maximumItemsPerPage, $unit));
}

if (0 !== $first % $length) {
throw new HttpException(Response::HTTP_REQUESTED_RANGE_NOT_SATISFIABLE, \sprintf('The range first position must be a multiple of its length (%d).', $length));
}

$options = $this->pagination->getOptions();
$filters = $request->attributes->get('_api_filters');
if (null === $filters) {
$queryString = RequestParser::getQueryString($request);
$filters = $queryString ? RequestParser::parseRequestParams($queryString) : [];
}

// Pagination::getLimit() ignores the items-per-page filter unless the client may choose it:
// set the operation too, so that the range wins over the query string.
$filters[$options['page_parameter_name']] = intdiv($first, $length) + 1;
$filters[$options['items_per_page_parameter_name']] = $length;
$request->attributes->set('_api_filters', $filters);

$operation = $operation->withPaginationItemsPerPage($length);
$request->attributes->set('_api_operation', $operation);

$data = $this->decorated->provide($operation, $uriVariables, $context);

if (!$data instanceof PartialPaginatorInterface) {
return $data;
}

if ($data instanceof PaginatorInterface) {
$totalItems = (int) $data->getTotalItems();

if ($first >= $totalItems) {
throw new HttpException(Response::HTTP_REQUESTED_RANGE_NOT_SATISFIABLE, \sprintf('The range first position (%d) is beyond the collection (%d %s).', $first, $totalItems, $unit), null, ['Content-Range' => \sprintf('%s */%d', $unit, $totalItems)]);
}
} elseif (0 === \count($data)) {
throw new HttpException(Response::HTTP_REQUESTED_RANGE_NOT_SATISFIABLE, \sprintf('The range first position (%d) is beyond the collection.', $first));
}

$request->attributes->set('_api_operation', $operation->withStatus(Response::HTTP_PARTIAL_CONTENT));

return $data;
}
}
28 changes: 28 additions & 0 deletions src/State/Util/HttpResponseHeadersTrait.php
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@

namespace ApiPlatform\State\Util;

use ApiPlatform\Metadata\CollectionOperationInterface;
use ApiPlatform\Metadata\Error;
use ApiPlatform\Metadata\Exception\HttpExceptionInterface;
use ApiPlatform\Metadata\Exception\InvalidArgumentException;
Expand All @@ -26,6 +27,8 @@
use ApiPlatform\Metadata\UrlGeneratorInterface;
use ApiPlatform\Metadata\Util\ClassInfoTrait;
use ApiPlatform\Metadata\Util\CloneTrait;
use ApiPlatform\State\Pagination\PaginatorInterface;
use ApiPlatform\State\Pagination\PartialPaginatorInterface;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpKernel\Exception\HttpExceptionInterface as SymfonyHttpExceptionInterface;
Expand Down Expand Up @@ -145,9 +148,34 @@ private function getHeaders(Request $request, HttpOperation $operation, array $c
$this->addLinkedDataPlatformHeaders($headers, $operation);
}

if (
$operation instanceof CollectionOperationInterface
&& null !== ($rangeUnit = $operation->getRangeUnit())
&& \in_array($status, [Response::HTTP_OK, Response::HTTP_PARTIAL_CONTENT], true)
) {
$headers['Accept-Ranges'] = $rangeUnit;

if (Response::HTTP_PARTIAL_CONTENT === $status && $originalData instanceof PartialPaginatorInterface && $contentRange = $this->getContentRange($rangeUnit, $originalData)) {
$headers['Content-Range'] = $contentRange;
}
}

return $headers;
}

private function getContentRange(string $unit, PartialPaginatorInterface $paginator): ?string
{
$count = \count($paginator);
if (0 === $count) {
return null;
}

$first = (int) (($paginator->getCurrentPage() - 1) * $paginator->getItemsPerPage());
$completeLength = $paginator instanceof PaginatorInterface ? (string) (int) $paginator->getTotalItems() : '*';

return \sprintf('%s %d-%d/%s', $unit, $first, $first + $count - 1, $completeLength);
}

private function addLinkedDataPlatformHeaders(array &$headers, HttpOperation $operation): void
{
if (!$this->resourceMetadataCollectionFactory) {
Expand Down
8 changes: 8 additions & 0 deletions src/Symfony/Bundle/Resources/config/state/provider.php
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@
use ApiPlatform\State\Provider\ContentNegotiationProvider;
use ApiPlatform\State\Provider\DeserializeProvider;
use ApiPlatform\State\Provider\ParameterProvider;
use ApiPlatform\State\Provider\RangeHeaderProvider;
use ApiPlatform\State\Provider\ReadProvider;
use ApiPlatform\Symfony\EventListener\ErrorListener;
use ApiPlatform\Validator\DenormalizationViolationFactory;
Expand Down Expand Up @@ -50,6 +51,13 @@

$services->alias(DenormalizationViolationFactoryInterface::class, 'api_platform.state.denormalization_violation_factory');

$services->set('api_platform.state_provider.range_header', RangeHeaderProvider::class)

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This enables the behavior globally. There is no framework setting or resource/operation metadata flag, so applications cannot opt in selectively and existing APIs gain new headers/Range semantics automatically. Given the provider and representation constraints, this should default to disabled and be enabled explicitly per operation (with an explicit range unit). Event-listener mode also does not wire this provider, while it still receives the response-trait changes.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Fixed in 89356d2. The feature is opt-in per operation: without a rangeUnit the Range header is ignored and no Accept-Ranges is emitted (testARangeIsIgnoredWithoutARangeUnit, on a second fixture operation left unconfigured). There is deliberately no global framework setting, since the unit has to be chosen per collection anyway.

The provider is now wired in the event-listener mode as well (symfony/events.php), at the same innermost priority, and the functional test runs green under USE_SYMFONY_LISTENERS=1. It is also registered in the Laravel service provider, directly around ReadProvider, which matches the Symfony position; that part is not covered by a Laravel test yet.

->decorate('api_platform.state_provider.read', null, 120)
->args([
service('api_platform.state_provider.range_header.inner'),
service('api_platform.pagination'),
]);

$services->set('api_platform.state_provider.deserialize', DeserializeProvider::class)
->decorate('api_platform.state_provider.main', null, 300)
->args([
Expand Down
8 changes: 8 additions & 0 deletions src/Symfony/Bundle/Resources/config/symfony/events.php
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,7 @@
use ApiPlatform\State\Provider\ContentNegotiationProvider;
use ApiPlatform\State\Provider\DeserializeProvider;
use ApiPlatform\State\Provider\ParameterProvider;
use ApiPlatform\State\Provider\RangeHeaderProvider;
use ApiPlatform\State\Provider\ReadProvider;
use ApiPlatform\Symfony\Action\DocumentationAction;
use ApiPlatform\Symfony\Action\EntrypointAction;
Expand Down Expand Up @@ -57,6 +58,13 @@
->arg(1, service('api_platform.serializer.context_builder'))
->arg('$logger', service('logger')->nullOnInvalid());

$services->set('api_platform.state_provider.range_header', RangeHeaderProvider::class)
->decorate('api_platform.state_provider.read', null, 120)
->args([
service('api_platform.state_provider.range_header.inner'),
service('api_platform.pagination'),
]);

// Outermost decorator of the read chain (access checkers sit at 0) so parameters are
// resolved, and their values propagated to the uriVariables, before anything reads them.
$services->set('api_platform.state_provider.parameter', ParameterProvider::class)
Expand Down
Loading