Completed
Pull Request — 2.2 (#1888)
by Han Hui
07:11
created

OrderExtension::applyToCollection()   D

Complexity

Conditions 10
Paths 12

Size

Total Lines 38
Code Lines 23

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 38
rs 4.8196
c 0
b 0
f 0
cc 10
eloc 23
nc 12
nop 5

How to fix   Complexity   

Long Method

Small methods make your code easier to understand, in particular if combined with a good name. Besides, if your method is small, finding a good name is usually much easier.

For example, if you find yourself adding comments to a method's body, this is usually a good sign to extract the commented part to a new method, and use the comment as a starting point when coming up with a good name for this new method.

Commonly applied refactorings include:

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\Util\QueryBuilderHelper;
17
use ApiPlatform\Core\Bridge\Doctrine\Orm\Util\QueryNameGeneratorInterface;
18
use ApiPlatform\Core\Exception\InvalidArgumentException;
19
use ApiPlatform\Core\Metadata\Resource\Factory\ResourceMetadataFactoryInterface;
20
use Doctrine\ORM\QueryBuilder;
21
22
/**
23
 * Applies selected ordering while querying resource collection.
24
 *
25
 * @author Kévin Dunglas <[email protected]>
26
 * @author Samuel ROZE <[email protected]>
27
 * @author Vincent Chalamon <[email protected]>
28
 */
29
final class OrderExtension implements ContextAwareQueryCollectionExtensionInterface
30
{
31
    private $order;
32
    private $resourceMetadataFactory;
33
34
    public function __construct(string $order = null, ResourceMetadataFactoryInterface $resourceMetadataFactory = null)
35
    {
36
        $this->resourceMetadataFactory = $resourceMetadataFactory;
37
        $this->order = $order;
38
    }
39
40
    /**
41
     * {@inheritdoc}
42
     */
43
    public function applyToCollection(QueryBuilder $queryBuilder, QueryNameGeneratorInterface $queryNameGenerator, string $resourceClass = null, string $operationName = null, array $context = [])
44
    {
45
        if (null === $resourceClass) {
46
            throw new InvalidArgumentException('The "$resourceClass" parameter must not be null');
47
        }
48
49
        $rootAlias = $queryBuilder->getRootAliases()[0];
50
51
        $classMetaData = $queryBuilder->getEntityManager()->getClassMetadata($resourceClass);
52
        $identifiers = $classMetaData->getIdentifier();
53
        if (null !== $this->resourceMetadataFactory) {
54
            $defaultOrder = $this->resourceMetadataFactory->create($resourceClass)->getAttribute('order');
55
            if (null !== $defaultOrder) {
56
                foreach ($defaultOrder as $field => $order) {
57
                    if (\is_int($field)) {
58
                        // Default direction
59
                        $field = $order;
60
                        $order = 'ASC';
61
                    }
62
63
                    if (false === ($pos = \strpos($field, '.'))
64
                        || isset($classMetaData->embeddedClasses[\substr($field, 0, $pos)])) {
65
                        // Configure default filter with property
66
                        $field = "{$rootAlias}.{$field}";
67
                    } else {
68
                        $alias = QueryBuilderHelper::addJoinOnce($queryBuilder, $queryNameGenerator, $rootAlias, substr($field, 0, $pos));
69
                        $field = sprintf('%s.%s', $alias, substr($field, $pos + 1));
70
                    }
71
                    $queryBuilder->addOrderBy($field, $order);
72
                }
73
74
                return;
75
            }
76
        }
77
78
        if (null !== $this->order) {
79
            foreach ($identifiers as $identifier) {
80
                $queryBuilder->addOrderBy("{$rootAlias}.{$identifier}", $this->order);
81
            }
82
        }
83
    }
84
}
85