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

api-platform / core / 14635100171

24 Apr 2025 06:39AM UTC coverage: 8.271% (+0.02%) from 8.252%
14635100171

Pull #6904

github

web-flow
Merge c9cefd82e into a3e5e53ea
Pull Request #6904: feat(graphql): added support for graphql subscriptions to work for actions

0 of 73 new or added lines in 3 files covered. (0.0%)

1999 existing lines in 144 files now uncovered.

13129 of 158728 relevant lines covered (8.27%)

13.6 hits per line

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

93.65
/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();
1,160✔
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);
547✔
54

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

UNCOV
150
        return $paginationFilters;
1✔
151
    }
152

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

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

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

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

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

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

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

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