Completed
Push — gridview-checkboxcolumn ( 5f8435...420708 )
by Dmitry
06:27 queued 20s
created

Pagination   B

Complexity

Total Complexity 46

Size/Duplication

Total Lines 278
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 3

Test Coverage

Coverage 72.28%
Metric Value
wmc 46
lcom 1
cbo 3
dl 0
loc 278
rs 8.3999
ccs 73
cts 101
cp 0.7228

10 Methods

Rating   Name   Duplication   Size   Complexity  
A getPageCount() 0 11 4
A getPage() 0 9 3
B setPage() 0 18 6
A getPageSize() 0 14 3
B setPageSize() 0 16 7
D createUrl() 0 29 11
A getOffset() 0 6 2
A getLimit() 0 6 2
A getLinks() 0 18 3
B getQueryParam() 0 9 5

How to fix   Complexity   

Complex Class

Complex classes like Pagination often do a lot of different things. To break such a class down, we need to identify a cohesive component within that class. A common approach to find such a component is to look for fields/methods that share the same prefixes, or suffixes. You can also have a look at the cohesion graph to spot any un-connected, or weakly-connected components.

Once you have determined the fields that belong together, you can apply the Extract Class refactoring. If the component makes sense as a sub-class, Extract Subclass is also a candidate, and is often faster.

While breaking up the class, it is a good idea to analyze how other classes use Pagination, and based on these observations, apply Extract Interface, too.

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\Object;
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
 * 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
 * @property integer $limit The limit of the data. This may be used to set the LIMIT value for a SQL statement
60
 * for fetching the current page of data. Note that if the page size is infinite, a value -1 will be returned.
61
 * This property is read-only.
62
 * @property array $links The links for navigational purpose. The array keys specify the purpose of the links
63
 * (e.g. [[LINK_FIRST]]), and the array values are the corresponding URLs. This property is read-only.
64
 * @property integer $offset The offset of the data. This may be used to set the OFFSET value for a SQL
65
 * statement for fetching the current page of data. This property is read-only.
66
 * @property integer $page The zero-based current page number.
67
 * @property integer $pageCount Number of pages. This property is read-only.
68
 * @property integer $pageSize The number of items per page. If it is less than 1, it means the page size is
69
 * infinite, and thus a single page contains all items.
70
 *
71
 * @author Qiang Xue <[email protected]>
72
 * @since 2.0
73
 */
