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

api-platform / core / 14008635868

22 Mar 2025 12:39PM UTC coverage: 8.52% (+0.005%) from 8.515%
14008635868

Pull #7042

github

web-flow
Merge fdd88ef56 into 47a6dffbb
Pull Request #7042: Purge parent collections in inheritance cases

4 of 9 new or added lines in 1 file covered. (44.44%)

540 existing lines in 57 files now uncovered.

13394 of 157210 relevant lines covered (8.52%)

22.93 hits per line

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

96.83
/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\JsonLd\Serializer\HydraPrefixTrait;
17
use ApiPlatform\Metadata\HttpOperation;
18
use ApiPlatform\Metadata\Resource\Factory\ResourceMetadataCollectionFactoryInterface;
19
use ApiPlatform\Metadata\UrlGeneratorInterface;
20
use ApiPlatform\Metadata\Util\IriHelper;
21
use ApiPlatform\State\Pagination\PaginatorInterface;
22
use ApiPlatform\State\Pagination\PartialPaginatorInterface;
23
use Symfony\Component\PropertyAccess\PropertyAccess;
24
use Symfony\Component\PropertyAccess\PropertyAccessorInterface;
25
use Symfony\Component\Serializer\Exception\UnexpectedValueException;
26
use Symfony\Component\Serializer\Normalizer\NormalizerAwareInterface;
27
use Symfony\Component\Serializer\Normalizer\NormalizerInterface;
28

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

40
    /**
41
     * @param array<string, mixed> $defaultContext
42
     */
43
    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, private readonly array $defaultContext = [])
44
    {
45
        $this->propertyAccessor = $propertyAccessor ?? PropertyAccess::createPropertyAccessor();
2,008✔
46
    }
47

48
    /**
49
     * {@inheritdoc}
50
     */
51
    public function normalize(mixed $object, ?string $format = null, array $context = []): array|string|int|float|bool|\ArrayObject|null
52
    {
53
        $data = $this->collectionNormalizer->normalize($object, $format, $context);
910✔
54

55
        if (isset($context['api_sub_level'])) {
910✔
56
            return $data;
500✔
57
        }
58

59
        if (!\is_array($data)) {
592✔
60
            throw new UnexpectedValueException('Expected data to be an array');
×
61
        }
62

63
        $currentPage = $lastPage = $itemsPerPage = $pageTotalItems = null;
592✔
64
        if ($paginated = ($object instanceof PartialPaginatorInterface)) {
592✔
65
            if ($object instanceof PaginatorInterface) {
529✔
66
                $paginated = 1. !== $lastPage = $object->getLastPage();
525✔
67
            } else {
UNCOV
68
                $itemsPerPage = $object->getItemsPerPage();
4✔
UNCOV
69
                $pageTotalItems = (float) \count($object);
4✔
70
            }
71

72
            $currentPage = $object->getCurrentPage();
529✔
73
        }
74

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

82
        if (!$appliedFilters && !$paginated) {
592✔
83
            return $data;
174✔
84
        }
85

86
        $isPaginatedWithCursor = false;
418✔
87
        $cursorPaginationAttribute = null;
418✔
88
        $operation = $context['operation'] ?? null;
418✔
89
        if (!$operation && $this->resourceMetadataFactory && isset($context['resource_class']) && $paginated) {
418✔
90
            $operation = $this->resourceMetadataFactory->create($context['resource_class'])->getOperation($context['operation_name'] ?? null);
×
91
        }
92

93
        $cursorPaginationAttribute = $operation instanceof HttpOperation ? $operation->getPaginationViaCursor() : null;
418✔
94
        $isPaginatedWithCursor = (bool) $cursorPaginationAttribute;
418✔
95

96
        $hydraPrefix = $this->getHydraPrefix($context + $this->defaultContext);
418✔
97
        $data[$hydraPrefix.'view'] = ['@id' => null, '@type' => $hydraPrefix.'PartialCollectionView'];
418✔
98

99
        if ($isPaginatedWithCursor) {
418✔
100
            return $this->populateDataWithCursorBasedPagination($data, $parsed, $object, $cursorPaginationAttribute, $operation?->getUrlGenerationStrategy() ?? $this->urlGenerationStrategy, $hydraPrefix);
5✔
101
        }
102

103
        $data[$hydraPrefix.'view']['@id'] = IriHelper::createIri($parsed['parts'], $parsed['parameters'], $this->pageParameterName, $paginated ? $currentPage : null, $operation?->getUrlGenerationStrategy() ?? $this->urlGenerationStrategy);
413✔
104

105
        if ($paginated) {
413✔
106
            return $this->populateDataWithPagination($data, $parsed, $currentPage, $lastPage, $itemsPerPage, $pageTotalItems, $operation?->getUrlGenerationStrategy() ?? $this->urlGenerationStrategy, $hydraPrefix);
145✔
107
        }
108

109
        return $data;
274✔
110
    }
