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

api-platform / core / 10903050455

17 Sep 2024 12:29PM UTC coverage: 7.684% (+0.7%) from 6.96%
10903050455

push

github

web-flow
fix: swagger ui with route identifier (#6616)

2 of 6 new or added lines in 6 files covered. (33.33%)

9000 existing lines in 286 files now uncovered.

12668 of 164863 relevant lines covered (7.68%)

22.93 hits per line

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

66.67
/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\Doctrine\Odm\State\Options as ODMOptions;
17
use ApiPlatform\Doctrine\Orm\State\Options;
18
use ApiPlatform\JsonLd\Serializer\HydraPrefixTrait;
19
use ApiPlatform\Metadata\FilterInterface;
20
use ApiPlatform\Metadata\Parameter;
21
use ApiPlatform\Metadata\Parameters;
22
use ApiPlatform\Metadata\QueryParameterInterface;
23
use ApiPlatform\Metadata\Resource\Factory\ResourceMetadataCollectionFactoryInterface;
24
use ApiPlatform\Metadata\ResourceClassResolverInterface;
25
use Psr\Container\ContainerInterface;
26
use Symfony\Component\Serializer\Exception\UnexpectedValueException;
27
use Symfony\Component\Serializer\Normalizer\AbstractObjectNormalizer;
28
use Symfony\Component\Serializer\Normalizer\NormalizerAwareInterface;
29
use Symfony\Component\Serializer\Normalizer\NormalizerInterface;
30

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

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

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

63
    public function getSupportedTypes($format): array
64
    {
UNCOV
65
        return $this->collectionNormalizer->getSupportedTypes($format);
2,016✔
66
    }
67

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

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

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

UNCOV
88
        $parameters = $operation->getParameters();
551✔
UNCOV
89
        $resourceFilters = $operation->getFilters();
551✔
UNCOV
90
        if (!$resourceFilters && !$parameters) {
551✔
UNCOV
91
            return $data;
205✔
92
        }
93

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

UNCOV
105
        if ($options = $operation->getStateOptions()) {
346✔
UNCOV
106
            if ($options instanceof Options && $options->getEntityClass()) {
346✔
107
                $resourceClass = $options->getEntityClass();
4✔
108
            }
109

UNCOV
110
            if ($options instanceof ODMOptions && $options->getDocumentClass()) {
346✔
UNCOV
111
                $resourceClass = $options->getDocumentClass();
4✔
112
            }
113
        }
114

UNCOV
115
        if ($currentFilters || ($parameters && \count($parameters))) {
346✔
UNCOV
116
            $hydraPrefix = $this->getHydraPrefix($context + $this->defaultContext);
346✔
UNCOV
117
            $data[$hydraPrefix.'search'] = $this->getSearch($resourceClass, $requestParts, $currentFilters, $parameters, $hydraPrefix);
346✔
118
        }
119

UNCOV
120
        return $data;
346✔
121
    }
122

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

133
    /**
134
     * Returns the content of the Hydra search property.
135
     *
136
     * @param FilterInterface[]        $filters
137
     * @param array<string, Parameter> $parameters
138
     */
139
    private function getSearch(string $resourceClass, array $parts, array $filters, array|Parameters|null $parameters, string $hydraPrefix): array
140
    {
UNCOV
141
        $variables = [];
346✔
UNCOV
142
        $mapping = [];
346✔
UNCOV
143
        foreach ($filters as $filter) {
346✔
UNCOV
144
            foreach ($filter->getDescription($resourceClass) as $variable => $data) {
346✔
UNCOV
145
                $variables[] = $variable;
345✔
UNCOV
146
                $mapping[] = ['@type' => 'IriTemplateMapping', 'variable' => $variable, 'property' => $data['property'] ?? null, 'required' => $data['required'] ?? false];
345✔
147
            }
148
        }
149

UNCOV
150
        foreach ($parameters ?? [] as $key => $parameter) {
346✔
151
            // Each IriTemplateMapping maps a variable used in the template to a property
UNCOV
152
            if (!$parameter instanceof QueryParameterInterface || false === $parameter->getHydra()) {
298✔
UNCOV
153
                continue;
298✔
154
            }
155

156
            if (!($property = $parameter->getProperty()) && ($filterId = $parameter->getFilter()) && ($filter = $this->getFilter($filterId))) {
×
157
                foreach ($filter->getDescription($resourceClass) as $variable => $description) {
×
158
                    // This is a practice induced by PHP and is not necessary when implementing URI template
159
                    if (str_ends_with((string) $variable, '[]')) {
×
160
                        continue;
×
161
                    }
162

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

174
                continue;
×
175
            }
176

177
            if (!$property) {
×
178
                continue;
×
179
            }
180

181
            $m = ['@type' => 'IriTemplateMapping', 'variable' => $key, 'property' => $property];
×
182
            $variables[] = $key;
×
183
            if (null !== ($required = $parameter->getRequired())) {
×
184
                $m['required'] = $required;
×
185
            }
186
            $mapping[] = $m;
×
187
        }
188

UNCOV
189
        return ['@type' => $hydraPrefix.'IriTemplate', $hydraPrefix.'template' => \sprintf('%s{?%s}', $parts['path'], implode(',', $variables)), $hydraPrefix.'variableRepresentation' => 'BasicRepresentation', $hydraPrefix.'mapping' => $mapping];
346✔
190
    }
191

192
    /**
193
     * Gets a filter with a backward compatibility.
194
     */
195
    private function getFilter(string $filterId): ?FilterInterface
196
    {
UNCOV
197
        if ($this->filterLocator && $this->filterLocator->has($filterId)) {
346✔
UNCOV
198
            return $this->filterLocator->get($filterId);
346✔
199
        }
200

201
        return null;
×
202
    }
203
}
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