74
class Pagination extends Object implements Linkable
75
{
76
    const LINK_NEXT = 'next';
77
    const LINK_PREV = 'prev';
78
    const LINK_FIRST = 'first';
79
    const LINK_LAST = 'last';
80
81
    /**
82
     * @var string name of the parameter storing the current page index.
83
     * @see params
84
     */
85
    public $pageParam = 'page';
86
    /**
87
     * @var string name of the parameter storing the page size.
88
     * @see params
89
     */
90
    public $pageSizeParam = 'per-page';
91
    /**
92
     * @var boolean whether to always have the page parameter in the URL created by [[createUrl()]].
93
     * If false and [[page]] is 0, the page parameter will not be put in the URL.
94
     */
95
    public $forcePageParam = true;
96
    /**
97
     * @var string the route of the controller action for displaying the paged contents.
98
     * If not set, it means using the currently requested route.
99
     */
100
    public $route;
101
    /**
102
     * @var array parameters (name => value) that should be used to obtain the current page number
103
     * and to create new pagination URLs. If not set, all parameters from $_GET will be used instead.
104
     *
105
     * In order to add hash to all links use `array_merge($_GET, ['#' => 'my-hash'])`.
106
     *
107
     * The array element indexed by [[pageParam]] is considered to be the current page number (defaults to 0);
108
     * while the element indexed by [[pageSizeParam]] is treated as the page size (defaults to [[defaultPageSize]]).
109
     */
110
    public $params;
111
    /**
112
     * @var \yii\web\UrlManager the URL manager used for creating pagination URLs. If not set,
113
     * the "urlManager" application component will be used.
114
     */
115
    public $urlManager;
116
    /**
117
     * @var boolean whether to check if [[page]] is within valid range.
118
     * When this property is true, the value of [[page]] will always be between 0 and ([[pageCount]]-1).
119
     * Because [[pageCount]] relies on the correct value of [[totalCount]] which may not be available
120
     * in some cases (e.g. MongoDB), you may want to set this property to be false to disable the page
121
     * number validation. By doing so, [[page]] will return the value indexed by [[pageParam]] in [[params]].
122
     */
123
    public $validatePage = true;
124
    /**
125
     * @var integer total number of items.
126
     */
127
    public $totalCount = 0;
128
    /**
129
     * @var integer 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|boolean the page size limits. The first array element stands for the minimal page size, and the second
135
     * the maximal 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 integer 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
146
    /**
147
     * @return integer number of pages
148
     */
149 28
    public function getPageCount()
150
    {
151 28
        $pageSize = $this->getPageSize();
152 28
        if ($pageSize < 1) {
153
            return $this->totalCount > 0 ? 1 : 0;
154
        } else {
155 28
            $totalCount = $this->totalCount < 0 ? 0 : (int) $this->totalCount;
156
157 28
            return (int) (($totalCount + $pageSize - 1) / $pageSize);
158
        }
159
    }
160
161
    private $_page;
162
163
    /**
164
     * Returns the zero-based current page number.
165
     * @param boolean $recalculate whether to recalculate the current page based on the page size and item count.
166
     * @return integer the zero-based current page number.
167
     */
168 28
    public function getPage($recalculate = false)
169
    {
170 28
        if ($this->_page === null || $recalculate) {
171 26
            $page = (int) $this->getQueryParam($this->pageParam, 1) - 1;
172 26
            $this->setPage($page, true);
173 26
        }
174
175 28
        return $this->_page;
176
    }
177
178
    /**
179
     * Sets the current page number.
180
     * @param integer $value the zero-based index of the current page.
181
     * @param boolean $validatePage whether to validate the page number. Note that in order
182
     * to validate the page number, both [[validatePage]] and this parameter must be true.
183
     */
184 28
    public function setPage($value, $validatePage = false)
185
    {
186 28
        if ($value === null) {
187
            $this->_page = null;
188
        } else {
189 28
            $value = (int) $value;
190 28
            if ($validatePage && $this->validatePage) {
191 27
                $pageCount = $this->getPageCount();
192 27
                if ($value >= $pageCount) {
193 1
                    $value = $pageCount - 1;
194 1
                }
195 27
            }
196 28
            if ($value < 0) {
197
                $value = 0;
198
            }
199 28
            $this->_page = $value;
200
        }
201 28
    }
202
203
    /**
204
     * Returns the number of items per page.
205
     * By default, this method will try to determine the page size by [[pageSizeParam]] in [[params]].
206
     * If the page size cannot be determined this way, [[defaultPageSize]] will be returned.
207
     * @return integer the number of items per page. If it is less than 1, it means the page size is infinite,
208
     * and thus a single page contains all items.
209
     * @see pageSizeLimit
210
     */
211 30
    public function getPageSize()
212
    {
213 30
        if ($this->_pageSize === null) {
214 27
            if (empty($this->pageSizeLimit)) {
215
                $pageSize = $this->defaultPageSize;
216
                $this->setPageSize($pageSize);
217
            } else {
218 27
                $pageSize = (int) $this->getQueryParam($this->pageSizeParam, $this->defaultPageSize);
219 27
                $this->setPageSize($pageSize, true);
220
            }
221 27
        }
222
223 30
        return $this->_pageSize;
224
    }
225
226
    /**
227
     * @param integer $value the number of items per page.
228
     * @param boolean $validatePageSize whether to validate page size.
229
     */
230 30
    public function setPageSize($value, $validatePageSize = false)
231
    {
232 30
        if ($value === null) {
233
            $this->_pageSize = null;
234
        } else {
235 30
            $value = (int) $value;
236 30
            if ($validatePageSize && isset($this->pageSizeLimit[0], $this->pageSizeLimit[1]) && count($this->pageSizeLimit) === 2) {
237 27
                if ($value < $this->pageSizeLimit[0]) {
238
                    $value = $this->pageSizeLimit[0];
239 27
                } elseif ($value > $this->pageSizeLimit[1]) {
240
                    $value = $this->pageSizeLimit[1];
241
                }
242 27
            }
243 30
            $this->_pageSize = $value;
244
        }
245 30
    }
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 integer $page the zero-based page number that the URL should point to.
251
     * @param integer $pageSize the number of items on each page. If not set, the value of [[pageSize]] will be used.
252
     * @param boolean $absolute whether to create an absolute URL. Defaults to `false`.
253
     * @return string the created URL
254
     * @see params
255
     * @see forcePageParam
256
     */
257 4
    public function createUrl($page, $pageSize = null, $absolute = false)
258
    {
259 4
        $page = (int) $page;
260 4
        $pageSize = (int) $pageSize;
261 4
        if (($params = $this->params) === null) {
262 4
            $request = Yii::$app->getRequest();
263 4
            $params = $request instanceof Request ? $request->getQueryParams() : [];
264 4
        }
265 4
        if ($page > 0 || $page >= 0 && $this->forcePageParam) {
266 4
            $params[$this->pageParam] = $page + 1;
267 4
        } else {
268 1
            unset($params[$this->pageParam]);
269
        }
270 4
        if ($pageSize <= 0) {
271 3
            $pageSize = $this->getPageSize();
272 3
        }
273 4
        if ($pageSize != $this->defaultPageSize) {
274 1
            $params[$this->pageSizeParam] = $pageSize;
275 1
        } else {
276 3
            unset($params[$this->pageSizeParam]);
277
        }
278 4
        $params[0] = $this->route === null ? Yii::$app->controller->getRoute() : $this->route;
279 4
        $urlManager = $this->urlManager === null ? Yii::$app->getUrlManager() : $this->urlManager;
280 4
        if ($absolute) {
281
            return $urlManager->createAbsoluteUrl($params);
282
        } else {
283 4
            return $urlManager->createUrl($params);
284
        }
285
    }
286
287
    /**
288
     * @return integer 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 26
    public function getOffset()
292
    {
293 26
        $pageSize = $this->getPageSize();
294
295 26
        return $pageSize < 1 ? 0 : $this->getPage() * $pageSize;
296
    }
297
298
    /**
299
     * @return integer the limit of the data. This may be used to set the
300
     * LIMIT value for a SQL statement for fetching the current page of data.
301
     * Note that if the page size is infinite, a value -1 will be returned.
302
     */
303 26
    public function getLimit()
304
    {
305 26
        $pageSize = $this->getPageSize();
306
307 26
        return $pageSize < 1 ? -1 : $pageSize;
308
    }
309
310
    /**
311
     * Returns a whole set of links for navigating to the first, last, next and previous pages.
312
     * @param boolean $absolute whether the generated URLs should be absolute.
313
     * @return array the links for navigational purpose. The array keys specify the purpose of the links (e.g. [[LINK_FIRST]]),
314
     * and the array values are the corresponding URLs.
315
     */
316
    public function getLinks($absolute = false)
317
    {
318
        $currentPage = $this->getPage();
319
        $pageCount = $this->getPageCount();
320
        $links = [
321
            Link::REL_SELF => $this->createUrl($currentPage, null, $absolute),
322
        ];
323
        if ($currentPage > 0) {
324
            $links[self::LINK_FIRST] = $this->createUrl(0, null, $absolute);
325
            $links[self::LINK_PREV] = $this->createUrl($currentPage - 1, null, $absolute);
326
        }
327
        if ($currentPage < $pageCount - 1) {
328
            $links[self::LINK_NEXT] = $this->createUrl($currentPage + 1, null, $absolute);
329
            $links[self::LINK_LAST] = $this->createUrl($pageCount - 1, null, $absolute);
330
        }
331
332
        return $links;
333
    }
334
335
    /**
336
     * Returns the value of the specified query parameter.
337
     * This method returns the named parameter value from [[params]]. Null is returned if the value does not exist.
338
     * @param string $name the parameter name
339
     * @param string $defaultValue the value to be returned when the specified parameter does not exist in [[params]].
340
     * @return string the parameter value
341
     */
342 29
    protected function getQueryParam($name, $defaultValue = null)
343
    {
344 29
        if (($params = $this->params) === null) {
345 29
            $request = Yii::$app->getRequest();
346 29
            $params = $request instanceof Request ? $request->getQueryParams() : [];
347 29
        }
348
349 29
        return isset($params[$name]) && is_scalar($params[$name]) ? $params[$name] : $defaultValue;
350
    }
351
}
352