Pagination.php 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354
  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\BaseObject;
  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 BaseObject 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. }
  150. $totalCount = $this->totalCount < 0 ? 0 : (int) $this->totalCount;
  151. return (int) (($totalCount + $pageSize - 1) / $pageSize);
  152. }
  153. private $_page;
  154. /**
  155. * Returns the zero-based current page number.
  156. * @param bool $recalculate whether to recalculate the current page based on the page size and item count.
  157. * @return int the zero-based current page number.
  158. */
  159. public function getPage($recalculate = false)
  160. {
  161. if ($this->_page === null || $recalculate) {
  162. $page = (int) $this->getQueryParam($this->pageParam, 1) - 1;
  163. $this->setPage($page, true);
  164. }
  165. return $this->_page;
  166. }
  167. /**
  168. * Sets the current page number.
  169. * @param int $value the zero-based index of the current page.
  170. * @param bool $validatePage whether to validate the page number. Note that in order
  171. * to validate the page number, both [[validatePage]] and this parameter must be true.
  172. */
  173. public function setPage($value, $validatePage = false)
  174. {
  175. if ($value === null) {
  176. $this->_page = null;
  177. } else {
  178. $value = (int) $value;
  179. if ($validatePage && $this->validatePage) {
  180. $pageCount = $this->getPageCount();
  181. if ($value >= $pageCount) {
  182. $value = $pageCount - 1;
  183. }
  184. }
  185. if ($value < 0) {
  186. $value = 0;
  187. }
  188. $this->_page = $value;
  189. }
  190. }
  191. /**
  192. * Returns the number of items per page.
  193. * By default, this method will try to determine the page size by [[pageSizeParam]] in [[params]].
  194. * If the page size cannot be determined this way, [[defaultPageSize]] will be returned.
  195. * @return int the number of items per page. If it is less than 1, it means the page size is infinite,
  196. * and thus a single page contains all items.
  197. * @see pageSizeLimit
  198. */
  199. public function getPageSize()
  200. {
  201. if ($this->_pageSize === null) {
  202. if (empty($this->pageSizeLimit)) {
  203. $pageSize = $this->defaultPageSize;
  204. $this->setPageSize($pageSize);
  205. } else {
  206. $pageSize = (int) $this->getQueryParam($this->pageSizeParam, $this->defaultPageSize);
  207. $this->setPageSize($pageSize, true);
  208. }
  209. }
  210. return $this->_pageSize;
  211. }
  212. /**
  213. * @param int $value the number of items per page.
  214. * @param bool $validatePageSize whether to validate page size.
  215. */
  216. public function setPageSize($value, $validatePageSize = false)
  217. {
  218. if ($value === null) {
  219. $this->_pageSize = null;
  220. } else {
  221. $value = (int) $value;
  222. if ($validatePageSize && isset($this->pageSizeLimit[0], $this->pageSizeLimit[1]) && count($this->pageSizeLimit) === 2) {
  223. if ($value < $this->pageSizeLimit[0]) {
  224. $value = $this->pageSizeLimit[0];
  225. } elseif ($value > $this->pageSizeLimit[1]) {
  226. $value = $this->pageSizeLimit[1];
  227. }
  228. }
  229. $this->_pageSize = $value;
  230. }
  231. }
  232. /**
  233. * Creates the URL suitable for pagination with the specified page number.
  234. * This method is mainly called by pagers when creating URLs used to perform pagination.
  235. * @param int $page the zero-based page number that the URL should point to.
  236. * @param int $pageSize the number of items on each page. If not set, the value of [[pageSize]] will be used.
  237. * @param bool $absolute whether to create an absolute URL. Defaults to `false`.
  238. * @return string the created URL
  239. * @see params
  240. * @see forcePageParam
  241. */
  242. public function createUrl($page, $pageSize = null, $absolute = false)
  243. {
  244. $page = (int) $page;
  245. $pageSize = (int) $pageSize;
  246. if (($params = $this->params) === null) {
  247. $request = Yii::$app->getRequest();
  248. $params = $request instanceof Request ? $request->getQueryParams() : [];
  249. }
  250. if ($page > 0 || $page == 0 && $this->forcePageParam) {
  251. $params[$this->pageParam] = $page + 1;
  252. } else {
  253. unset($params[$this->pageParam]);
  254. }
  255. if ($pageSize <= 0) {
  256. $pageSize = $this->getPageSize();
  257. }
  258. if ($pageSize != $this->defaultPageSize) {
  259. $params[$this->pageSizeParam] = $pageSize;
  260. } else {
  261. unset($params[$this->pageSizeParam]);
  262. }
  263. $params[0] = $this->route === null ? Yii::$app->controller->getRoute() : $this->route;
  264. $urlManager = $this->urlManager === null ? Yii::$app->getUrlManager() : $this->urlManager;
  265. if ($absolute) {
  266. return $urlManager->createAbsoluteUrl($params);
  267. }
  268. return $urlManager->createUrl($params);
  269. }
  270. /**
  271. * @return int the offset of the data. This may be used to set the
  272. * OFFSET value for a SQL statement for fetching the current page of data.
  273. */
  274. public function getOffset()
  275. {
  276. $pageSize = $this->getPageSize();
  277. return $pageSize < 1 ? 0 : $this->getPage() * $pageSize;
  278. }
  279. /**
  280. * @return int the limit of the data. This may be used to set the
  281. * LIMIT value for a SQL statement for fetching the current page of data.
  282. * Note that if the page size is infinite, a value -1 will be returned.
  283. */
  284. public function getLimit()
  285. {
  286. $pageSize = $this->getPageSize();
  287. return $pageSize < 1 ? -1 : $pageSize;
  288. }
  289. /**
  290. * Returns a whole set of links for navigating to the first, last, next and previous pages.
  291. * @param bool $absolute whether the generated URLs should be absolute.
  292. * @return array the links for navigational purpose. The array keys specify the purpose of the links (e.g. [[LINK_FIRST]]),
  293. * and the array values are the corresponding URLs.
  294. */
  295. public function getLinks($absolute = false)
  296. {
  297. $currentPage = $this->getPage();
  298. $pageCount = $this->getPageCount();
  299. $links = [
  300. Link::REL_SELF => $this->createUrl($currentPage, null, $absolute),
  301. ];
  302. if ($currentPage > 0) {
  303. $links[self::LINK_FIRST] = $this->createUrl(0, null, $absolute);
  304. $links[self::LINK_PREV] = $this->createUrl($currentPage - 1, null, $absolute);
  305. }
  306. if ($currentPage < $pageCount - 1) {
  307. $links[self::LINK_NEXT] = $this->createUrl($currentPage + 1, null, $absolute);
  308. $links[self::LINK_LAST] = $this->createUrl($pageCount - 1, null, $absolute);
  309. }
  310. return $links;
  311. }
  312. /**
  313. * Returns the value of the specified query parameter.
  314. * This method returns the named parameter value from [[params]]. Null is returned if the value does not exist.
  315. * @param string $name the parameter name
  316. * @param string $defaultValue the value to be returned when the specified parameter does not exist in [[params]].
  317. * @return string the parameter value
  318. */
  319. protected function getQueryParam($name, $defaultValue = null)
  320. {
  321. if (($params = $this->params) === null) {
  322. $request = Yii::$app->getRequest();
  323. $params = $request instanceof Request ? $request->getQueryParams() : [];
  324. }
  325. return isset($params[$name]) && is_scalar($params[$name]) ? $params[$name] : $defaultValue;
  326. }
  327. }