Completed
Push — master ( f6ccff...fc822b )
by Kévin
03:05
created

OrderExtension::applyToCollection()   C

Complexity

Conditions 7
Paths 9

Size

Total Lines 25
Code Lines 15

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 25
rs 6.7272
c 0
b 0
f 0
cc 7
eloc 15
nc 9
nop 4
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\QueryNameGeneratorInterface;
17
use ApiPlatform\Core\Metadata\Resource\Factory\ResourceMetadataFactoryInterface;
18
use Doctrine\ORM\QueryBuilder;
19
20
/**
21
 * Applies selected ordering while querying resource collection.
22
 *
23
 * @author Kévin Dunglas <[email protected]>
24
 * @author Samuel ROZE <[email protected]>
25
 * @author Vincent Chalamon <[email protected]>
26
 */
27
final class OrderExtension implements QueryCollectionExtensionInterface
28
{
29
    private $order;
30
    private $resourceMetadataFactory;
31
32
    public function __construct(string $order = null, ResourceMetadataFactoryInterface $resourceMetadataFactory = null)
33
    {
34
        $this->resourceMetadataFactory = $resourceMetadataFactory;
35
        $this->order = $order;
36
    }
37
38
    /**
39
     * {@inheritdoc}
40
     */
41
    public function applyToCollection(QueryBuilder $queryBuilder, QueryNameGeneratorInterface $queryNameGenerator, string $resourceClass, string $operationName = null)
42
    {
43
        $classMetaData = $queryBuilder->getEntityManager()->getClassMetadata($resourceClass);
44
        $identifiers = $classMetaData->getIdentifier();
45
        if (null !== $this->resourceMetadataFactory) {
46
            $defaultOrder = $this->resourceMetadataFactory->create($resourceClass)->getAttribute('order');
47
            if (null !== $defaultOrder) {
48
                foreach ($defaultOrder as $field => $order) {
49
                    if (is_int($field)) {
50
                        $field = $order;
51
                        $order = 'ASC';
52
                    }
53
                    $queryBuilder->addOrderBy('o.'.$field, $order);
54
                }
55
56
                return;
57
            }
58
        }
59
60
        if (null !== $this->order) {
61
            foreach ($identifiers as $identifier) {
62
                $queryBuilder->addOrderBy('o.'.$identifier, $this->order);
63
            }
64
        }
65
    }
66
}
67