Passed
Push — master ( e9c651...e1baf6 )
by Christian
02:19
created

BaseQueryTrait::addOrder()   B

Complexity

Conditions 7
Paths 11

Size

Total Lines 32
Code Lines 16

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
eloc 16
dl 0
loc 32
rs 8.8333
c 0
b 0
f 0
cc 7
nc 11
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
16
trait BaseQueryTrait
17
{
18
    /**
19
     * @param QueryBuilder              $builder
20
     * @param array<int|string, string> $sort
21
     * @param string                    $defaultEntity
22
     * @param array<string,string>      $aliasMapping
23
     * @param string                    $defaultOrder
24
     *
25
     * @return QueryBuilder
26
     */
27
    final protected function addOrder(QueryBuilder $builder, array $sort, string $defaultEntity, array $aliasMapping = [], string $defaultOrder = 'asc'): QueryBuilder
28
    {
29
        foreach ($sort as $field => $order) {
30
            if (\is_int($field)) {
31
                $field = $order;
32
                $order = $defaultOrder;
33
            }
34
35
            $fieldSpl = explode('.', $field);
36
37
            if (\count($fieldSpl) > 2) {
38
                continue;
39
            }
40
41
            $table = $defaultEntity;
42
43
            // Map entity to table name
44
            if (2 === \count($fieldSpl)) {
45
                foreach ($aliasMapping as $k => $v) {
46
                    if ($fieldSpl[0] === $k) {
47
                        $table = $v;
48
                        $field = $fieldSpl[1];
49
50
                        break;
51
                    }
52
                }
53
            }
54
55
            $builder->addOrderBy($table.'.'.$field, $order);
56
        }
57
58
        return $builder;
59
    }
60
}
61