Completed
Pull Request — 3.x (#844)
by Marko
16:59 queued 14:54
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\Query;
15
use Sonata\AdminBundle\Datagrid\Pager as BasePager;
16
17
/**
18
 * Doctrine pager class.
19
 *
20
 * @author Jonathan H. Wage <[email protected]>
21
 */
22
class Pager extends BasePager
23
{
24
    /**
25
     * NEXT_MAJOR: remove this property.
26
     *
27
     * @deprecated This property is deprecated since version 2.4 and will be removed in 3.0
28
     */
29
    protected $queryBuilder = null;
30
31
    public function computeNbResult()
32
    {
33
        $countQuery = clone $this->getQuery();
34
35
        if (count($this->getParameters()) > 0) {
36
            $countQuery->setParameters($this->getParameters());
37
        }
38
39
        $countQuery->select(sprintf(
40
            'count(%s %s.%s) as cnt',
41
            $countQuery instanceof ProxyQuery && !$countQuery->isDistinct() ? null : 'DISTINCT',
42
            current($countQuery->getRootAliases()),
43
            current($this->getCountColumn())
44
        ));
45
46
        return $countQuery->resetDQLPart('orderBy')->getQuery()->getSingleScalarResult();
47
    }
48
49
    public function getResults($hydrationMode = Query::HYDRATE_OBJECT)
50
    {
51
        return $this->getQuery()->execute([], $hydrationMode);
52
    }
53
54
    public function getQuery()
55
    {
56
        return $this->query;
57
    }
58
59
    public function init()
60
    {
61
        $this->resetIterator();
62
63
        $this->setNbResults($this->computeNbResult());
64
65
        $this->getQuery()->setFirstResult(null);
66
        $this->getQuery()->setMaxResults(null);
67
68
        if (count($this->getParameters()) > 0) {
69
            $this->getQuery()->setParameters($this->getParameters());
70
        }
71
72
        if (0 == $this->getPage() || 0 == $this->getMaxPerPage() || 0 == $this->getNbResults()) {
73
            $this->setLastPage(0);
74
        } else {
75
            $offset = ($this->getPage() - 1) * $this->getMaxPerPage();
76
77
            $this->setLastPage(ceil($this->getNbResults() / $this->getMaxPerPage()));
78
79
            $this->getQuery()->setFirstResult($offset);
80
            $this->getQuery()->setMaxResults($this->getMaxPerPage());
81
        }
82
    }
83
}
84