• Home
  • Features
  • Pricing
  • Docs
  • Announcements
  • Sign In

api-platform / core / 10729306835

05 Sep 2024 10:46PM UTC coverage: 7.655% (-0.01%) from 7.665%
10729306835

push

github

web-flow
Merge pull request #6586 from soyuka/merge-342

Merge 3.4

0 of 54 new or added lines in 12 files covered. (0.0%)

8760 existing lines in 277 files now uncovered.

12505 of 163357 relevant lines covered (7.66%)

22.84 hits per line

Source File
Press 'n' to go to next uncovered line, 'b' for previous

96.77
/src/Hydra/Serializer/PartialCollectionViewNormalizer.php
1
<?php
2

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

12
declare(strict_types=1);
13

14
namespace ApiPlatform\Hydra\Serializer;
15

16
use ApiPlatform\Metadata\HttpOperation;
17
use ApiPlatform\Metadata\Resource\Factory\ResourceMetadataCollectionFactoryInterface;
18
use ApiPlatform\Metadata\UrlGeneratorInterface;
19
use ApiPlatform\Metadata\Util\IriHelper;
20
use ApiPlatform\State\Pagination\PaginatorInterface;
21
use ApiPlatform\State\Pagination\PartialPaginatorInterface;
22
use Symfony\Component\PropertyAccess\PropertyAccess;
23
use Symfony\Component\PropertyAccess\PropertyAccessorInterface;
24
use Symfony\Component\Serializer\Exception\UnexpectedValueException;
25
use Symfony\Component\Serializer\Normalizer\NormalizerAwareInterface;
26
use Symfony\Component\Serializer\Normalizer\NormalizerInterface;
27

28
/**
29
 * Adds a view key to the result of a paginated Hydra collection.
30
 *
31
 * @author Kévin Dunglas <dunglas@gmail.com>
32
 * @author Samuel ROZE <samuel.roze@gmail.com>
33
 */
34
final class PartialCollectionViewNormalizer implements NormalizerInterface, NormalizerAwareInterface
35
{
36
    private readonly PropertyAccessorInterface $propertyAccessor;
37

38
    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)
39
    {
UNCOV
40
        $this->propertyAccessor = $propertyAccessor ?? PropertyAccess::createPropertyAccessor();
2,255✔
41
    }
42

43
    /**
44
     * {@inheritdoc}
45
     */
46
    public function normalize(mixed $object, ?string $format = null, array $context = []): array|string|int|float|bool|\ArrayObject|null
47
    {
UNCOV
48
        $data = $this->collectionNormalizer->normalize($object, $format, $context);
938✔
49

UNCOV
50
        if (isset($context['api_sub_level'])) {
938✔
UNCOV
51
            return $data;
653✔
52
        }
53

UNCOV
54
        if (!\is_array($data)) {
548✔
55
            throw new UnexpectedValueException('Expected data to be an array');
×
56
        }
57

UNCOV
58
        $currentPage = $lastPage = $itemsPerPage = $pageTotalItems = null;
548✔
UNCOV
59
        if ($paginated = ($object instanceof PartialPaginatorInterface)) {
548✔
UNCOV
60
            if ($object instanceof PaginatorInterface) {
498✔
UNCOV
61
                $paginated = 1. !== $lastPage = $object->getLastPage();
494✔
62
            } else {
63
                $itemsPerPage = $object->getItemsPerPage();
4✔
64
                $pageTotalItems = (float) \count($object);
4✔
65
            }
66

UNCOV
67
            $currentPage = $object->getCurrentPage();
498✔
68
        }
69

70
        // TODO: This needs to be changed as well as I wrote in the CollectionFiltersNormalizer
71
        // We should not rely on the request_uri but instead rely on the UriTemplate
72
        // This needs that we implement the RFC and that we do more parsing before calling the serialization (MainController)
UNCOV
73
        $parsed = IriHelper::parseIri($context['uri'] ?? $context['request_uri'] ?? '/', $this->pageParameterName);
548✔
UNCOV
74
        $appliedFilters = $parsed['parameters'];
548✔
UNCOV
75
        unset($appliedFilters[$this->enabledParameterName]);
548✔
76

UNCOV
77
        if (!$appliedFilters && !$paginated) {
548✔
UNCOV
78
            return $data;
206✔
79
        }
80

UNCOV
81
        $isPaginatedWithCursor = false;
342✔
UNCOV
82
        $cursorPaginationAttribute = null;
342✔
UNCOV
83
        $operation = $context['operation'] ?? null;
342✔
UNCOV
84
        if (!$operation && $this->resourceMetadataFactory && isset($context['resource_class']) && $paginated) {
342✔
85
            $operation = $this->resourceMetadataFactory->create($context['resource_class'])->getOperation($context['operation_name'] ?? null);
×
86
        }
87

UNCOV
88
        $cursorPaginationAttribute = $operation instanceof HttpOperation ? $operation->getPaginationViaCursor() : null;
342✔
UNCOV
89
        $isPaginatedWithCursor = (bool) $cursorPaginationAttribute;
342✔
90

UNCOV
91
        $data['hydra:view'] = ['@id' => null, '@type' => 'hydra:PartialCollectionView'];
342✔
92

UNCOV
93
        if ($isPaginatedWithCursor) {
342✔
UNCOV
94
            return $this->populateDataWithCursorBasedPagination($data, $parsed, $object, $cursorPaginationAttribute, $operation?->getUrlGenerationStrategy() ?? $this->urlGenerationStrategy);
7✔
95
        }
96

UNCOV
97
        $data['hydra:view']['@id'] = IriHelper::createIri($parsed['parts'], $parsed['parameters'], $this->pageParameterName, $paginated ? $currentPage : null, $operation?->getUrlGenerationStrategy() ?? $this->urlGenerationStrategy);
335✔
98

UNCOV
99
        if ($paginated) {
335✔
UNCOV
100
            return $this->populateDataWithPagination($data, $parsed, $currentPage, $lastPage, $itemsPerPage, $pageTotalItems, $operation?->getUrlGenerationStrategy() ?? $this->urlGenerationStrategy);
200✔
101
        }
102

UNCOV
103
        return $data;
141✔
104
    }
