BaseQueryTrait::addOrderField()   A
last analyzed

Complexity

Conditions 5
Paths 5

Size

Total Lines 22
Code Lines 10

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
eloc 10
c 1
b 0
f 0
dl 0
loc 22
rs 9.6111
cc 5
nc 5
nop 5
1
<?php
2
3
declare(strict_types=1);
4
5
/*
6
 * (c) Christian Gripp <[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
namespace Core23\Doctrine\Manager\ORM;
13
14
use Doctrine\ORM\QueryBuilder;
15
use InvalidArgumentException;
16
17
trait BaseQueryTrait
18
{
19
    /**
20
     * @param array<int|string, string> $sort
21
     * @param array<string, string>     $aliasMapping
22
     */
23
    final protected function addOrder(QueryBuilder $builder, array $sort, string $defaultAlias, array $aliasMapping = [], string $defaultOrder = 'asc'): QueryBuilder
24
    {
25
        foreach ($sort as $field => $order) {
26
            if (\is_int($field)) {
27
                $field = $order;
28
                $order = $defaultOrder;
29
            }
30
31
            $this->addOrderField($builder, $defaultAlias, $field, $order, $aliasMapping);
32
        }
33
34
        return $builder;
35
    }
36
37
    private function addOrderField(QueryBuilder $builder, string $table, string $field, string $order, array $aliasMapping = []): void
38
    {
39
        $fieldSpl = explode('.', $field);
40
41
        if (\count($fieldSpl) > 2) {
42
            throw new InvalidArgumentException(sprintf('The fieldname "%s" cannot contain more than one dot', $field));
43
        }
44
45
        // Map entity to table name
46
        if (2 === \count($fieldSpl)) {
47
            [$table, $field] = $fieldSpl;
48
49
            foreach ($aliasMapping as $k => $v) {
50
                if ($fieldSpl[0] === $k) {
51
                    $table = $v;
52
53
                    break;
54
                }
55
            }
56
        }
57
58
        $builder->addOrderBy($table.'.'.$field, $order);
59
    }
60
}
61