summaryrefslogtreecommitdiffstats
path: root/library/Icinga/Web/Paginator/Adapter/QueryAdapter.php
blob: 6f103e5ab7d6c2133c7147bbc7bbfe04fe9a5a06 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
<?php
/* Icinga Web 2 | (c) 2013 Icinga Development Team | GPLv2+ */

namespace Icinga\Web\Paginator\Adapter;

use Zend_Paginator_Adapter_Interface;
use Icinga\Data\QueryInterface;

class QueryAdapter implements Zend_Paginator_Adapter_Interface
{
    /**
     * The query being paginated
     *
     * @var QueryInterface
     */
    protected $query;

    /**
     * Item count
     *
     * @var int
     */
    protected $count;

    /**
     * Create a new QueryAdapter
     *
     * @param   QueryInterface  $query      The query to paginate
     */
    public function __construct(QueryInterface $query)
    {
        $this->setQuery($query);
    }

    /**
     * Set the query to paginate
     *
     * @param   QueryInterface  $query
     *
     * @return  $this
     */
    public function setQuery(QueryInterface $query)
    {
        $this->query = $query;
        return $this;
    }

    /**
     * Return the query being paginated
     *
     * @return  QueryInterface
     */
    public function getQuery()
    {
        return $this->query;
    }

    /**
     * Fetch and return the rows in the given range of the query result
     *
     * @param   int     $offset             Page offset
     * @param   int     $itemCountPerPage   Number of items per page
     *
     * @return  array
     */
    public function getItems($offset, $itemCountPerPage)
    {
        return $this->query->limit($itemCountPerPage, $offset)->fetchAll();
    }

    /**
     * Return the total number of items in the query result
     *
     * @return  int
     */
    public function count(): int
    {
        if ($this->count === null) {
            $this->count = $this->query->count();
        }

        return $this->count;
    }
}