• 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

92.86
/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\Parameters;
21
use ApiPlatform\Metadata\QueryParameterInterface;
22
use ApiPlatform\Metadata\Resource\Factory\ResourceMetadataCollectionFactoryInterface;
23
use ApiPlatform\Metadata\ResourceClassResolverInterface;
24
use Psr\Container\ContainerInterface;
25
use Symfony\Component\Serializer\Exception\UnexpectedValueException;
26
use Symfony\Component\Serializer\Normalizer\AbstractObjectNormalizer;
27
use Symfony\Component\Serializer\Normalizer\NormalizerAwareInterface;
28
use Symfony\Component\Serializer\Normalizer\NormalizerInterface;
29

30
/**
31
 * Enhances the result of collection by adding the filters applied on collection.
32
 *
33
 * @author Samuel ROZE <samuel.roze@gmail.com>
34
 */
35
final class CollectionFiltersNormalizer implements NormalizerInterface, NormalizerAwareInterface
36
{
37
    use HydraPrefixTrait;
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;
1,160✔
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);
547✔
60
    }
61

62
    public function getSupportedTypes($format): array
63
    {
64
        return $this->collectionNormalizer->getSupportedTypes($format);
1,024✔
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)) {
547✔
UNCOV
73
            return $object;
1✔
74
        }
75

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

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

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

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

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

109
            if ($options instanceof ODMOptions && $options->getDocumentClass()) {
288✔
UNCOV
110
                $resourceClass = $options->getDocumentClass();
2✔
111
            }
112
        }
113

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

119
        return $data;
306✔
120
    }
121

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

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

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

154
            if (($filterId = $parameter->getFilter()) && \is_string($filterId) && ($filter = $this->getFilter($filterId))) {
190✔
155
                $filterDescription = $filter->getDescription($resourceClass);
8✔
156

157
                foreach ($filterDescription as $variable => $description) {
8✔
158
                    // // This is a practice induced by PHP and is not necessary when implementing URI template
159
                    if (str_ends_with((string) $variable, '[]')) {
8✔
160
                        continue;
4✔
161
                    }
162

163
                    if (($prop = $parameter->getProperty()) && ($description['property'] ?? null) !== $prop) {
8✔
164
                        continue;
×
165
                    }
166

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

178
                if ($filterDescription) {
8✔
179
                    continue;
8✔
180
                }
181
            }
182

183
            if (!($property = $parameter->getProperty())) {
186✔
184
                continue;
50✔
185
            }
186

187
            $m = ['@type' => 'IriTemplateMapping', 'variable' => $key, 'property' => $property];
176✔
188
            $variables[] = $key;
176✔
189
            if (null !== ($required = $parameter->getRequired())) {
176✔
190
                $m['required'] = $required;
4✔
191
            }
192
            $mapping[] = $m;
176✔
193
        }
194

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

198
    /**
199
     * Gets a filter with a backward compatibility.
200
     */
201
    private function getFilter(string $filterId): ?FilterInterface
202
    {
203
        if ($this->filterLocator && $this->filterLocator->has($filterId)) {
124✔
204
            return $this->filterLocator->get($filterId);
124✔
205
        }
206

207
        return null;
×
208
    }
209
}
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