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

api-platform / core / 5650127293

pending completion
5650127293

push

github

web-flow
fix: don't implement deprecated CacheableSupportsMethodInterface with Symfony 6.3+ (#5696)

* fix: don't implement deprecated CacheableSupportsMethodInterface

* fix: a check, and add tests

* fix ApiGatewayNormalizerTest

* more fixes

* fix more tests

* fix lowest

* only trigger the deprecation for Symfony 6.3

167 of 167 new or added lines in 23 files covered. (100.0%)

10865 of 18368 relevant lines covered (59.15%)

19.9 hits per line

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

81.94
/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\Serializer\CacheableSupportsMethodInterface;
19
use ApiPlatform\State\Pagination\PaginatorInterface;
20
use ApiPlatform\State\Pagination\PartialPaginatorInterface;
21
use ApiPlatform\Util\IriHelper;
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\CacheableSupportsMethodInterface as BaseCacheableSupportsMethodInterface;
26
use Symfony\Component\Serializer\Normalizer\NormalizerAwareInterface;
27
use Symfony\Component\Serializer\Normalizer\NormalizerInterface;
28
use Symfony\Component\Serializer\Serializer;
29

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

40
    public function __construct(private readonly NormalizerInterface $collectionNormalizer, private readonly string $pageParameterName = 'page', private string $enabledParameterName = 'pagination', private readonly ?ResourceMetadataCollectionFactoryInterface $resourceMetadataFactory = null, PropertyAccessorInterface $propertyAccessor = null)
41
    {
42
        $this->propertyAccessor = $propertyAccessor ?? PropertyAccess::createPropertyAccessor();
68✔
43
    }
44

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

52
        if (isset($context['api_sub_level'])) {
30✔
53
            return $data;
4✔
54
        }
55

56
        if (!\is_array($data)) {
26✔
57
            throw new UnexpectedValueException('Expected data to be an array');
×
58
        }
59

60
        $currentPage = $lastPage = $itemsPerPage = $pageTotalItems = null;
26✔
61
        if ($paginated = ($object instanceof PartialPaginatorInterface)) {
26✔
62
            if ($object instanceof PaginatorInterface) {
20✔
63
                $paginated = 1. !== $lastPage = $object->getLastPage();
18✔
64
            } else {
65
                $itemsPerPage = $object->getItemsPerPage();
2✔
66
                $pageTotalItems = (float) \count($object);
2✔
67
            }
68

69
            $currentPage = $object->getCurrentPage();
20✔
70
        }
71

72
        $parsed = IriHelper::parseIri($context['request_uri'] ?? '/', $this->pageParameterName);
26✔
73
        $appliedFilters = $parsed['parameters'];
26✔
74
        unset($appliedFilters[$this->enabledParameterName]);
26✔
75

76
        if (!$appliedFilters && !$paginated) {
26✔
77
            return $data;
20✔
78
        }
79

80
        $isPaginatedWithCursor = false;
6✔
81
        $cursorPaginationAttribute = null;
6✔
82
        if ($this->resourceMetadataFactory && isset($context['resource_class']) && $paginated) {
6✔
83
            /** @var HttpOperation $operation */
84
            $operation = $this->resourceMetadataFactory->create($context['resource_class'])->getOperation($context['operation_name'] ?? null);
2✔
85
            $isPaginatedWithCursor = [] !== $cursorPaginationAttribute = ($operation->getPaginationViaCursor() ?? []);
2✔
86
        }
87

88
        $data['hydra:view'] = ['@id' => null, '@type' => 'hydra:PartialCollectionView'];
6✔
89

90
        if ($isPaginatedWithCursor) {
6✔
91
            return $this->populateDataWithCursorBasedPagination($data, $parsed, $object, $cursorPaginationAttribute);
2✔
92
        }
93

94
        $data['hydra:view']['@id'] = IriHelper::createIri($parsed['parts'], $parsed['parameters'], $this->pageParameterName, $paginated ? $currentPage : null);
4✔
95

96
        if ($paginated) {
4✔
97
            return $this->populateDataWithPagination($data, $parsed, $currentPage, $lastPage, $itemsPerPage, $pageTotalItems);
4✔
98
        }
99

100
        return $data;
×
101
    }
102

103
    /**
104
     * {@inheritdoc}
105
     */
106
    public function supportsNormalization(mixed $data, string $format = null, array $context = []): bool
107
    {
108
        return $this->collectionNormalizer->supportsNormalization($data, $format, $context);
22✔
109
    }
110

111
    public function getSupportedTypes($format): array
