Passed
Push — master ( f1ac78...3fa2d6 )
by Alexander
18:02 queued 09:02
created

Pagination::getTotalCount()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 6
Code Lines 3

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 4
CRAP Score 2

Importance

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