111

112
    /**
113
     * {@inheritdoc}
114
     */
115
    public function supportsNormalization(mixed $data, ?string $format = null, array $context = []): bool
116
    {
117
        return $this->collectionNormalizer->supportsNormalization($data, $format, $context);
910✔
118
    }
119

120
    public function getSupportedTypes($format): array
121
    {
122
        return $this->collectionNormalizer->getSupportedTypes($format);
1,789✔
123
    }
124

125
    /**
126
     * {@inheritdoc}
127
     */
128
    public function setNormalizer(NormalizerInterface $normalizer): void
129
    {
130
        if ($this->collectionNormalizer instanceof NormalizerAwareInterface) {
2,008✔
131
            $this->collectionNormalizer->setNormalizer($normalizer);
2,008✔
132
        }
133
    }
134

135
    private function cursorPaginationFields(array $fields, int $direction, $object): array
136
    {
137
        $paginationFilters = [];
2✔
138

139
        foreach ($fields as $field) {
2✔
140
            $forwardRangeOperator = 'desc' === strtolower($field['direction']) ? 'lt' : 'gt';
2✔
141
            $backwardRangeOperator = 'gt' === $forwardRangeOperator ? 'lt' : 'gt';
2✔
142

143
            $operator = $direction > 0 ? $forwardRangeOperator : $backwardRangeOperator;
2✔
144

145
            $paginationFilters[$field['field']] = [
2✔
146
                $operator => (string) $this->propertyAccessor->getValue($object, $field['field']),
2✔
147
            ];
2✔
148
        }
149

150
        return $paginationFilters;
2✔
151
    }
152

153
    private function populateDataWithCursorBasedPagination(array $data, array $parsed, \Traversable $object, ?array $cursorPaginationAttribute, ?int $urlGenerationStrategy, string $hydraPrefix): array
154
    {
155
        $objects = iterator_to_array($object);
5✔
156
        $firstObject = current($objects);
5✔
157
        $lastObject = end($objects);
5✔
158

159
        $data[$hydraPrefix.'view']['@id'] = IriHelper::createIri($parsed['parts'], $parsed['parameters'], urlGenerationStrategy: $urlGenerationStrategy);
5✔
160

161
        if (false !== $lastObject && \is_array($cursorPaginationAttribute)) {
5✔
162
            $data[$hydraPrefix.'view'][$hydraPrefix.'next'] = IriHelper::createIri($parsed['parts'], array_merge($parsed['parameters'], $this->cursorPaginationFields($cursorPaginationAttribute, 1, $lastObject)), urlGenerationStrategy: $urlGenerationStrategy);
2✔
163
        }
164

165
        if (false !== $firstObject && \is_array($cursorPaginationAttribute)) {
5✔
166
            $data[$hydraPrefix.'view'][$hydraPrefix.'previous'] = IriHelper::createIri($parsed['parts'], array_merge($parsed['parameters'], $this->cursorPaginationFields($cursorPaginationAttribute, -1, $firstObject)), urlGenerationStrategy: $urlGenerationStrategy);
2✔
167
        }
168

169
        return $data;
5✔
170
    }
171

172
    private function populateDataWithPagination(array $data, array $parsed, ?float $currentPage, ?float $lastPage, ?float $itemsPerPage, ?float $pageTotalItems, ?int $urlGenerationStrategy, string $hydraPrefix): array
173
    {
174
        if (null !== $lastPage) {
145✔
175
            $data[$hydraPrefix.'view'][$hydraPrefix.'first'] = IriHelper::createIri($parsed['parts'], $parsed['parameters'], $this->pageParameterName, 1., $urlGenerationStrategy);
144✔
176
            $data[$hydraPrefix.'view'][$hydraPrefix.'last'] = IriHelper::createIri($parsed['parts'], $parsed['parameters'], $this->pageParameterName, $lastPage, $urlGenerationStrategy);
144✔
177
        }
178

179
        if (1. !== $currentPage) {
145✔
180
            $data[$hydraPrefix.'view'][$hydraPrefix.'previous'] = IriHelper::createIri($parsed['parts'], $parsed['parameters'], $this->pageParameterName, $currentPage - 1., $urlGenerationStrategy);
12✔
181
        }
182

183
        if ((null !== $lastPage && $currentPage < $lastPage) || (null === $lastPage && $pageTotalItems >= $itemsPerPage)) {
145✔
184
            $data[$hydraPrefix.'view'][$hydraPrefix.'next'] = IriHelper::createIri($parsed['parts'], $parsed['parameters'], $this->pageParameterName, $currentPage + 1., $urlGenerationStrategy);
143✔
185
        }
186

187
        return $data;
145✔
188
    }
189
}
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