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

api-platform / core / 16347491392

17 Jul 2025 02:11PM UTC coverage: 22.039% (+0.03%) from 22.009%
16347491392

push

github

soyuka
Merge 4.1

17 of 23 new or added lines in 7 files covered. (73.91%)

206 existing lines in 8 files now uncovered.

11533 of 52331 relevant lines covered (22.04%)

23.45 hits per line

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

92.31
/src/Hydra/Serializer/CollectionFiltersNormalizer.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\FilterInterface;
18
use ApiPlatform\Metadata\Parameters;
19
use ApiPlatform\Metadata\QueryParameterInterface;
20
use ApiPlatform\Metadata\Resource\Factory\ResourceMetadataCollectionFactoryInterface;
21
use ApiPlatform\Metadata\ResourceClassResolverInterface;
22
use ApiPlatform\State\Util\StateOptionsTrait;
23
use Psr\Container\ContainerInterface;
24
use Symfony\Component\Serializer\Exception\UnexpectedValueException;
25
use Symfony\Component\Serializer\Normalizer\AbstractObjectNormalizer;
26
use Symfony\Component\Serializer\Normalizer\NormalizerAwareInterface;
27
use Symfony\Component\Serializer\Normalizer\NormalizerInterface;
28

29
/**
30
 * Enhances the result of collection by adding the filters applied on collection.
31
 *
32
 * @author Samuel ROZE <samuel.roze@gmail.com>
33
 */
