Passed
Push — master ( 71fe6e...6a7137 )
by Christian
01:55
created

BaseQueryTrait::addOrder()   A

Complexity

Conditions 3
Paths 3

Size

Total Lines 12
Code Lines 6

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
eloc 6
dl 0
loc 12
rs 10
c 0
b 0
f 0
cc 3
nc 3
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 QueryBuilder              $builder
21
     * @param array<int|string, string> $sort
22
     * @param string                    $defaultAlias
23
     * @param array<string,string>      $aliasMapping
24
     * @param string                    $defaultOrder
25
     *
26
     * @return QueryBuilder
27
     */
28
    final protected function addOrder(QueryBuilder $builder, array $sort, string $defaultAlias, array $aliasMapping = [], string $defaultOrder = 'asc'): QueryBuilder
29
    {
30
        foreach ($sort as $field => $order) {
31
            if (\is_int($field)) {
32
                $field = $order;
33
                $order = $defaultOrder;
34
            }
35
36
            $this->addOrderField($builder, $defaultAlias, $field, $order, $aliasMapping);
37
        }
38
39
        return $builder;
40
    }
41
42
    /**
43
     * @param QueryBuilder $builder
44
     * @param string       $table
45
     * @param string       $field
46
     * @param string       $order
47
     * @param array        $aliasMapping
48
     */
49
    private function addOrderField(QueryBuilder $builder, string $table, string $field, string $order, array $aliasMapping = []): void
50
    {
51
        $fieldSpl = explode('.', $field);
52
53
        if (\count($fieldSpl) > 2) {
54
            throw new InvalidArgumentException(sprintf('The fieldname "%s" cannot contain more than one dot', $field));
55
        }
56
57
        // Map entity to table name
58
        if (2 === \count($fieldSpl)) {
59
            [$table, $field] = $fieldSpl;
60
61
            foreach ($aliasMapping as $k => $v) {
62
                if ($fieldSpl[0] === $k) {
63
                    $table = $v;
64
65
                    break;
66
                }
67
            }
68
        }
69
70
        $builder->addOrderBy($table.'.'.$field, $order);
71
    }
72
}
73