Completed
Pull Request — master (#16756)
by Vladimir
13:05
created

Pagination::createUrl()   C

Complexity

Conditions 11
Paths 192

Size

Total Lines 29

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 18
CRAP Score 11.0176

Importance

Changes 0
Metric Value
dl 0
loc 29
rs 6.55
c 0
b 0
f 0
ccs 18
cts 19
cp 0.9474
cc 11
nc 192
nop 3
crap 11.0176

How to fix   Complexity   

Long Method

Small methods make your code easier to understand, in particular if combined with a good name. Besides, if your method is small, finding a good name is usually much easier.

For example, if you find yourself adding comments to a method's body, this is usually a good sign to extract the commented part to a new method, and use the comment as a starting point when coming up with a good name for this new method.

Commonly applied refactorings include:

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