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

api-platform / core / 18223414080

03 Oct 2025 01:18PM UTC coverage: 0.0% (-22.0%) from 21.956%
18223414080

Pull #7397

github

web-flow
Merge 69d085182 into 0b8237918
Pull Request #7397: fix(jsonschema/jsonld): make `@id` and `@type` properties required only in the JSON-LD schema for output

0 of 18 new or added lines in 2 files covered. (0.0%)

12304 existing lines in 405 files now uncovered.

0 of 53965 relevant lines covered (0.0%)

0.0 hits per line

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

0.0
/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\Hydra\State\Util\PaginationHelperTrait;
17
use ApiPlatform\JsonLd\Serializer\HydraPrefixTrait;
18
use ApiPlatform\Metadata\HttpOperation;
19
use ApiPlatform\Metadata\Resource\Factory\ResourceMetadataCollectionFactoryInterface;
20
use ApiPlatform\Metadata\UrlGeneratorInterface;
21
use ApiPlatform\Metadata\Util\IriHelper;
22
use ApiPlatform\State\Pagination\PaginatorInterface;
23
use ApiPlatform\State\Pagination\PartialPaginatorInterface;
24
use Symfony\Component\PropertyAccess\PropertyAccess;
25
use Symfony\Component\PropertyAccess\PropertyAccessorInterface;
26
use Symfony\Component\Serializer\Exception\UnexpectedValueException;
27
use Symfony\Component\Serializer\Normalizer\NormalizerAwareInterface;
28
use Symfony\Component\Serializer\Normalizer\NormalizerInterface;
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
37
{
38
    use HydraPrefixTrait;
39
    use PaginationHelperTrait;
40
    private readonly PropertyAccessorInterface $propertyAccessor;
41

42
    /**
43
     * @param array<string, mixed> $defaultContext
44
     */
45
    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 = [])
46
    {
UNCOV
47
        $this->propertyAccessor = $propertyAccessor ?? PropertyAccess::createPropertyAccessor();
×
48
    }
49

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

UNCOV
57
        if (isset($context['api_sub_level'])) {
×
UNCOV
58
            return $data;
×
59
        }
60

UNCOV
61
        if (!\is_array($data)) {
×
62
            throw new UnexpectedValueException('Expected data to be an array');
×
63
        }
64

UNCOV
65
        $paginated = $object instanceof PartialPaginatorInterface;
×
UNCOV
66
        if ($paginated && $object instanceof PaginatorInterface) {
×
UNCOV
67
            $paginated = 1. !== $object->getLastPage();
×
68
        }
69

UNCOV
70
        $parsed = IriHelper::parseIri($context['uri'] ?? $context['request_uri'] ?? '/', $this->pageParameterName);
×
UNCOV
71
        $appliedFilters = $parsed['parameters'];
×
UNCOV
72
        unset($appliedFilters[$this->enabledParameterName]);
×
73

UNCOV
74
        if (!$appliedFilters && !$paginated) {
×
UNCOV
75
            return $data;
×
76
        }
77

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

UNCOV
85
        $cursorPaginationAttribute = $operation instanceof HttpOperation ? $operation->getPaginationViaCursor() : null;
×
UNCOV
86
        $isPaginatedWithCursor = (bool) $cursorPaginationAttribute;
×
87

UNCOV
88
        $hydraPrefix = $this->getHydraPrefix($context + $this->defaultContext);
×
89

UNCOV
90
        if ($isPaginatedWithCursor) {
×
91
            $data[$hydraPrefix.'view'] = ['@id' => null, '@type' => $hydraPrefix.'PartialCollectionView'];
×
92

93
            return $this->populateDataWithCursorBasedPagination($data, $parsed, $object, $cursorPaginationAttribute, $operation?->getUrlGenerationStrategy() ?? $this->urlGenerationStrategy, $hydraPrefix);
×
94
        }
95

UNCOV
96
        $partialCollectionView = $this->getPartialCollectionView($object, $context['uri'] ?? $context['request_uri'] ?? '/', $this->pageParameterName, $this->enabledParameterName, $operation?->getUrlGenerationStrategy() ?? $this->urlGenerationStrategy);
