-
-
Notifications
You must be signed in to change notification settings - Fork 901
/
Copy pathPartialCollectionViewNormalizer.php
207 lines (167 loc) · 9.54 KB
/
PartialCollectionViewNormalizer.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
<?php
/*
* This file is part of the API Platform project.
*
* (c) Kévin Dunglas <[email protected]>
*
* 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\Hydra\Serializer;
use ApiPlatform\Metadata\HttpOperation;
use ApiPlatform\Metadata\Resource\Factory\ResourceMetadataCollectionFactoryInterface;
use ApiPlatform\Metadata\UrlGeneratorInterface;
use ApiPlatform\Serializer\CacheableSupportsMethodInterface;
use ApiPlatform\State\Pagination\PaginatorInterface;
use ApiPlatform\State\Pagination\PartialPaginatorInterface;
use ApiPlatform\Util\IriHelper;
use Symfony\Component\PropertyAccess\PropertyAccess;
use Symfony\Component\PropertyAccess\PropertyAccessorInterface;
use Symfony\Component\Serializer\Exception\UnexpectedValueException;
use Symfony\Component\Serializer\Normalizer\CacheableSupportsMethodInterface as BaseCacheableSupportsMethodInterface;
use Symfony\Component\Serializer\Normalizer\NormalizerAwareInterface;
use Symfony\Component\Serializer\Normalizer\NormalizerInterface;
use Symfony\Component\Serializer\Serializer;
/**
* Adds a view key to the result of a paginated Hydra collection.
*
* @author Kévin Dunglas <[email protected]>
* @author Samuel ROZE <[email protected]>
*/
final class PartialCollectionViewNormalizer implements NormalizerInterface, NormalizerAwareInterface, CacheableSupportsMethodInterface
{
private readonly PropertyAccessorInterface $propertyAccessor;
public function __construct(private readonly NormalizerInterface $collectionNormalizer, private readonly string $pageParameterName = 'page', private string $enabledParameterName = 'pagination', private readonly ?ResourceMetadataCollectionFactoryInterface $resourceMetadataFactory = null, ?PropertyAccessorInterface $propertyAccessor = null, private readonly int $urlGenerationStrategy = UrlGeneratorInterface::ABS_PATH)
{
$this->propertyAccessor = $propertyAccessor ?? PropertyAccess::createPropertyAccessor();
}
/**
* {@inheritdoc}
*/
public function normalize(mixed $object, ?string $format = null, array $context = []): array|string|int|float|bool|\ArrayObject|null
{
$data = $this->collectionNormalizer->normalize($object, $format, $context);
if (isset($context['api_sub_level'])) {
return $data;
}
if (!\is_array($data)) {
throw new UnexpectedValueException('Expected data to be an array');
}
$currentPage = $lastPage = $itemsPerPage = $pageTotalItems = null;
if ($paginated = ($object instanceof PartialPaginatorInterface)) {
if ($object instanceof PaginatorInterface) {
$paginated = 1. !== $lastPage = $object->getLastPage();
} else {
$itemsPerPage = $object->getItemsPerPage();
$pageTotalItems = (float) \count($object);
}
$currentPage = $object->getCurrentPage();
}
// TODO: This needs to be changed as well as I wrote in the CollectionFiltersNormalizer
// We should not rely on the request_uri but instead rely on the UriTemplate
// This needs that we implement the RFC and that we do more parsing before calling the serialization (MainController)
$parsed = IriHelper::parseIri($context['uri'] ?? $context['request_uri'] ?? '/', $this->pageParameterName);
$appliedFilters = $parsed['parameters'];
unset($appliedFilters[$this->enabledParameterName]);
if (!$appliedFilters && !$paginated) {
return $data;
}
$isPaginatedWithCursor = false;
$cursorPaginationAttribute = null;
$operation = $context['operation'] ?? null;
if (!$operation && $this->resourceMetadataFactory && isset($context['resource_class']) && $paginated) {
$operation = $this->resourceMetadataFactory->create($context['resource_class'])->getOperation($context['operation_name'] ?? null);
}
$cursorPaginationAttribute = $operation instanceof HttpOperation ? $operation->getPaginationViaCursor() : null;
$isPaginatedWithCursor = (bool) $cursorPaginationAttribute;
$data['hydra:view'] = ['@id' => null, '@type' => 'hydra:PartialCollectionView'];
if ($isPaginatedWithCursor) {
return $this->populateDataWithCursorBasedPagination($data, $parsed, $object, $cursorPaginationAttribute, $operation?->getUrlGenerationStrategy() ?? $this->urlGenerationStrategy, $itemsPerPage, $pageTotalItems);
}
$data['hydra:view']['@id'] = IriHelper::createIri($parsed['parts'], $parsed['parameters'], $this->pageParameterName, $paginated ? $currentPage : null, $operation?->getUrlGenerationStrategy() ?? $this->urlGenerationStrategy);
if ($paginated) {
return $this->populateDataWithPagination($data, $parsed, $currentPage, $lastPage, $itemsPerPage, $pageTotalItems, $operation?->getUrlGenerationStrategy() ?? $this->urlGenerationStrategy);
}
return $data;
}
/**
* {@inheritdoc}
*/
public function supportsNormalization(mixed $data, ?string $format = null, array $context = []): bool
{
return $this->collectionNormalizer->supportsNormalization($data, $format, $context);
}
public function getSupportedTypes($format): array
{
// @deprecated remove condition when support for symfony versions under 6.3 is dropped
if (!method_exists($this->collectionNormalizer, 'getSupportedTypes')) {
return [
'*' => $this->collectionNormalizer instanceof BaseCacheableSupportsMethodInterface && $this->collectionNormalizer->hasCacheableSupportsMethod(),
];
}
return $this->collectionNormalizer->getSupportedTypes($format);
}
public function hasCacheableSupportsMethod(): bool
{
if (method_exists(Serializer::class, 'getSupportedTypes')) {
trigger_deprecation(
'api-platform/core',
'3.1',
'The "%s()" method is deprecated, use "getSupportedTypes()" instead.',
__METHOD__
);
}
return $this->collectionNormalizer instanceof BaseCacheableSupportsMethodInterface && $this->collectionNormalizer->hasCacheableSupportsMethod();
}
/**
* {@inheritdoc}
*/
public function setNormalizer(NormalizerInterface $normalizer): void
{
if ($this->collectionNormalizer instanceof NormalizerAwareInterface) {
$this->collectionNormalizer->setNormalizer($normalizer);
}
}
private function cursorPaginationFields(array $fields, int $direction, $object): array
{
$paginationFilters = [];
foreach ($fields as $field) {
$forwardRangeOperator = 'desc' === strtolower($field['direction']) ? 'lt' : 'gt';
$backwardRangeOperator = 'gt' === $forwardRangeOperator ? 'lt' : 'gt';
$operator = $direction > 0 ? $forwardRangeOperator : $backwardRangeOperator;
$paginationFilters[$field['field']] = [
$operator => (string) $this->propertyAccessor->getValue($object, $field['field']),
];
}
return $paginationFilters;
}
private function populateDataWithCursorBasedPagination(array $data, array $parsed, \Traversable $object, ?array $cursorPaginationAttribute, ?int $urlGenerationStrategy, ?float $itemsPerPage, ?float $pageTotalItems): array
{
$objects = iterator_to_array($object);
$firstObject = current($objects);
$lastObject = end($objects);
$data['hydra:view']['@id'] = IriHelper::createIri($parsed['parts'], $parsed['parameters'], urlGenerationStrategy: $urlGenerationStrategy);
if (false !== $lastObject && \is_array($cursorPaginationAttribute) && $pageTotalItems >= $itemsPerPage) {
$data['hydra:view']['hydra:next'] = IriHelper::createIri($parsed['parts'], array_merge($parsed['parameters'], $this->cursorPaginationFields($cursorPaginationAttribute, 1, $lastObject)), urlGenerationStrategy: $urlGenerationStrategy);
}
if (false !== $firstObject && \is_array($cursorPaginationAttribute)) {
$data['hydra:view']['hydra:previous'] = IriHelper::createIri($parsed['parts'], array_merge($parsed['parameters'], $this->cursorPaginationFields($cursorPaginationAttribute, -1, $firstObject)), urlGenerationStrategy: $urlGenerationStrategy);
}
return $data;
}
private function populateDataWithPagination(array $data, array $parsed, ?float $currentPage, ?float $lastPage, ?float $itemsPerPage, ?float $pageTotalItems, ?int $urlGenerationStrategy): array
{
if (null !== $lastPage) {
$data['hydra:view']['hydra:first'] = IriHelper::createIri($parsed['parts'], $parsed['parameters'], $this->pageParameterName, 1., $urlGenerationStrategy);
$data['hydra:view']['hydra:last'] = IriHelper::createIri($parsed['parts'], $parsed['parameters'], $this->pageParameterName, $lastPage, $urlGenerationStrategy);
}
if (1. !== $currentPage) {
$data['hydra:view']['hydra:previous'] = IriHelper::createIri($parsed['parts'], $parsed['parameters'], $this->pageParameterName, $currentPage - 1., $urlGenerationStrategy);
}
if ((null !== $lastPage && $currentPage < $lastPage) || (null === $lastPage && $pageTotalItems >= $itemsPerPage)) {
$data['hydra:view']['hydra:next'] = IriHelper::createIri($parsed['parts'], $parsed['parameters'], $this->pageParameterName, $currentPage + 1., $urlGenerationStrategy);
}
return $data;
}
}