34
final class CollectionFiltersNormalizer implements NormalizerInterface, NormalizerAwareInterface
35
{
36
    use HydraPrefixTrait;
37
    use StateOptionsTrait;
38
    private ?ContainerInterface $filterLocator = null;
39

40
    /**
41
     * @param ContainerInterface   $filterLocator  The new filter locator or the deprecated filter collection
42
     * @param array<string, mixed> $defaultContext
43
     */
44
    public function __construct(
45
        private readonly NormalizerInterface $collectionNormalizer,
46
        private readonly ResourceMetadataCollectionFactoryInterface $resourceMetadataCollectionFactory,
47
        private readonly ResourceClassResolverInterface $resourceClassResolver,
48
        ?ContainerInterface $filterLocator = null,
49
        private readonly array $defaultContext = [],
50
    ) {
51
        $this->filterLocator = $filterLocator;
596✔
52
    }
53

54
    /**
55
     * {@inheritdoc}
56
     */
57
    public function supportsNormalization(mixed $data, ?string $format = null, array $context = []): bool
58
    {
59
        return $this->collectionNormalizer->supportsNormalization($data, $format, $context);
342✔
60
    }
61

62
    public function getSupportedTypes($format): array
63
    {
64
        return $this->collectionNormalizer->getSupportedTypes($format);
490✔
65
    }
66

67
    /**
68
     * {@inheritdoc}
69
     */
70
    public function normalize(mixed $object, ?string $format = null, array $context = []): array|string|int|float|bool|\ArrayObject|null
71
    {
72
        if (($context[AbstractObjectNormalizer::PRESERVE_EMPTY_OBJECTS] ?? false) && $object instanceof \ArrayObject && !\count($object)) {
342✔
73
            return $object;
×
74
        }
75

76
        $data = $this->collectionNormalizer->normalize($object, $format, $context);
342✔
77
        if (!isset($context['resource_class']) || isset($context['api_sub_level'])) {
342✔
78
            return $data;
114✔
79
        }
80

81
        if (!\is_array($data)) {
238✔
82
            throw new UnexpectedValueException('Expected data to be an array');
×
83
        }
84
        $resourceClass = $this->resourceClassResolver->getResourceClass($object, $context['resource_class']);
238✔
85
        $operation = $context['operation'] ?? $this->resourceMetadataCollectionFactory->create($resourceClass)->getOperation($context['operation_name'] ?? null);
238✔
86

87
        $parameters = $operation->getParameters();
238✔
88
        $resourceFilters = $operation->getFilters();
238✔
89
        if (!$resourceFilters && !$parameters) {
238✔
90
            return $data;
26✔
91
        }
92

93
        $requestParts = parse_url($context['request_uri'] ?? '');
212✔
94
        if (!\is_array($requestParts)) {
212✔
95
            return $data;
×
96
        }
97
        $currentFilters = [];
212✔
98
        foreach ($resourceFilters as $filterId) {
212✔
99
            if ($filter = $this->getFilter($filterId)) {
8✔
100
                $currentFilters[] = $filter;
8✔
101
            }
102
        }
103

104
        $resourceClass = $this->getStateOptionsClass($operation, $resourceClass);
212✔
105

106
        if ($currentFilters || ($parameters && \count($parameters))) {
212✔
107
            $hydraPrefix = $this->getHydraPrefix($context + $this->defaultContext);
212✔
108
            $data[$hydraPrefix.'search'] = $this->getSearch($resourceClass, $requestParts, $currentFilters, $parameters, $hydraPrefix);
212✔
109
        }
110

111
        return $data;
212✔
112
    }
113

114
    /**
115
     * {@inheritdoc}
116
     */
117
    public function setNormalizer(NormalizerInterface $normalizer): void
118
    {
119
        if ($this->collectionNormalizer instanceof NormalizerAwareInterface) {
596✔
120
            $this->collectionNormalizer->setNormalizer($normalizer);
596✔
121
        }
122
    }
123

124
    /**
125
     * Returns the content of the Hydra search property.
126
     *
127
     * @param FilterInterface[] $filters
128
     */
129
    private function getSearch(string $resourceClass, array $parts, array $filters, ?Parameters $parameters, string $hydraPrefix): array
130
    {
131
        $variables = [];
212✔
132
        $mapping = [];
212✔
133
        foreach ($filters as $filter) {
212✔
134
            foreach ($filter->getDescription($resourceClass) as $variable => $data) {
8✔
135
                $variables[] = $variable;
8✔
136
                $mapping[] = ['@type' => 'IriTemplateMapping', 'variable' => $variable, 'property' => $data['property'] ?? null, 'required' => $data['required'] ?? false];
8✔
137
            }
138
        }
139

140
        foreach ($parameters ?? [] as $key => $parameter) {
212✔
141
            // Each IriTemplateMapping maps a variable used in the template to a property
142
            if (!$parameter instanceof QueryParameterInterface || false === $parameter->getHydra()) {
208✔
143
                continue;
12✔
144
            }
145

146
            if (($filterId = $parameter->getFilter()) && \is_string($filterId) && ($filter = $this->getFilter($filterId))) {
204✔
147
                $filterDescription = $filter->getDescription($resourceClass);
10✔
148

149
                foreach ($filterDescription as $variable => $description) {
10✔
150
                    // // This is a practice induced by PHP and is not necessary when implementing URI template
151
                    if (str_ends_with((string) $variable, '[]')) {
10✔
152
                        continue;
4✔
153
                    }
154

155
                    if (!($descriptionProperty = $description['property'] ?? null)) {
10✔
156
                        continue;
2✔
157
                    }
158

159
                    if (($prop = $parameter->getProperty()) && $descriptionProperty !== $prop) {
8✔
UNCOV
160
                        continue;
×
161
                    }
162

163
                    // :property is a pattern allowed when defining parameters
164
                    $k = str_replace(':property', $descriptionProperty, $key);
8✔
165
                    $variable = str_replace($descriptionProperty, $k, $variable);
8✔
166
                    $variables[] = $variable;
8✔
167
                    $m = ['@type' => 'IriTemplateMapping', 'variable' => $variable, 'property' => $descriptionProperty];
8✔
168
                    if (null !== ($required = $parameter->getRequired() ?? $description['required'] ?? null)) {
8✔
169
                        $m['required'] = $required;
8✔
170
                    }
171
                    $mapping[] = $m;
8✔
172
                }
173

174
                if ($filterDescription) {
10✔
175
                    continue;
10✔
176
                }
177
            }
178

179
            if (str_contains($key, ':property') && $parameter->getProperties()) {
200✔
180
                $required = $parameter->getRequired();
2✔
181
                foreach ($parameter->getProperties() as $prop) {
2✔
182
                    $k = str_replace(':property', $prop, $key);
2✔
183
                    $m = ['@type' => 'IriTemplateMapping', 'variable' => $k, 'property' => $prop];
2✔
184
                    $variables[] = $k;
2✔
185
                    if (null !== $required) {
2✔
186
                        $m['required'] = $required;
×
187
                    }
188
                    $mapping[] = $m;
2✔
189
                }
190

191
                continue;
2✔
192
            }
193

194
            if (!($property = $parameter->getProperty())) {
198✔
195
                continue;
62✔
196
            }
197

198
            $m = ['@type' => 'IriTemplateMapping', 'variable' => $key, 'property' => $property];
176✔
199
            $variables[] = $key;
176✔
200
            if (null !== ($required = $parameter->getRequired())) {
176✔
201
                $m['required'] = $required;
4✔
202
            }
203
            $mapping[] = $m;
176✔
204
        }
205

206
        return ['@type' => $hydraPrefix.'IriTemplate', $hydraPrefix.'template' => \sprintf('%s{?%s}', $parts['path'], implode(',', $variables)), $hydraPrefix.'variableRepresentation' => 'BasicRepresentation', $hydraPrefix.'mapping' => $mapping];
212✔
207
    }
208

209
    /**
210
     * Gets a filter with a backward compatibility.
211
     */
212
    private function getFilter(string $filterId): ?FilterInterface
213
    {
214
        if ($this->filterLocator && $this->filterLocator->has($filterId)) {
18✔
215
            return $this->filterLocator->get($filterId);
18✔
216
        }
217

218
        return null;
×
219
    }
220
}
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