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

api-platform / core / 10814494863

11 Sep 2024 03:11PM UTC coverage: 7.008% (-0.7%) from 7.679%
10814494863

push

github

web-flow
fix(state): remove resource_class change (#6607)

11516 of 164321 relevant lines covered (7.01%)

22.85 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,259✔
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);
942✔
54

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

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

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

72
            $currentPage = $object->getCurrentPage();
498✔
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);
551✔
79
        $appliedFilters = $parsed['parameters'];
551✔
80
        unset($appliedFilters[$this->enabledParameterName]);
551✔
81

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

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

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

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

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

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

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

109
        return $data;
141✔
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);
942✔
118
    }
119

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

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

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

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

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

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

150
        return $paginationFilters;
3✔
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);
7✔
156
        $firstObject = current($objects);
7✔
157
        $lastObject = end($objects);
7✔
158

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

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

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

169
        return $data;
7✔
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) {
200✔
175
            $data[$hydraPrefix.'view'][$hydraPrefix.'first'] = IriHelper::createIri($parsed['parts'], $parsed['parameters'], $this->pageParameterName, 1., $urlGenerationStrategy);
199✔
176
            $data[$hydraPrefix.'view'][$hydraPrefix.'last'] = IriHelper::createIri($parsed['parts'], $parsed['parameters'], $this->pageParameterName, $lastPage, $urlGenerationStrategy);
199✔
177
        }
178

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

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

187
        return $data;
200✔
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