Completed
Push — master ( b61b75...933b2f )
by joanhey
01:55
created

Paginator::countQuery()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 6
Code Lines 3

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 1
eloc 3
nc 1
nop 2
dl 0
loc 6
rs 9.4285
c 0
b 0
f 0
1
<?php
2
/**
3
 * KumbiaPHP web & app Framework.
4
 *
5
 * LICENSE
6
 *
7
 * This source file is subject to the new BSD license that is bundled
8
 * with this package in the file LICENSE.txt.
9
 * It is also available through the world-wide-web at this URL:
10
 * http://wiki.kumbiaphp.com/Licencia
11
 * If you did not receive a copy of the license and are unable to
12
 * obtain it through the world-wide-web, please send an email
13
 * to [email protected] so we can send you a copy immediately.
14
 *
15
 * @category   Kumbia
16
 *
17
 * @copyright  2005 - 2016  Kumbia Team (http://www.kumbiaphp.com)
18
 * @license    http://wiki.kumbiaphp.com/Licencia     New BSD License
19
 */
20
namespace Kumbia\ActiveRecord;
21
22
/**
23
 * Implementación de paginador.
24
 */
25
class Paginator implements \IteratorAggregate, \Countable, \JsonSerializable
26
{
27
    /**
28
     * Número de página actual.
29
     *
30
     * @var int
31
     */
32
    protected $page;
33
34
    /**
35
     * Cantidad de items por página.
36
     *
37
     * @var int
38
     */
39
    protected $perPage;
40
41
    /**
42
     * Número de páginas totales.
43
     *
44
     * @var int
45
     */
46
    protected $totalPages;
47
48
    /**
49
     * Cantidad de items totales.
50
     *
51
     * @var int
52
     */
53
    protected $count;
54
55
    /**
56
     * Nombre del modelo a usar.
57
     *
58
     * @var string
59
     */
60
    protected $model;
61
62
    /**
63
     * Cadena SQL a ejecutar.
64
     *
65
     * @var string
66
     */
67
    protected $sql;
68
69
    /**
70
     * Párametros de la consulta.
71
     *
72
     * @var array|null
73
     */
74
    protected $values;
75
76
    /**
77
     * Items de pagina.
78
     *
79
     * @var array de objetos
80
     */
81
    private $items;
82
83
    /**
84
     * Constructor.
85
     *
86
     * @param string $model   nombre de clase de modelo
87
     * @param string $sql     consulta select sql
88
     * @param int    $page    numero de pagina
89
     * @param int    $perPage cantidad de items por pagina
90
     * @param mixed  $values  valores
91
     */
92
    public function __construct($model, $sql, $page, $perPage, $values = null)
93
    {
94
        $this->perPage = (int) $perPage;
95
        $this->page = (int) $page;
96
97
        /*validacion*/
98
        $this->validPage();
99
100
        $this->model = $model;
101
102
        // Valores para consulta
103
        $this->values = ($values !== null && !is_array($values)) ?
104
        array_slice(func_get_args(), 4) : $values;
105
106
        $this->count = $this->countQuery($model, $sql);
107
        $this->totalPages = (int) max(1, ceil($this->count / $this->perPage));
108
        $this->validCurrent();
109
        // Establece el limit y offset
110
        $this->sql = QueryGenerator::query($model::getDriver(), 'limit', $sql, $perPage, ($page - 1) * $perPage);
111
        $this->items = $model::query($this->sql, $this->values)->fetchAll();
112
    }
113
114
    /**
115
     * Permite que al usar json_encode() con una instacia de Paginator funcione correctamente
116
     * retornando los items del paginador.
117
     */
118
    public function jsonSerialize()
119
    {
120
        return $this->items;
121
    }
122
123
    /**
124
     * Verifica que la pagina sea válida.
125
     */
126
    private function validPage()
127
    {
128
        //Si la página o por página es menor de 1 (0 o negativo)
129
        if ($this->page < 1 || $this->perPage < 1) {
130
            throw new \RangeException("La página $this->page no existe", 404);
131
        }
132
    }
133
134
    /**
135
     * Valida que la página actual.
136
     */
137
    private function validCurrent()
138
    {
139
        if ($this->page > $this->totalPages) {
140
            throw new \RangeException("La página $this->page no existe", 404);
141
        }
142
    }
143
144
    /**
145
     * (non-PHPdoc).
146
     *
147
     * @see IteratorAggregate::getIterator()
148
     */
149
    public function getIterator()
150
    {
151
        return new \ArrayIterator($this->items);
152
    }
153
154
    /**
155
     * Cuenta el número de resultados totales.
156
     *
157
     * @param string $model
158
     * @param string $sql
159
     *
160
     * @return int total de resultados
161
     */
162
    protected function countQuery($model, $sql)
163
    {
164
        $query = $model::query("SELECT COUNT(*) AS count FROM ($sql) AS t", $this->values)->fetch();
165
166
        return (int) $query->count;
167
    }
168
169
    /**
170
     * Total de items.
171
     *
172
     * @return int
173
     */
174
    public function totalItems()
175
    {
176
        return $this->count;
177
    }
178
179
    /**
180
     * Total de páginas.
181
     *
182
     * @return int
183
     */
184
    public function totalPages()
185
    {
186
        return $this->totalPages;
187
    }
188
189
    /**
190
     * Calcula el valor de la próxima página.
191
     *
192
     * @return int
193
     */
194
    public function nextPage()
195
    {
196
        return ($this->totalPages > $this->page) ? ($this->page + 1) : null;
197
    }
198
199
    /**
200
     * Calcula el valor de la página anterior.
201
     *
202
     * @return int
203
     */
204
    public function prevPage()
205
    {
206
        return ($this->page > 1) ? ($this->page - 1) : null;
207
    }
208
209
    /**
210
     * Items devueltos.
211
     *
212
     * @see Countable::countable()
213
     *
214
     * @return int
215
     */
216
    public function count()
217
    {
218
        return count($this->items);
219
    }
220
221
    /**
222
     * Página actual de paginador.
223
     *
224
     * @return int
225
     */
226
    public function page()
227
    {
228
        return $this->page;
229
    }
230
231
    /**
232
     * Campos del objeto.
233
     *
234
     * @return array
235
     */
236
    public function getFields()
237
    {
238
        return $this->items[0]->getFields();
239
    }
240
241
    /**
242
     * Alias de Campos del objeto.
243
     *
244
     * @return array
245
     */
246
    public function getAlias()
247
    {
248
        return $this->items[0]->getAlias();
249
    }
250
}
251