Pagination.php 13 KB

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