Paginator::validPage()   A
last analyzed

Complexity

Conditions 3
Paths 2

Size

Total Lines 7

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 3
nc 2
nop 0
dl 0
loc 7
rs 10
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 - 2020  Kumbia Team (http://www.kumbiaphp.com)
18
 * @license    http://wiki.kumbiaphp.com/Licencia     New BSD License
19
 */
20
21
namespace Kumbia\ActiveRecord;
22
23
/**
24
 * Implementación de paginador.
25
 */
26
class Paginator implements \IteratorAggregate, \Countable, \JsonSerializable
27
{
28
    /**
29
     * Número de página actual.
30
     *
31
     * @var int
32
     */
33
    protected $page;
34
35
    /**
36
     * Cantidad de items por página.
37
     *
38
     * @var int
39
     */
40
    protected $perPage;
41
42
    /**
43
     * Número de páginas totales.
44
     *
45
     * @var int
46
     */
47
    protected $totalPages;
48
49
    /**
50
     * Cantidad de items totales.
51
     *
52
     * @var int
53
     */
54
    protected $count;
55
56
    /**
57
     * Nombre del modelo a usar.
58
     *
59
     * @var string
60
     */
61
    protected $model;
62
63
    /**
64
     * Cadena SQL a ejecutar.
65
     *
66
     * @var string
67
     */
68
    protected $sql;
69
70
    /**
71
     * Párametros de la consulta.
72
     *
73
     * @var array
74
     */
75
    protected $values;
76
77
    /**
78
     * Items de pagina.
79
     *
80
     * @var array de objetos
81
     */
82
    private $items;
83
84
    /**
85
     * Constructor.
86
     *
87
     * @param string $model   nombre de clase de modelo
88
     * @param string $sql     consulta select sql
89
     * @param int    $page    numero de pagina
90
     * @param int    $perPage cantidad de items por pagina
91
     * @param mixed  $values  valores
92
     */
93
    public function __construct(string $model, string $sql, int $page, int $perPage, array $values = [])
94
    {
95
        $this->perPage = $perPage;
96
        $this->page    = $page;
97
98
        /*validacion*/
99
        $this->validPage();
100
101
        $this->model = $model;
102
103
        // Valores para consulta
104
        $this->values = $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(): void
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(): void
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(): \ArrayIterator
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(string $model, string $sql): int
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(): int
175
    {
176
        return $this->count;
177
    }
178
179
    /**
180
     * Total de páginas.
181
     *
182
     * @return int
183
     */
184
    public function totalPages(): int
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(): int
195
    {
196
        return $this->totalPages > $this->page ? $this->page + 1 : 0;
197
    }
198
199
    /**
200
     * Calcula el valor de la página anterior.
201
     *
202
     * @return int
203
     */
204
    public function prevPage(): int
205
    {
206
        return $this->page > 1 ? $this->page - 1 : 0;
207
    }
208
209
    /**
210
     * Items devueltos.
211
     *
212
     * @see Countable::countable()
213
     *
214
     * @return int
215
     */
216
    public function count(): int
217
    {
218
        return count($this->items);
219
    }
220
221
    /**
222
     * Página actual de paginador.
223
     *
224
     * @return int
225
     */
226
    public function page(): int
227
    {
228
        return $this->page;
229
    }
230
231
    /**
232
     * Campos del objeto.
233
     *
234
     * @return string[]
235
     */
236
    public function getFields(): array
237
    {
238
        return $this->items[0]->getFields();
239
    }
240
241
    /**
242
     * Alias de Campos del objeto.
243
     *
244
     * @return string[]
245
     */
246
    public function getAlias(): array
247
    {
248
        return $this->items[0]->getAlias();
249
    }
250
}
251