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

OrderExtension   A

Complexity

Total Complexity 11

Size/Duplication

Total Lines 52
Duplicated Lines 0 %

Importance

Changes 0
Metric Value
wmc 11
dl 0
loc 52
rs 10
c 0
b 0
f 0

2 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 4 1
D applyToCollection() 0 38 10
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