105

106
    /**
107
     * {@inheritdoc}
108
     */
109
    public function supportsNormalization(mixed $data, ?string $format = null, array $context = []): bool
110
    {
UNCOV
111
        return $this->collectionNormalizer->supportsNormalization($data, $format, $context);
938✔
112
    }
113

114
    public function getSupportedTypes($format): array
115
    {
UNCOV
116
        return $this->collectionNormalizer->getSupportedTypes($format);
2,012✔
117
    }
118

119
    /**
120
     * {@inheritdoc}
121
     */
122
    public function setNormalizer(NormalizerInterface $normalizer): void
123
    {
UNCOV
124
        if ($this->collectionNormalizer instanceof NormalizerAwareInterface) {
2,255✔
UNCOV
125
            $this->collectionNormalizer->setNormalizer($normalizer);
2,255✔
126
        }
127
    }
128

129
    private function cursorPaginationFields(array $fields, int $direction, $object): array
130
    {
UNCOV
131
        $paginationFilters = [];
3✔
132

UNCOV
133
        foreach ($fields as $field) {
3✔
UNCOV
134
            $forwardRangeOperator = 'desc' === strtolower($field['direction']) ? 'lt' : 'gt';
3✔
UNCOV
135
            $backwardRangeOperator = 'gt' === $forwardRangeOperator ? 'lt' : 'gt';
3✔
136

UNCOV
137
            $operator = $direction > 0 ? $forwardRangeOperator : $backwardRangeOperator;
3✔
138

UNCOV
139
            $paginationFilters[$field['field']] = [
3✔
UNCOV
140
                $operator => (string) $this->propertyAccessor->getValue($object, $field['field']),
3✔
UNCOV
141
            ];
3✔
142
        }
143

UNCOV
144
        return $paginationFilters;
3✔
145
    }
146

147
    private function populateDataWithCursorBasedPagination(array $data, array $parsed, \Traversable $object, ?array $cursorPaginationAttribute, ?int $urlGenerationStrategy): array
148
    {
UNCOV
149
        $objects = iterator_to_array($object);
7✔
UNCOV
150
        $firstObject = current($objects);
7✔
UNCOV
151
        $lastObject = end($objects);
7✔
152

UNCOV
153
        $data['hydra:view']['@id'] = IriHelper::createIri($parsed['parts'], $parsed['parameters'], urlGenerationStrategy: $urlGenerationStrategy);
7✔
154

UNCOV
155
        if (false !== $lastObject && \is_array($cursorPaginationAttribute)) {
7✔
UNCOV
156
            $data['hydra:view']['hydra:next'] = IriHelper::createIri($parsed['parts'], array_merge($parsed['parameters'], $this->cursorPaginationFields($cursorPaginationAttribute, 1, $lastObject)), urlGenerationStrategy: $urlGenerationStrategy);
3✔
157
        }
158

UNCOV
159
        if (false !== $firstObject && \is_array($cursorPaginationAttribute)) {
7✔
UNCOV
160
            $data['hydra:view']['hydra:previous'] = IriHelper::createIri($parsed['parts'], array_merge($parsed['parameters'], $this->cursorPaginationFields($cursorPaginationAttribute, -1, $firstObject)), urlGenerationStrategy: $urlGenerationStrategy);
3✔
161
        }
162

UNCOV
163
        return $data;
7✔
164
    }
165

166
    private function populateDataWithPagination(array $data, array $parsed, ?float $currentPage, ?float $lastPage, ?float $itemsPerPage, ?float $pageTotalItems, ?int $urlGenerationStrategy): array
167
    {
UNCOV
168
        if (null !== $lastPage) {
200✔
UNCOV
169
            $data['hydra:view']['hydra:first'] = IriHelper::createIri($parsed['parts'], $parsed['parameters'], $this->pageParameterName, 1., $urlGenerationStrategy);
199✔
UNCOV
170
            $data['hydra:view']['hydra:last'] = IriHelper::createIri($parsed['parts'], $parsed['parameters'], $this->pageParameterName, $lastPage, $urlGenerationStrategy);
199✔
171
        }
172

UNCOV
173
        if (1. !== $currentPage) {
200✔
UNCOV
174
            $data['hydra:view']['hydra:previous'] = IriHelper::createIri($parsed['parts'], $parsed['parameters'], $this->pageParameterName, $currentPage - 1., $urlGenerationStrategy);
17✔
175
        }
176

UNCOV
177
        if ((null !== $lastPage && $currentPage < $lastPage) || (null === $lastPage && $pageTotalItems >= $itemsPerPage)) {
200✔
UNCOV
178
            $data['hydra:view']['hydra:next'] = IriHelper::createIri($parsed['parts'], $parsed['parameters'], $this->pageParameterName, $currentPage + 1., $urlGenerationStrategy);
197✔
179
        }
180

UNCOV
181
        return $data;
200✔
182
    }
183
}
STATUS · Troubleshooting · Open an Issue · Sales · Support · CAREERS · ENTERPRISE · START FREE · SCHEDULE DEMO
ANNOUNCEMENTS · TWITTER · TOS & SLA · Supported CI Services · What's a CI service? · Automated Testing

© 2025 Coveralls, Inc