Passed
Push — master ( 46e57d...ec86a4 )
by Christian
01:49
created

BaseQueryTrait::addOrder()   C

Complexity

Conditions 7
Paths 11

Size

Total Lines 32
Code Lines 16

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 32
rs 6.7272
c 0
b 0
f 0
cc 7
eloc 16
nc 11
nop 5
1
<?php
2
3
/*
4
 * (c) Christian Gripp <[email protected]>
5
 *
6
 * For the full copyright and license information, please view the LICENSE
7
 * file that was distributed with this source code.
8
 */
9
10
namespace Core23\DoctrineExtensions\Manager\ORM;
11
12
use Doctrine\ORM\QueryBuilder;
13
use Sonata\DatagridBundle\Pager\Doctrine\Pager;
14
use Sonata\DatagridBundle\Pager\PagerInterface;
15
use Sonata\DatagridBundle\ProxyQuery\Doctrine\ProxyQuery;
16
17
trait BaseQueryTrait
18
{
19
    /**
20
     * Builds a pager for a given query builder.
21
     *
22
     * @param QueryBuilder $builder
23
     * @param int          $limit
24
     * @param int          $page
25
     *
26
     * @return PagerInterface
27
     */
28
    public function createPager(QueryBuilder $builder, int $limit, int $page): PagerInterface
29
    {
30
        $pager = new Pager();
31
        $pager->setMaxPerPage($limit);
32
        $pager->setQuery(new ProxyQuery($builder));
33
        $pager->setPage($page);
34
        $pager->init();
35
36
        return $pager;
37
    }
38
39
    /**
40
     * @param QueryBuilder $builder
41
     * @param array        $sort
42
     * @param string       $defaultEntity
43
     * @param array        $aliasMapping
44
     * @param string       $defaultOrder
45
     *
46
     * @return QueryBuilder
47
     */
48
    public function addOrder(QueryBuilder $builder, array $sort, string $defaultEntity, array $aliasMapping = array(), string $defaultOrder = 'asc'): QueryBuilder
49
    {
50
        foreach ($sort as $field => $order) {
51
            if (is_int($field)) {
52
                $field = $order;
53
                $order = $defaultOrder;
54
            }
55
56
            $fieldSpl = explode('.', $field);
57
58
            if (count($fieldSpl) > 2) {
59
                continue;
60
            }
61
62
            $table = $defaultEntity;
63
64
            // Map entity to table name
65
            if (2 === count($fieldSpl)) {
66
                foreach ($aliasMapping as $k => $v) {
67
                    if ($fieldSpl[0] === $k) {
68
                        $table = $v;
69
                        $field = $fieldSpl[1];
70
71
                        break;
72
                    }
73
                }
74
            }
75
76
            $builder->addOrderBy($table.'.'.$field, $order);
77
        }
78
79
        return $builder;
80
    }
81
}
82