Completed
Pull Request — 3.x (#844)
by Marko
15:45
created

Pager::appendTreeWalker()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 11

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 11
rs 9.9
c 0
b 0
f 0
cc 2
nc 2
nop 2
1
<?php
2
3
/*
4
 * This file is part of the Sonata Project package.
5
 *
6
 * (c) Thomas Rabaix <[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 Sonata\DoctrineORMAdminBundle\Datagrid;
13
14
use Doctrine\ORM\AbstractQuery;
15
use Doctrine\ORM\Query;
16
use Doctrine\ORM\Tools\Pagination\CountWalker;
17
use Sonata\AdminBundle\Datagrid\Pager as BasePager;
18
19
/**
20
 * Doctrine pager class.
21
 *
22
 * @author Jonathan H. Wage <[email protected]>
23
 */
24
class Pager extends BasePager
25
{
26
    /**
27
     * NEXT_MAJOR: remove this property.
28
     *
29
     * @deprecated This property is deprecated since version 2.4 and will be removed in 3.0
30
     */
31
    protected $queryBuilder = null;
32
33
    public function computeNbResult()
34
    {
35
        $countQuery = clone $this->getQuery();
36
37
        if (count($this->getParameters()) > 0) {
38
            $countQuery->setParameters($this->getParameters());
39
        }
40
41
        $countQuery->select(sprintf(
42
            'count(%s %s.%s) as cnt',
43
            $countQuery instanceof ProxyQuery && !$countQuery->isDistinct() ? null : 'DISTINCT',
44
            current($countQuery->getRootAliases()),
45
            current($this->getCountColumn())
46
        ));
47
48
        return $countQuery->resetDQLPart('orderBy')->getQuery()->getSingleScalarResult();
49
    }
50
51
    public function getResults($hydrationMode = Query::HYDRATE_OBJECT)
52
    {
53
        return $this->getQuery()->execute([], $hydrationMode);
54
    }
55
56
    public function getQuery()
57
    {
58
        return $this->query;
59
    }
60
61
    public function init()
62
    {
63
        $this->resetIterator();
64
65
        $this->setNbResults($this->computeNbResult());
66
67
        $this->getQuery()->setFirstResult(null);
68
        $this->getQuery()->setMaxResults(null);
69
70
        if (count($this->getParameters()) > 0) {
71
            $this->getQuery()->setParameters($this->getParameters());
72
        }
73
74
        if (0 == $this->getPage() || 0 == $this->getMaxPerPage() || 0 == $this->getNbResults()) {
75
            $this->setLastPage(0);
76
        } else {
77
            $offset = ($this->getPage() - 1) * $this->getMaxPerPage();
78
79
            $this->setLastPage(ceil($this->getNbResults() / $this->getMaxPerPage()));
80
81
            $this->getQuery()->setFirstResult($offset);
82
            $this->getQuery()->setMaxResults($this->getMaxPerPage());
83
        }
84
    }
85
}
86