Passed
Pull Request — 2.2 (#20357)
by Wilmer
09:06 queued 16s
created

Pagination::getOffset()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 4
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 3
CRAP Score 2

Importance

Changes 0
Metric Value
cc 2
eloc 2
nc 2
nop 0
dl 0
loc 4
ccs 3
cts 3
cp 1
crap 2
rs 10
c 0
b 0
f 0
1
<?php
2
3
/**
4
 * @link https://www.yiiframework.com/
5
 * @copyright Copyright (c) 2008 Yii Software LLC
6
 * @license https://www.yiiframework.com/license/
7
 */
8
9
namespace yii\data;
10
11
use Closure;
12
use Yii;
13
use yii\base\BaseObject;
14
use yii\web\Link;
15
use yii\web\Linkable;
16
use yii\web\Request;
17
18
/**
19
 * Pagination represents information relevant to pagination of data items.
20
 *
21
 * When data needs to be rendered in multiple pages, Pagination can be used to
22
 * represent information such as [[totalCount|total item count]], [[pageSize|page size]],
23
 * [[page|current page]], etc. These information can be passed to [[\yii\widgets\LinkPager|pagers]]
24
 * to render pagination buttons or links.
25
 *
26
 * The following example shows how to create a pagination object and feed it
27
 * to a pager.
28
 *
29
 * Controller action:
30
 *
31
 * ```php
32
 * public function actionIndex()
33
 * {
34
 *     $query = Article::find()->where(['status' => 1]);
35
 *     $countQuery = clone $query;
36
 *     $pages = new Pagination(['totalCount' => $countQuery->count()]);
37
 *     $models = $query->offset($pages->offset)
38
 *         ->limit($pages->limit)
39
 *         ->all();
40
 *
41
 *     return $this->render('index', [
42
 *          'models' => $models,
43
 *          'pages' => $pages,
44
 *     ]);
45
 * }
46
 * ```
47
 *
48
 * View:
49
 *
50
 * ```php
51
 * foreach ($models as $model) {
52
 *     // display $model here
53
 * }
54
 *
55
 * // display pagination
56
 * echo LinkPager::widget([
57
 *     'pagination' => $pages,
58
 * ]);
59
 * ```
60
 *
61
 * For more details and usage information on Pagination, see the [guide article on pagination](guide:output-pagination).
62
 *
63
 * @property-read int $limit The limit of the data. This may be used to set the LIMIT value for a SQL
64
 * statement for fetching the current page of data. Note that if the page size is infinite, a value -1 will be
65
 * returned.
66
 * @property-read array $links The links for navigational purpose. The array keys specify the purpose of the
67
 * links (e.g. [[LINK_FIRST]]), and the array values are the corresponding URLs.
68
 * @property-read int $offset The offset of the data. This may be used to set the OFFSET value for a SQL
69
 * statement for fetching the current page of data.
70
 * @property int $page The zero-based current page number.
71
 * @property-read int $pageCount Number of pages.
72
 * @property int $pageSize The number of items per page. If it is less than 1, it means the page size is
73
 * infinite, and thus a single page contains all items.
74
 * @property int $totalCount total number of items.
75
 *
76
 * @author Qiang Xue <[email protected]>
77
 * @since 2.0
78
 */
79
class Pagination extends BaseObject implements Linkable
80
{
81
    const LINK_NEXT = 'next';
82
    const LINK_PREV = 'prev';
83
    const LINK_FIRST = 'first';
84
    const LINK_LAST = 'last';
85
86
    /**
87
     * @var string name of the parameter storing the current page index.
88
     * @see params
89
     */
90
    public $pageParam = 'page';
91
    /**
92
     * @var string name of the parameter storing the page size.
93
     * @see params
94
     */
95
    public $pageSizeParam = 'per-page';
96
    /**
97
     * @var bool whether to always have the page parameter in the URL created by [[createUrl()]].
98
     * If false and [[page]] is 0, the page parameter will not be put in the URL.
99
     */
100
    public $forcePageParam = true;
101
    /**
102
     * @var string|null the route of the controller action for displaying the paged contents.
103
     * If not set, it means using the currently requested route.
104
     */
105
    public $route;
106
    /**
107
     * @var array|null parameters (name => value) that should be used to obtain the current page number
108
     * and to create new pagination URLs. If not set, all parameters from $_GET will be used instead.
109
     *
110
     * In order to add hash to all links use `array_merge($_GET, ['#' => 'my-hash'])`.
111
     *
112
     * The array element indexed by [[pageParam]] is considered to be the current page number (defaults to 0);
113
     * while the element indexed by [[pageSizeParam]] is treated as the page size (defaults to [[defaultPageSize]]).
114
     */
115
    public $params;
116
    /**
117
     * @var \yii\web\UrlManager|null the URL manager used for creating pagination URLs. If not set,
118
     * the "urlManager" application component will be used.
119
     */
120
    public $urlManager;
121
    /**
122
     * @var bool whether to check if [[page]] is within valid range.
123
     * When this property is true, the value of [[page]] will always be between 0 and ([[pageCount]]-1).
124
     * Because [[pageCount]] relies on the correct value of [[totalCount]] which may not be available
125
     * in some cases (e.g. MongoDB), you may want to set this property to be false to disable the page
126
     * number validation. By doing so, [[page]] will return the value indexed by [[pageParam]] in [[params]].
127
     */
128
    public $validatePage = true;
129
    /**
130
     * @var int the default page size. This property will be returned by [[pageSize]] when page size
131
     * cannot be determined by [[pageSizeParam]] from [[params]].
132
     */
133
    public $defaultPageSize = 20;
134
    /**
135
     * @var array|false the page size limits. The first array element defines the minimum page size, and the second
136
     * the maximum page size. If this is false, it means [[pageSize]] should always return the value of [[defaultPageSize]].
137
     */
138
    public $pageSizeLimit = [1, 50];
139
140
    /**
141
     * @var int number of items on each page.
142
     * If it is less than 1, it means the page size is infinite, and thus a single page contains all items.
143
     */
144
    private $_pageSize;
145
    /**
146
     * @var Closure|int total number of items or closure returning it.
147
     */
148
    private $_totalCount = 0;
149
150
151
    /**
152
     * @return int number of pages
153
     */
154 89
    public function getPageCount()
155
    {
156 89
        $pageSize = $this->getPageSize();
157 89
        $totalCount = $this->getTotalCount();
158 89
        if ($pageSize < 1) {
159 8
            return $totalCount > 0 ? 1 : 0;
160
        }
161 81
        return (int) ((max($totalCount, 0) + $pageSize - 1) / $pageSize);
162
    }
163
164
    private $_page;
165
166
    /**
167
     * Returns the zero-based current page number.
168
     * @param bool $recalculate whether to recalculate the current page based on the page size and item count.
169
     * @return int the zero-based current page number.
170
     */
171 87
    public function getPage($recalculate = false)
172
    {
173 87
        if ($this->_page === null || $recalculate) {
174 47
            $page = (int) $this->getQueryParam($this->pageParam, 1) - 1;
175 47
            $this->setPage($page, true);
176
        }
177 87
        return $this->_page;
178
    }
179
180
    /**
181
     * Sets the current page number.
182
     * @param int $value the zero-based index of the current page.
183
     * @param bool $validatePage whether to validate the page number. Note that in order
184
     * to validate the page number, both [[validatePage]] and this parameter must be true.
185
     */
186 79
    public function setPage($value, $validatePage = false)
187
    {
188 79
        if ($value === null) {
0 ignored issues
show
introduced by
The condition $value === null is always false.
Loading history...
189 2
            $this->_page = null;
190
        } else {
191 79
            $value = (int) $value;
192 79
            if ($validatePage && $this->validatePage) {
193 62
                $pageCount = $this->getPageCount();
194 62
                if ($value >= $pageCount) {
195 24
                    $value = $pageCount - 1;
196
                }
197
            }
198 79
            if ($value < 0) {
199 21
                $value = 0;
200
            }
201 79
            $this->_page = $value;
202
        }
203
    }
204
205
    /**
206
     * Returns the number of items per page.
207
     * By default, this method will try to determine the page size by [[pageSizeParam]] in [[params]].
208
     * If the page size cannot be determined this way, [[defaultPageSize]] will be returned.
209
     * @return int the number of items per page. If it is less than 1, it means the page size is infinite,
210
     * and thus a single page contains all items.
211
     * @see pageSizeLimit
212
     */
213 123
    public function getPageSize()
214
    {
215 123
        if ($this->_pageSize === null) {
216 74
            if (empty($this->pageSizeLimit) || !isset($this->pageSizeLimit[0], $this->pageSizeLimit[1])) {
217 6
                $pageSize = $this->defaultPageSize;
218 6
                $this->setPageSize($pageSize);
219
            } else {
220 68
                $pageSize = (int) $this->getQueryParam($this->pageSizeParam, $this->defaultPageSize);
221 68
                $this->setPageSize($pageSize, true);
222
            }
223
        }
224 123
        return $this->_pageSize;
225
    }
226
227
    /**
228
     * @param int $value the number of items per page.
229
     * @param bool $validatePageSize whether to validate page size.
230
     */
231 113
    public function setPageSize($value, $validatePageSize = false)
232
    {
233 113
        if ($value === null) {
0 ignored issues
show
introduced by
The condition $value === null is always false.
Loading history...
234 4
            $this->_pageSize = null;
235
        } else {
236 113
            $value = (int) $value;
237 113
            if ($validatePageSize && isset($this->pageSizeLimit[0], $this->pageSizeLimit[1])) {
238 71
                if ($value < $this->pageSizeLimit[0]) {
239 2
                    $value = $this->pageSizeLimit[0];
240 69
                } elseif ($value > $this->pageSizeLimit[1]) {
241 2
                    $value = $this->pageSizeLimit[1];
242
                }
243
            }
244 113
            $this->_pageSize = $value;
245
        }
246
    }
247
248
    /**
249
     * Creates the URL suitable for pagination with the specified page number.
250
     * This method is mainly called by pagers when creating URLs used to perform pagination.
251
     * @param int $page the zero-based page number that the URL should point to.
252
     * @param int|null $pageSize the number of items on each page. If not set, the value of [[pageSize]] will be used.
253
     * @param bool $absolute whether to create an absolute URL. Defaults to `false`.
254
     * @return string the created URL
255
     * @see params
256
     * @see forcePageParam
257
     */
258 35
    public function createUrl($page, $pageSize = null, $absolute = false)
259
    {
260 35
        $page = (int) $page;
261 35
        $pageSize = (int) $pageSize;
262 35
        if (($params = $this->params) === null) {
263 32
            $request = Yii::$app->getRequest();
264 32
            $params = $request instanceof Request ? $request->getQueryParams() : [];
265
        }
266 35
        if ($page > 0 || ($page === 0 && $this->forcePageParam)) {
267 35
            $params[$this->pageParam] = $page + 1;
268
        } else {
269 1
            unset($params[$this->pageParam]);
270
        }
271 35
        if ($pageSize <= 0) {
272 32
            $pageSize = $this->getPageSize();
273
        }
274 35
        if ($pageSize != $this->defaultPageSize) {
275 22
            $params[$this->pageSizeParam] = $pageSize;
276
        } else {
277 13
            unset($params[$this->pageSizeParam]);
278
        }
279 35
        $params[0] = $this->route === null ? Yii::$app->controller->getRoute() : $this->route;
280 35
        $urlManager = $this->urlManager === null ? Yii::$app->getUrlManager() : $this->urlManager;
281 35
        if ($absolute) {
282 14
            return $urlManager->createAbsoluteUrl($params);
283
        }
284 21
        return $urlManager->createUrl($params);
285
    }
286
287
    /**
288
     * @return int the offset of the data. This may be used to set the
289
     * OFFSET value for a SQL statement for fetching the current page of data.
290
     */
291 58
    public function getOffset()
292
    {
293 58
        $pageSize = $this->getPageSize();
294 58
        return $pageSize < 1 ? 0 : $this->getPage() * $pageSize;
295
    }
296
297
    /**
298
     * @return int the limit of the data. This may be used to set the
299
     * LIMIT value for a SQL statement for fetching the current page of data.
300
     * Note that if the page size is infinite, a value -1 will be returned.
301
     */
302 56
    public function getLimit()
303
    {
304 56
        $pageSize = $this->getPageSize();
305 56
        return $pageSize < 1 ? -1 : $pageSize;
306
    }
307
308
    /**
309
     * Returns a whole set of links for navigating to the first, last, next and previous pages.
310
     * @param bool $absolute whether the generated URLs should be absolute.
311
     * @return array the links for navigational purpose. The array keys specify the purpose of the links (e.g. [[LINK_FIRST]]),
312
     * and the array values are the corresponding URLs.
313
     */
314 22
    public function getLinks($absolute = false)
315
    {
316 22
        $currentPage = $this->getPage();
317 22
        $pageCount = $this->getPageCount();
318
319 22
        $links = [Link::REL_SELF => $this->createUrl($currentPage, null, $absolute)];
320 22
        if ($pageCount > 0) {
321 19
            $links[self::LINK_FIRST] = $this->createUrl(0, null, $absolute);
322 19
            $links[self::LINK_LAST] = $this->createUrl($pageCount - 1, null, $absolute);
323 19
            if ($currentPage > 0) {
324 10
                $links[self::LINK_PREV] = $this->createUrl($currentPage - 1, null, $absolute);
325
            }
326 19
            if ($currentPage < $pageCount - 1) {
327 4
                $links[self::LINK_NEXT] = $this->createUrl($currentPage + 1, null, $absolute);
328
            }
329
        }
330 22
        return $links;
331
    }
332
333
    /**
334
     * Returns the value of the specified query parameter.
335
     * This method returns the named parameter value from [[params]]. Null is returned if the value does not exist.
336
     * @param string $name the parameter name
337
     * @param string|null $defaultValue the value to be returned when the specified parameter does not exist in [[params]].
338
     * @return string|null the parameter value
339
     */
340 70
    protected function getQueryParam($name, $defaultValue = null)
341
    {
342 70
        if (($params = $this->params) === null) {
343 65
            $request = Yii::$app->getRequest();
344 65
            $params = $request instanceof Request ? $request->getQueryParams() : [];
345
        }
346 70
        return isset($params[$name]) && is_scalar($params[$name]) ? $params[$name] : $defaultValue;
347
    }
348
349
    /**
350
     * @return int total number of items.
351
     */
352 89
    public function getTotalCount()
353
    {
354 89
        if (is_numeric($this->_totalCount)) {
355 35
            return (int)$this->_totalCount;
356
        }
357 54
        return (int)call_user_func($this->_totalCount);
358
    }
359
360
    /**
361
     * @param Closure|int $count
362
     */
363 85
    public function setTotalCount($count)
364
    {
365 85
        $this->_totalCount = $count;
366
    }
367
}
368