Completed
Push — 2.0 ( e69d85...2b1775 )
by Kévin
19s
created

OrderExtension   A

Complexity

Total Complexity 4

Size/Duplication

Total Lines 24
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 3

Importance

Changes 0
Metric Value
wmc 4
c 0
b 0
f 0
lcom 1
cbo 3
dl 0
loc 24
rs 10

2 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 4 1
A applyToCollection() 0 11 3
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 Doctrine\ORM\QueryBuilder;
18
19
/**
20
 * Applies selected ordering while querying resource collection.
21
 *
22
 * @author Kévin Dunglas <[email protected]>
23
 * @author Samuel ROZE <[email protected]>
24
 */
25
final class OrderExtension implements QueryCollectionExtensionInterface
26
{
27
    private $order;
28
29
    public function __construct(string $order = null)
30
    {
31
        $this->order = $order;
32
    }
33
34
    /**
35
     * {@inheritdoc}
36
     */
37
    public function applyToCollection(QueryBuilder $queryBuilder, QueryNameGeneratorInterface $queryNameGenerator, string $resourceClass, string $operationName = null)
38
    {
39
        $classMetaData = $queryBuilder->getEntityManager()->getClassMetadata($resourceClass);
40
        $identifiers = $classMetaData->getIdentifier();
41
42
        if (null !== $this->order) {
43
            foreach ($identifiers as $identifier) {
44
                $queryBuilder->addOrderBy('o.'.$identifier, $this->order);
45
            }
46
        }
47
    }
48
}
49