×
97

UNCOV
98
        $view = [
×
UNCOV
99
            '@id' => $partialCollectionView->id,
×
UNCOV
100
            '@type' => $hydraPrefix.'PartialCollectionView',
×
UNCOV
101
        ];
×
102

UNCOV
103
        if (null !== $partialCollectionView->first) {
×
UNCOV
104
            $view[$hydraPrefix.'first'] = $partialCollectionView->first;
×
UNCOV
105
            $view[$hydraPrefix.'last'] = $partialCollectionView->last;
×
106
        }
107

UNCOV
108
        if (null !== $partialCollectionView->previous) {
×
109
            $view[$hydraPrefix.'previous'] = $partialCollectionView->previous;
×
110
        }
111

UNCOV
112
        if (null !== $partialCollectionView->next) {
×
UNCOV
113
            $view[$hydraPrefix.'next'] = $partialCollectionView->next;
×
114
        }
115

UNCOV
116
        $data[$hydraPrefix.'view'] = $view;
×
117

UNCOV
118
        return $data;
×
119
    }
120

121
    /**
122
     * {@inheritdoc}
123
     */
124
    public function supportsNormalization(mixed $data, ?string $format = null, array $context = []): bool
125
    {
UNCOV
126
        return $this->collectionNormalizer->supportsNormalization($data, $format, $context);
×
127
    }
128

129
    /**
130
     * @param string|null $format
131
     */
132
    public function getSupportedTypes($format): array
133
    {
UNCOV
134
        return $this->collectionNormalizer->getSupportedTypes($format);
×
135
    }
136

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

147
    /**
148
     * @param object $object
149
     */
150
    private function cursorPaginationFields(array $fields, int $direction, $object): array
151
    {
152
        $paginationFilters = [];
×
153

154
        foreach ($fields as $field) {
×
155
            $forwardRangeOperator = 'desc' === strtolower($field['direction']) ? 'lt' : 'gt';
×
156
            $backwardRangeOperator = 'gt' === $forwardRangeOperator ? 'lt' : 'gt';
×
157

158
            $operator = $direction > 0 ? $forwardRangeOperator : $backwardRangeOperator;
×
159

160
            $paginationFilters[$field['field']] = [
×
161
                $operator => (string) $this->propertyAccessor->getValue($object, $field['field']),
×
162
            ];
×
163
        }
164

165
        return $paginationFilters;
×
166
    }
167

168
    private function populateDataWithCursorBasedPagination(array $data, array $parsed, \Traversable $object, ?array $cursorPaginationAttribute, ?int $urlGenerationStrategy, string $hydraPrefix): array
169
    {
170
        $objects = iterator_to_array($object);
×
171
        $firstObject = current($objects);
×
172
        $lastObject = end($objects);
×
173

174
        $data[$hydraPrefix.'view']['@id'] = IriHelper::createIri($parsed['parts'], $parsed['parameters'], urlGenerationStrategy: $urlGenerationStrategy);
×
175

176
        if (false !== $lastObject && \is_array($cursorPaginationAttribute)) {
×
177
            $data[$hydraPrefix.'view'][$hydraPrefix.'next'] = IriHelper::createIri($parsed['parts'], array_merge($parsed['parameters'], $this->cursorPaginationFields($cursorPaginationAttribute, 1, $lastObject)), urlGenerationStrategy: $urlGenerationStrategy);
×
178
        }
179

180
        if (false !== $firstObject && \is_array($cursorPaginationAttribute)) {
×
181
            $data[$hydraPrefix.'view'][$hydraPrefix.'previous'] = IriHelper::createIri($parsed['parts'], array_merge($parsed['parameters'], $this->cursorPaginationFields($cursorPaginationAttribute, -1, $firstObject)), urlGenerationStrategy: $urlGenerationStrategy);
×
182
        }
183

184
        return $data;
×
185
    }
186
}
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