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
|
|
|
$queryBuilder->addOrderBy('o.'.$defaultOrder[0], $defaultOrder[1] ?? 'ASC'); |
49
|
|
|
|
50
|
|
|
return; |
51
|
|
|
} |
52
|
|
|
} |
53
|
|
|
|
54
|
|
|
if (null !== $this->order) { |
55
|
|
|
foreach ($identifiers as $identifier) { |
56
|
|
|
$queryBuilder->addOrderBy('o.'.$identifier, $this->order); |
57
|
|
|
} |
58
|
|
|
} |
59
|
|
|
} |
60
|
|
|
} |
61
|
|
|
|