Passed
Pull Request — master (#2789)
by
unknown
05:40
created

php$0 ➔ getResourceClassFromQueryBuilder()   A

Complexity

Conditions 2

Size

Total Lines 5

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 2
dl 0
loc 5
rs 10
c 0
b 0
f 0
1
<?php
2
3
/*
4
 * This file is part of the API Platform project.
5
 *
6
 * (c) Kévin Dunglas <[email protected]>
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\Core\Bridge\Doctrine\Orm\Extension;
15
16
use ApiPlatform\Core\Bridge\Doctrine\Orm\AbstractPaginator;
17
use ApiPlatform\Core\Bridge\Doctrine\Orm\Cache\QueryExpander;
18
use ApiPlatform\Core\Bridge\Doctrine\Orm\Paginator;
19
use ApiPlatform\Core\Bridge\Doctrine\Orm\Util\QueryChecker;
20
use ApiPlatform\Core\Bridge\Doctrine\Orm\Util\QueryNameGeneratorInterface;
21
use ApiPlatform\Core\DataProvider\Pagination;
22
use ApiPlatform\Core\Exception\InvalidArgumentException;
23
use ApiPlatform\Core\Metadata\Resource\Factory\ResourceMetadataFactoryInterface;
24
use ApiPlatform\Core\Metadata\Resource\ResourceMetadata;
25
use Doctrine\Common\Persistence\ManagerRegistry;
26
use Doctrine\ORM\QueryBuilder;
27
use Doctrine\ORM\Tools\Pagination\CountWalker;
28
use Doctrine\ORM\Tools\Pagination\Paginator as DoctrineOrmPaginator;
29
use Symfony\Component\HttpFoundation\Request;
30
use Symfony\Component\HttpFoundation\RequestStack;
31
32
/**
33
 * Applies pagination on the Doctrine query for resource collection when enabled.
34
 *
35
 * @author Kévin Dunglas <[email protected]>
36
 * @author Samuel ROZE <[email protected]>
37
 */
38
final class PaginationExtension implements ContextAwareQueryResultCollectionExtensionInterface
39
{
40
    private $managerRegistry;
41
    private $requestStack;
42
    private $resourceMetadataFactory;
43
    private $enabled;
44
    private $clientEnabled;
45
    private $clientItemsPerPage;
46
    private $itemsPerPage;
47
    private $pageParameterName;
48
    private $enabledParameterName;
49
    private $itemsPerPageParameterName;
50
    private $maximumItemPerPage;
51
    private $partial;
52
    private $clientPartial;
53
    private $partialParameterName;
54
    private $pagination;
55
    private $queryExpander;
56
57
    /**
58
     * @param ResourceMetadataFactoryInterface|RequestStack $resourceMetadataFactory
59
     * @param Pagination|ResourceMetadataFactoryInterface   $pagination
60
     * @param mixed|null                                    $queryExpander
61
     */
62
    public function __construct(ManagerRegistry $managerRegistry, /* ResourceMetadataFactoryInterface */ $resourceMetadataFactory, /* Pagination */ $pagination, /* ?QueryExpander */ $queryExpander = null)
63
    {
64
        if ($resourceMetadataFactory instanceof RequestStack && $pagination instanceof ResourceMetadataFactoryInterface) {
65
            @trigger_error(sprintf('Passing an instance of "%s" as second argument of "%s" is deprecated since API Platform 2.4 and will not be possible anymore in API Platform 3. Pass an instance of "%s" instead.', RequestStack::class, self::class, ResourceMetadataFactoryInterface::class), E_USER_DEPRECATED);
66
            @trigger_error(sprintf('Passing an instance of "%s" as third argument of "%s" is deprecated since API Platform 2.4 and will not be possible anymore in API Platform 3. Pass an instance of "%s" instead.', ResourceMetadataFactoryInterface::class, self::class, Pagination::class), E_USER_DEPRECATED);
67
68
            $this->requestStack = $resourceMetadataFactory;
69
            $resourceMetadataFactory = $pagination;
70
            $pagination = null;
71
72
            $args = \array_slice(\func_get_args(), 4);
73
            $legacyPaginationArgs = [
74
                ['arg_name' => 'enabled', 'type' => 'bool', 'default' => true],
75
                ['arg_name' => 'clientEnabled', 'type' => 'bool', 'default' => false],
76
                ['arg_name' => 'clientItemsPerPage', 'type' => 'bool', 'default' => false],
77
                ['arg_name' => 'itemsPerPage', 'type' => 'int', 'default' => 30],
78
                ['arg_name' => 'pageParameterName', 'type' => 'string', 'default' => 'page'],
79
                ['arg_name' => 'enabledParameterName', 'type' => 'string', 'default' => 'pagination'],
80
                ['arg_name' => 'itemsPerPageParameterName', 'type' => 'string', 'default' => 'itemsPerPage'],
81
                ['arg_name' => 'maximumItemPerPage', 'type' => 'int', 'default' => null],
82
                ['arg_name' => 'partial', 'type' => 'bool', 'default' => false],
83
                ['arg_name' => 'clientPartial', 'type' => 'bool', 'default' => false],
84
                ['arg_name' => 'partialParameterName', 'type' => 'string', 'default' => 'partial'],
85
            ];
86
87
            foreach ($legacyPaginationArgs as $pos => $arg) {
88
                if (\array_key_exists($pos, $args)) {
89
                    @trigger_error(sprintf('Passing "$%s" arguments is deprecated since API Platform 2.4 and will not be possible anymore in API Platform 3. Pass an instance of "%s" as third argument instead.', implode('", "$', array_column($legacyPaginationArgs, 'arg_name')), Paginator::class), E_USER_DEPRECATED);
90
91
                    if (!((null === $arg['default'] && null === $args[$pos]) || \call_user_func("is_{$arg['type']}", $args[$pos]))) {
92
                        throw new InvalidArgumentException(sprintf('The "$%s" argument is expected to be a %s%s.', $arg['arg_name'], $arg['type'], null === $arg['default'] ? ' or null' : ''));
93
                    }
94
95
                    $value = $args[$pos];
96
                } else {
97
                    $value = $arg['default'];
98
                }
99
100
                $this->{$arg['arg_name']} = $value;
101
            }
102
        } elseif (!$resourceMetadataFactory instanceof ResourceMetadataFactoryInterface) {
103
            throw new InvalidArgumentException(sprintf('The "$resourceMetadataFactory" argument is expected to be an implementation of the "%s" interface.', ResourceMetadataFactoryInterface::class));
104
        } elseif (!$pagination instanceof Pagination) {
105
            throw new InvalidArgumentException(sprintf('The "$pagination" argument is expected to be an instance of the "%s" class.', Pagination::class));
106
        }
107
108
        $this->managerRegistry = $managerRegistry;
109
        $this->resourceMetadataFactory = $resourceMetadataFactory;
110
        $this->pagination = $pagination;
111
        $this->queryExpander = $queryExpander;
112
    }
113
114
    /**
115
     * {@inheritdoc}
116
     */
117
    public function applyToCollection(QueryBuilder $queryBuilder, QueryNameGeneratorInterface $queryNameGenerator, string $resourceClass, string $operationName = null, array $context = [])
118
    {
119
        if (null === $pagination = $this->getPagination($queryBuilder, $resourceClass, $operationName, $context)) {
120
            return;
121
        }
122
123
        [$offset, $limit] = $pagination;
124
125
        $queryBuilder
126
            ->setFirstResult($offset)
127
            ->setMaxResults($limit);
128
    }
129
130
    /**
131
     * {@inheritdoc}
132
     */
133
    public function supportsResult(string $resourceClass, string $operationName = null, array $context = []): bool
134
    {
135
        if (null === $this->requestStack) {
136
            return $this->pagination->isEnabled($resourceClass, $operationName, $context);
137
        }
138
139
        if (null === $request = $this->requestStack->getCurrentRequest()) {
140
            return false;
141
        }
142
143
        return $this->isPaginationEnabled($request, $this->resourceMetadataFactory->create($resourceClass), $operationName);
144
    }
145
146
    /**
147
     * {@inheritdoc}
148
     */
149
    public function getResult(QueryBuilder $queryBuilder, string $resourceClass = null, string $operationName = null, array $context = [])
150
    {
151
        $query = $queryBuilder->getQuery();
152
        $queryExpanderResourceClass = $resourceClass ?? $this->getResourceClassFromQueryBuilder($queryBuilder);
153
        if (null !== $this->queryExpander && null !== $queryExpanderResourceClass) {
154
            $this->queryExpander->expand($queryExpanderResourceClass, $query);
155
        }
156
157
        // Only one alias, without joins, disable the DISTINCT on the COUNT
158
        if (1 === \count($queryBuilder->getAllAliases())) {
159
            $query->setHint(CountWalker::HINT_DISTINCT, false);
160
        }
161
162
        $doctrineOrmPaginator = new DoctrineOrmPaginator($query, $this->shouldDoctrinePaginatorFetchJoinCollection($queryBuilder, $resourceClass, $operationName));
163
        $doctrineOrmPaginator->setUseOutputWalkers($this->shouldDoctrinePaginatorUseOutputWalkers($queryBuilder, $resourceClass, $operationName));
164
165
        if (null === $this->requestStack) {
166
            $isPartialEnabled = $this->pagination->isPartialEnabled($resourceClass, $operationName, $context);
167
        } else {
168
            $isPartialEnabled = $this->isPartialPaginationEnabled(
169
                $this->requestStack->getCurrentRequest(),
170
                null === $resourceClass ? null : $this->resourceMetadataFactory->create($resourceClass),
171
                $operationName
172
            );
173
        }
174
175
        if ($isPartialEnabled) {
176
            return new class($doctrineOrmPaginator) extends AbstractPaginator {
177
            };
178
        }
179
180
        return new Paginator($doctrineOrmPaginator);
181
    }
182
183
    /**
184
     * @throws InvalidArgumentException
185
     */
186
    private function getPagination(QueryBuilder $queryBuilder, string $resourceClass, ?string $operationName, array $context): ?array
187
    {
188
        $request = null;
189
        if (null !== $this->requestStack && null === $request = $this->requestStack->getCurrentRequest()) {
190
            return null;
191
        }
192
193
        if (null === $request) {
194
            if (!$this->pagination->isEnabled($resourceClass, $operationName, $context)) {
195
                return null;
196
            }
197
198
            $context = $this->addCountToContext($queryBuilder, $context);
199
200
            return \array_slice($this->pagination->getPagination($resourceClass, $operationName, $context), 1);
201
        }
202
203
        $resourceMetadata = $this->resourceMetadataFactory->create($resourceClass);
204
        if (!$this->isPaginationEnabled($request, $resourceMetadata, $operationName)) {
205
            return null;
206
        }
207
208
        $itemsPerPage = $resourceMetadata->getCollectionOperationAttribute($operationName, 'pagination_items_per_page', $this->itemsPerPage, true);
209
        if ($request->attributes->getBoolean('_graphql', false)) {
210
            $collectionArgs = $request->attributes->get('_graphql_collections_args', []);
211
            $itemsPerPage = $collectionArgs[$resourceClass]['first'] ?? $itemsPerPage;
212
        }
213
214
        if ($resourceMetadata->getCollectionOperationAttribute($operationName, 'pagination_client_items_per_page', $this->clientItemsPerPage, true)) {
215
            $maxItemsPerPage = $resourceMetadata->getCollectionOperationAttribute($operationName, 'maximum_items_per_page', $this->maximumItemPerPage, true);
216
            $itemsPerPage = (int) $this->getPaginationParameter($request, $this->itemsPerPageParameterName, $itemsPerPage);
217
            $itemsPerPage = (null !== $maxItemsPerPage && $itemsPerPage >= $maxItemsPerPage ? $maxItemsPerPage : $itemsPerPage);
218
        }
219
220
        if (0 > $itemsPerPage) {
221
            throw new InvalidArgumentException('Item per page parameter should not be less than 0');
222
        }
223
224
        $page = (int) $this->getPaginationParameter($request, $this->pageParameterName, 1);
225
226
        if (1 > $page) {
227
            throw new InvalidArgumentException('Page should not be less than 1');
228
        }
229
230
        if (0 === $itemsPerPage && 1 < $page) {
231
            throw new InvalidArgumentException('Page should not be greater than 1 if itemsPerPage is equal to 0');
232
        }
233
234
        $firstResult = ($page - 1) * $itemsPerPage;
235
        if ($request->attributes->getBoolean('_graphql', false)) {
236
            $collectionArgs = $request->attributes->get('_graphql_collections_args', []);
237
            if (isset($collectionArgs[$resourceClass]['after'])) {
238
                $after = base64_decode($collectionArgs[$resourceClass]['after'], true);
239
                $firstResult = (int) $after;
240
                $firstResult = false === $after ? $firstResult : ++$firstResult;
241
            }
242
        }
243
244
        return [$firstResult, $itemsPerPage];
245
    }
246
247
    private function getResourceClassFromQueryBuilder(QueryBuilder $queryBuilder): ?string
248
    {
249
        $fromPart = $queryBuilder->getDQLPart('from');
250
        if (1 === \count($fromPart)) {
251
            return $fromPart[0]->getFrom();
252
        }
253
    }
254
255
    private function isPartialPaginationEnabled(Request $request = null, ResourceMetadata $resourceMetadata = null, string $operationName = null): bool
256
    {
257
        $enabled = $this->partial;
258
        $clientEnabled = $this->clientPartial;
259
260
        if ($resourceMetadata) {
261
            $enabled = $resourceMetadata->getCollectionOperationAttribute($operationName, 'pagination_partial', $enabled, true);
262
263
            if ($request) {
264
                $clientEnabled = $resourceMetadata->getCollectionOperationAttribute($operationName, 'pagination_client_partial', $clientEnabled, true);
265
            }
266
        }
267
268
        if ($clientEnabled && $request) {
269
            $enabled = filter_var($this->getPaginationParameter($request, $this->partialParameterName, $enabled), FILTER_VALIDATE_BOOLEAN);
270
        }
271
272
        return $enabled;
273
    }
274
275
    private function isPaginationEnabled(Request $request, ResourceMetadata $resourceMetadata, string $operationName = null): bool
276
    {
277
        $enabled = $resourceMetadata->getCollectionOperationAttribute($operationName, 'pagination_enabled', $this->enabled, true);
278
        $clientEnabled = $resourceMetadata->getCollectionOperationAttribute($operationName, 'pagination_client_enabled', $this->clientEnabled, true);
279
280
        if ($clientEnabled) {
281
            $enabled = filter_var($this->getPaginationParameter($request, $this->enabledParameterName, $enabled), FILTER_VALIDATE_BOOLEAN);
282
        }
283
284
        return $enabled;
285
    }
286
287
    private function getPaginationParameter(Request $request, string $parameterName, $default = null)
288
    {
289
        if (null !== $paginationAttribute = $request->attributes->get('_api_pagination')) {
290
            return \array_key_exists($parameterName, $paginationAttribute) ? $paginationAttribute[$parameterName] : $default;
291
        }
292
293
        return $request->query->get($parameterName, $default);
294
    }
295
296
    private function addCountToContext(QueryBuilder $queryBuilder, array $context): array
297
    {
298
        if (!($context['graphql'] ?? false)) {
299
            return $context;
300
        }
301
302
        if (isset($context['filters']['last']) && !isset($context['filters']['before'])) {
303
            $context['count'] = (new DoctrineOrmPaginator($queryBuilder))->count();
304
        }
305
306
        return $context;
307
    }
308
309
    /**
310
     * Determines the value of the $fetchJoinCollection argument passed to the Doctrine ORM Paginator.
311
     */
312
    private function shouldDoctrinePaginatorFetchJoinCollection(QueryBuilder $queryBuilder, string $resourceClass = null, string $operationName = null): bool
313
    {
314
        if (null !== $resourceClass) {
315
            $resourceMetadata = $this->resourceMetadataFactory->create($resourceClass);
316
317
            if (null !== $fetchJoinCollection = $resourceMetadata->getCollectionOperationAttribute($operationName, 'pagination_fetch_join_collection', null, true)) {
318
                return $fetchJoinCollection;
319
            }
320
        }
321
322
        /*
323
         * "Cannot count query which selects two FROM components, cannot make distinction"
324
         *
325
         * @see https://github.com/doctrine/orm/blob/v2.6.3/lib/Doctrine/ORM/Tools/Pagination/WhereInWalker.php#L81
326
         * @see https://github.com/doctrine/doctrine2/issues/2910
327
         */
328
        if (QueryChecker::hasRootEntityWithCompositeIdentifier($queryBuilder, $this->managerRegistry)) {
329
            return false;
330
        }
331
332
        if (QueryChecker::hasJoinedToManyAssociation($queryBuilder, $this->managerRegistry)) {
333
            return true;
334
        }
335
336
        // disable $fetchJoinCollection by default (performance)
337
        return false;
338
    }
339
340
    /**
341
     * Determines whether the Doctrine ORM Paginator should use output walkers.
342
     */
343
    private function shouldDoctrinePaginatorUseOutputWalkers(QueryBuilder $queryBuilder, string $resourceClass = null, string $operationName = null): bool
344
    {
345
        if (null !== $resourceClass) {
346
            $resourceMetadata = $this->resourceMetadataFactory->create($resourceClass);
347
348
            if (null !== $useOutputWalkers = $resourceMetadata->getCollectionOperationAttribute($operationName, 'pagination_use_output_walkers', null, true)) {
349
                return $useOutputWalkers;
350
            }
351
        }
352
353
        /*
354
         * "Cannot count query that uses a HAVING clause. Use the output walkers for pagination"
355
         *
356
         * @see https://github.com/doctrine/orm/blob/v2.6.3/lib/Doctrine/ORM/Tools/Pagination/CountWalker.php#L56
357
         */
358
        if (QueryChecker::hasHavingClause($queryBuilder)) {
359
            return true;
360
        }
361
362
        /*
363
         * "Cannot count query which selects two FROM components, cannot make distinction"
364
         *
365
         * @see https://github.com/doctrine/orm/blob/v2.6.3/lib/Doctrine/ORM/Tools/Pagination/CountWalker.php#L64
366
         */
367
        if (QueryChecker::hasRootEntityWithCompositeIdentifier($queryBuilder, $this->managerRegistry)) {
368
            return true;
369
        }
370
371
        /*
372
         * "Paginating an entity with foreign key as identifier only works when using the Output Walkers. Call Paginator#setUseOutputWalkers(true) before iterating the paginator."
373
         *
374
         * @see https://github.com/doctrine/orm/blob/v2.6.3/lib/Doctrine/ORM/Tools/Pagination/LimitSubqueryWalker.php#L77
375
         */
376
        if (QueryChecker::hasRootEntityWithForeignKeyIdentifier($queryBuilder, $this->managerRegistry)) {
377
            return true;
378
        }
379
380
        /*
381
         * "Cannot select distinct identifiers from query with LIMIT and ORDER BY on a column from a fetch joined to-many association. Use output walkers."
382
         *
383
         * @see https://github.com/doctrine/orm/blob/v2.6.3/lib/Doctrine/ORM/Tools/Pagination/LimitSubqueryWalker.php#L150
384
         */
385
        if (QueryChecker::hasMaxResults($queryBuilder) && QueryChecker::hasOrderByOnFetchJoinedToManyAssociation($queryBuilder, $this->managerRegistry)) {
386
            return true;
387
        }
388
389
        // Disable output walkers by default (performance)
390
        return false;
391
    }
392
}
393