Pager::computeNbResult()   A
last analyzed

Complexity

Conditions 1
Paths 1

Size

Total Lines 4

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 4
rs 10
c 0
b 0
f 0
cc 1
nc 1
nop 0
1
<?php
2
3
declare(strict_types=1);
4
5
/*
6
 * This file is part of the Sonata Project package.
7
 *
8
 * (c) Thomas Rabaix <[email protected]>
9
 *
10
 * For the full copyright and license information, please view the LICENSE
11
 * file that was distributed with this source code.
12
 */
13
14
namespace Sonata\DoctrinePHPCRAdminBundle\Datagrid;
15
16
use Doctrine\ODM\PHPCR\Query\Query as PHPCRQuery;
17
use Sonata\AdminBundle\Datagrid\Pager as BasePager;
18
19
/**
20
 * Doctrine pager class.
21
 *
22
 * @author     Jonathan H. Wage <[email protected]>
23
 * @author     Nacho Martin <[email protected]>
24
 */
25
class Pager extends BasePager
26
{
27
    /**
28
     * Returns a query for counting the total results.
29
     *
30
     * @return int
31
     */
32
    public function computeNbResult()
33
    {
34
        return \count($this->getResults(PHPCRQuery::HYDRATE_PHPCR));
35
    }
36
37
    /**
38
     * Get all the results for the pager instance.
39
     *
40
     * @param mixed $hydrationMode A hydration mode identifier
41
     *
42
     * @return array
43
     */
44
    public function getResults($hydrationMode = null)
45
    {
46
        return $this->getQuery()->execute([], $hydrationMode);
47
    }
48
49
    /**
50
     * Initializes the pager setting the offset and maxResults in ProxyQuery
51
     * and obtaining the total number of pages.
52
     *
53
     * @throws \RuntimeException the QueryBuilder is uninitialized
54
     */
55
    public function init(): void
56
    {
57
        if (!$this->getQuery()) {
58
            throw new \RuntimeException('Uninitialized QueryBuilder');
59
        }
60
61
        $this->resetIterator();
62
        $this->setNbResults($this->computeNbResult());
63
64
        if (0 === $this->getPage() || 0 === $this->getMaxPerPage() || 0 === $this->getNbResults()) {
65
            $this->setLastPage(0);
66
            $this->getQuery()->setFirstResult(0);
67
            $this->getQuery()->setMaxResults(0);
68
        } else {
69
            $offset = ($this->getPage() - 1) * $this->getMaxPerPage();
70
            $this->setLastPage((int) ceil($this->getNbResults() / $this->getMaxPerPage()));
71
            $this->getQuery()->setFirstResult($offset);
72
            $this->getQuery()->setMaxResults($this->getMaxPerPage());
73
        }
74
    }
75
}
76