112
    {
113
        // @deprecated remove condition when support for symfony versions under 6.3 is dropped
114
        if (!method_exists($this->collectionNormalizer, 'getSupportedTypes')) {
30✔
115
            return [
×
116
                '*' => $this->collectionNormalizer instanceof BaseCacheableSupportsMethodInterface && $this->collectionNormalizer->hasCacheableSupportsMethod(),
×
117
            ];
×
118
        }
119

120
        return $this->collectionNormalizer->getSupportedTypes($format);
30✔
121
    }
122

123
    public function hasCacheableSupportsMethod(): bool
124
    {
125
        if (method_exists(Serializer::class, 'getSupportedTypes')) {
×
126
            trigger_deprecation(
×
127
                'api-platform/core',
×
128
                '3.1',
×
129
                'The "%s()" method is deprecated, use "getSupportedTypes()" instead.',
×
130
                __METHOD__
×
131
            );
×
132
        }
133

134
        return $this->collectionNormalizer instanceof BaseCacheableSupportsMethodInterface && $this->collectionNormalizer->hasCacheableSupportsMethod();
×
135
    }
136

137
    /**
138
     * {@inheritdoc}
139
     */
140
    public function setNormalizer(NormalizerInterface $normalizer): void
141
    {
142
        if ($this->collectionNormalizer instanceof NormalizerAwareInterface) {
56✔
143
            $this->collectionNormalizer->setNormalizer($normalizer);
56✔
144
        }
145
    }
146

147
    private function cursorPaginationFields(array $fields, int $direction, $object): array
148
    {
149
        $paginationFilters = [];
2✔
150

151
        foreach ($fields as $field) {
2✔
152
            $forwardRangeOperator = 'desc' === strtolower($field['direction']) ? 'lt' : 'gt';
2✔
153
            $backwardRangeOperator = 'gt' === $forwardRangeOperator ? 'lt' : 'gt';
2✔
154

155
            $operator = $direction > 0 ? $forwardRangeOperator : $backwardRangeOperator;
2✔
156

157
            $paginationFilters[$field['field']] = [
2✔
158
                $operator => (string) $this->propertyAccessor->getValue($object, $field['field']),
2✔
159
            ];
2✔
160
        }
161

162
        return $paginationFilters;
2✔
163
    }
164

165
    private function populateDataWithCursorBasedPagination(array $data, array $parsed, \Traversable $object, ?array $cursorPaginationAttribute): array
166
    {
167
        $objects = iterator_to_array($object);
2✔
168
        $firstObject = current($objects);
2✔
169
        $lastObject = end($objects);
2✔
170

171
        $data['hydra:view']['@id'] = IriHelper::createIri($parsed['parts'], $parsed['parameters']);
2✔
172

173
        if (false !== $lastObject && \is_array($cursorPaginationAttribute)) {
2✔
174
            $data['hydra:view']['hydra:next'] = IriHelper::createIri($parsed['parts'], array_merge($parsed['parameters'], $this->cursorPaginationFields($cursorPaginationAttribute, 1, $lastObject)));
2✔
175
        }
176

177
        if (false !== $firstObject && \is_array($cursorPaginationAttribute)) {
2✔
178
            $data['hydra:view']['hydra:previous'] = IriHelper::createIri($parsed['parts'], array_merge($parsed['parameters'], $this->cursorPaginationFields($cursorPaginationAttribute, -1, $firstObject)));
2✔
179
        }
180

181
        return $data;
2✔
182
    }
183

184
    private function populateDataWithPagination(array $data, array $parsed, ?float $currentPage, ?float $lastPage, ?float $itemsPerPage, ?float $pageTotalItems): array
185
    {
186
        if (null !== $lastPage) {
4✔
187
            $data['hydra:view']['hydra:first'] = IriHelper::createIri($parsed['parts'], $parsed['parameters'], $this->pageParameterName, 1.);
2✔
188
            $data['hydra:view']['hydra:last'] = IriHelper::createIri($parsed['parts'], $parsed['parameters'], $this->pageParameterName, $lastPage);
2✔
189
        }
190

191
        if (1. !== $currentPage) {
4✔
192
            $data['hydra:view']['hydra:previous'] = IriHelper::createIri($parsed['parts'], $parsed['parameters'], $this->pageParameterName, $currentPage - 1.);
4✔
193
        }
194

195
        if ((null !== $lastPage && $currentPage < $lastPage) || (null === $lastPage && $pageTotalItems >= $itemsPerPage)) {
4✔
196
            $data['hydra:view']['hydra:next'] = IriHelper::createIri($parsed['parts'], $parsed['parameters'], $this->pageParameterName, $currentPage + 1.);
4✔
197
        }
198

199
        return $data;
4✔
200
    }
201
}
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

© 2026 Coveralls, Inc