• 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

90.63
/src/Doctrine/Odm/Filter/OrderFilter.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\Doctrine\Odm\Filter;
15

16
use ApiPlatform\Doctrine\Common\Filter\OrderFilterInterface;
17
use ApiPlatform\Doctrine\Common\Filter\OrderFilterTrait;
18
use ApiPlatform\Doctrine\Common\Filter\PropertyPlaceholderOpenApiParameterTrait;
19
use ApiPlatform\Metadata\JsonSchemaFilterInterface;
20
use ApiPlatform\Metadata\OpenApiParameterFilterInterface;
21
use ApiPlatform\Metadata\Operation;
22
use ApiPlatform\Metadata\Parameter;
23
use Doctrine\ODM\MongoDB\Aggregation\Builder;
24
use Doctrine\Persistence\ManagerRegistry;
25
use Psr\Log\LoggerInterface;
26
use Symfony\Component\Serializer\NameConverter\NameConverterInterface;
27

28
/**
29
 * The order filter allows to sort a collection against the given properties.
30
 *
31
 * Syntax: `?order[property]=<asc|desc>`.
32
 *
33
 * <div data-code-selector>
34
 *
35
 * ```php
36
 * <?php
37
 * // api/src/Entity/Book.php
38
 * use ApiPlatform\Metadata\ApiFilter;
39
 * use ApiPlatform\Metadata\ApiResource;
40
 * use ApiPlatform\Doctrine\Odm\Filter\OrderFilter;
41
 *
42
 * #[ApiResource]
43
 * #[ApiFilter(OrderFilter::class, properties: ['id', 'title'], arguments: ['orderParameterName' => 'order'])]
44
 * class Book
45
 * {
46
 *     // ...
47
 * }
48
 * ```
49
 *
50
 * ```yaml
51
 * # config/services.yaml
52
 * services:
53
 *     book.order_filter:
54
 *         parent: 'api_platform.doctrine.odm.order_filter'
55
 *         arguments: [ $properties: { id: ~, title: ~ }, $orderParameterName: order ]
56
 *         tags:  [ 'api_platform.filter' ]
57
 *         # The following are mandatory only if a _defaults section is defined with inverted values.
58
 *         # You may want to isolate filters in a dedicated file to avoid adding the following lines (by adding them in the defaults section)
59
 *         autowire: false
60
 *         autoconfigure: false
61
 *         public: false
62
 *
63
 * # api/config/api_platform/resources.yaml
64
 * resources:
65
 *     App\Entity\Book:
66
 *         - operations:
67
 *               ApiPlatform\Metadata\GetCollection:
68
 *                   filters: ['book.order_filter']
69
 * ```
70
 *
71
 * ```xml
72
 * <?xml version="1.0" encoding="UTF-8" ?>
73
 * <!-- api/config/services.xml -->
74
 * <?xml version="1.0" encoding="UTF-8" ?>
75
 * <container
76
 *         xmlns="http://symfony.com/schema/dic/services"
77
 *         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
78
 *         xsi:schemaLocation="http://symfony.com/schema/dic/services
79
 *         https://symfony.com/schema/dic/services/services-1.0.xsd">
80
 *     <services>
81
 *         <service id="book.order_filter" parent="api_platform.doctrine.odm.order_filter">
82
 *             <argument type="collection" key="properties">
83
 *                 <argument key="id"/>
84
 *                 <argument key="title"/>
85
 *             </argument>
86
 *             <argument key="orderParameterName">order</argument>
87
 *             <tag name="api_platform.filter"/>
88
 *         </service>
89
 *     </services>
90
 * </container>
91
 * <!-- api/config/api_platform/resources.xml -->
92
 * <resources
93
 *         xmlns="https://api-platform.com/schema/metadata/resources-3.0"
94
 *         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
95
 *         xsi:schemaLocation="https://api-platform.com/schema/metadata/resources-3.0
96
 *         https://api-platform.com/schema/metadata/resources-3.0.xsd">
97
 *     <resource class="App\Entity\Book">
98
 *         <operations>
99
 *             <operation class="ApiPlatform\Metadata\GetCollection">
100
 *                 <filters>
101
 *                     <filter>book.order_filter</filter>
102
 *                 </filters>
103
 *             </operation>
104
 *         </operations>
105
 *     </resource>
106
 * </resources>
107
 * ```
108
 *
109
 * </div>
110
 *
111
 * Given that the collection endpoint is `/books`, you can filter books by title in ascending order and then by ID in descending order with the following query: `/books?order[title]=desc&order[id]=asc`.
112
 *
113
 * By default, whenever the query does not specify the direction explicitly (e.g.: `/books?order[title]&order[id]`), filters will not be applied unless you configure a default order direction to use:
114
 *
115
 * <div data-code-selector>
116
 *
117
 * ```php
118
 * <?php
119
 * // api/src/Entity/Book.php
120
 * use ApiPlatform\Metadata\ApiFilter;
121
 * use ApiPlatform\Metadata\ApiResource;
122
 * use ApiPlatform\Doctrine\Odm\Filter\OrderFilter;
123
 *
124
 * #[ApiResource]
125
 * #[ApiFilter(OrderFilter::class, properties: ['id' => 'ASC', 'title' => 'DESC'])]
126
 * class Book
127
 * {
128
 *     // ...
129
 * }
130
 * ```
131
 *
132
 * ```yaml
133
 * # config/services.yaml
134
 * services:
135
 *     book.order_filter:
136
 *         parent: 'api_platform.doctrine.odm.order_filter'
137
 *         arguments: [ { id: ASC, title: DESC } ]
138
 *         tags:  [ 'api_platform.filter' ]
139
 *         # The following are mandatory only if a _defaults section is defined with inverted values.
140
 *         # You may want to isolate filters in a dedicated file to avoid adding the following lines (by adding them in the defaults section)
141
 *         autowire: false
142
 *         autoconfigure: false
143
 *         public: false
144
 *
145
 * # api/config/api_platform/resources.yaml
146
 * resources:
147
 *     App\Entity\Book:
148
 *         - operations:
149
 *               ApiPlatform\Metadata\GetCollection:
150
 *                   filters: ['book.order_filter']
151
 * ```
152
 *
153
 * ```xml
154
 * <?xml version="1.0" encoding="UTF-8" ?>
155
 * <!-- api/config/services.xml -->
156
 * <?xml version="1.0" encoding="UTF-8" ?>
157
 * <container
158
 *         xmlns="http://symfony.com/schema/dic/services"
159
 *         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
160
 *         xsi:schemaLocation="http://symfony.com/schema/dic/services
161
 *         https://symfony.com/schema/dic/services/services-1.0.xsd">
162
 *     <services>
163
 *         <service id="book.order_filter" parent="api_platform.doctrine.odm.order_filter">
164
 *             <argument type="collection">
165
 *                 <argument key="id">ASC</argument>
166
 *                 <argument key="title">DESC</argument>
167
 *             </argument>
168
 *             <tag name="api_platform.filter"/>
169
 *         </service>
170
 *     </services>
171
 * </container>
172
 * <!-- api/config/api_platform/resources.xml -->
173
 * <resources
174
 *         xmlns="https://api-platform.com/schema/metadata/resources-3.0"
175
 *         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
176
 *         xsi:schemaLocation="https://api-platform.com/schema/metadata/resources-3.0
177
 *         https://api-platform.com/schema/metadata/resources-3.0.xsd">
178
 *     <resource class="App\Entity\Book">
179
 *         <operations>
180
 *             <operation class="ApiPlatform\Metadata\GetCollection">
181
 *                 <filters>
182
 *                     <filter>book.order_filter</filter>
183
 *                 </filters>
184
 *             </operation>
185
 *         </operations>
186
 *     </resource>
187
 * </resources>
188
 * ```
189
 *
190
 * </div>
191
 *
192
 * When the property used for ordering can contain `null` values, you may want to specify how `null` values are treated in the comparison:
193
 * - Use the default behavior of the DBMS: use `null` strategy
194
 * - Exclude items: use `ApiPlatform\Doctrine\Odm\Filter\OrderFilter::NULLS_SMALLEST` (`nulls_smallest`) strategy
195
 * - Consider items as oldest: use `ApiPlatform\Doctrine\Odm\Filter\OrderFilter::NULLS_LARGEST` (`nulls_largest`) strategy
196
 * - Consider items as youngest: use `ApiPlatform\Doctrine\Odm\Filter\OrderFilter::NULLS_ALWAYS_FIRST` (`nulls_always_first`) strategy
197
 * - Always include items: use `ApiPlatform\Doctrine\Odm\Filter\OrderFilter::NULLS_ALWAYS_LAST` (`nulls_always_last`) strategy
198
 *
199
 * @author Kévin Dunglas <dunglas@gmail.com>
200
 * @author Théo FIDRY <theo.fidry@gmail.com>
201
 * @author Alan Poulain <contact@alanpoulain.eu>
202
 */
203
final class OrderFilter extends AbstractFilter implements OrderFilterInterface, JsonSchemaFilterInterface, OpenApiParameterFilterInterface
204
{
205
    use OrderFilterTrait;
206
    use PropertyPlaceholderOpenApiParameterTrait;
207

208
    public function __construct(?ManagerRegistry $managerRegistry = null, string $orderParameterName = 'order', ?LoggerInterface $logger = null, ?array $properties = null, ?NameConverterInterface $nameConverter = null)
209
    {
UNCOV
210
        if (null !== $properties) {
307✔
UNCOV
211
            $properties = array_map(static function ($propertyOptions) {
307✔
212
                // shorthand for default direction
UNCOV
213
                if (\is_string($propertyOptions)) {
307✔
UNCOV
214
                    $propertyOptions = [
300✔
UNCOV
215
                        'default_direction' => $propertyOptions,
300✔
UNCOV
216
                    ];
300✔
217
                }
218

UNCOV
219
                return $propertyOptions;
307✔
UNCOV
220
            }, $properties);
307✔
221
        }
222

UNCOV
223
        parent::__construct($managerRegistry, $logger, $properties, $nameConverter);
307✔
224

UNCOV
225
        $this->orderParameterName = $orderParameterName;
307✔
226
    }
227

228
    /**
229
     * {@inheritdoc}
230
     */
231
    public function apply(Builder $aggregationBuilder, string $resourceClass, ?Operation $operation = null, array &$context = []): void
232
    {
233
        if (
UNCOV
234
            isset($context['filters'])
136✔
UNCOV
235
            && (!isset($context['filters'][$this->orderParameterName]) || !\is_array($context['filters'][$this->orderParameterName]))
136✔
UNCOV
236
            && !isset($context['parameter'])
136✔
237
        ) {
UNCOV
238
            return;
115✔
239
        }
240

UNCOV
241
        $parameter = $context['parameter'] ?? null;
21✔
UNCOV
242
        if (null !== ($value = $context['filters'][$parameter?->getProperty()] ?? null)) {
21✔
243
            $this->filterProperty($this->denormalizePropertyName($parameter->getProperty()), $value, $aggregationBuilder, $resourceClass, $operation, $context);
×
244

245
            return;
×
246
        }
247

UNCOV
248
        foreach ($context['filters'][$this->orderParameterName] as $property => $value) {
21✔
UNCOV
249
            $this->filterProperty($this->denormalizePropertyName($property), $value, $aggregationBuilder, $resourceClass, $operation, $context);
21✔
250
        }
251
    }
252

253
    /**
254
     * {@inheritdoc}
255
     */
256
    protected function filterProperty(string $property, $value, Builder $aggregationBuilder, string $resourceClass, ?Operation $operation = null, array &$context = []): void
257
    {
UNCOV
258
        if (!$this->isPropertyEnabled($property, $resourceClass) || !$this->isPropertyMapped($property, $resourceClass)) {
21✔
UNCOV
259
            return;
5✔
260
        }
261

UNCOV
262
        $direction = $this->normalizeValue($value, $property);
17✔
UNCOV
263
        if (null === $direction) {
17✔
264
            return;
×
265
        }
266

UNCOV
267
        $matchField = $property;
17✔
268

UNCOV
269
        if ($this->isPropertyNested($property, $resourceClass)) {
17✔
UNCOV
270
            [$matchField] = $this->addLookupsForNestedProperty($property, $aggregationBuilder, $resourceClass, true);
3✔
271
        }
272

UNCOV
273
        $aggregationBuilder->sort(
17✔
UNCOV
274
            $context['mongodb_odm_sort_fields'] = ($context['mongodb_odm_sort_fields'] ?? []) + [$matchField => $direction]
17✔
UNCOV
275
        );
17✔
276
    }
277

278
    /**
279
     * @return array<string, mixed>
280
     */
281
    public function getSchema(Parameter $parameter): array
282
    {
UNCOV
283
        return ['type' => 'string', 'enum' => ['asc', 'desc']];
1✔
284
    }
285
}
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