Você não pode selecionar mais de 25 tópicos Os tópicos devem começar com uma letra ou um número, podem incluir traços ('-') e podem ter até 35 caracteres.

352 linhas
13KB

  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. * @property integer $limit The limit of the data. This may be used to set the LIMIT value for a SQL statement
  57. * for fetching the current page of data. Note that if the page size is infinite, a value -1 will be returned.
  58. * This property is read-only.
  59. * @property array $links The links for navigational purpose. The array keys specify the purpose of the links
  60. * (e.g. [[LINK_FIRST]]), and the array values are the corresponding URLs. This property is read-only.
  61. * @property integer $offset The offset of the data. This may be used to set the OFFSET value for a SQL
  62. * statement for fetching the current page of data. This property is read-only.
  63. * @property integer $page The zero-based current page number.
  64. * @property integer $pageCount Number of pages. This property is read-only.
  65. * @property integer $pageSize The number of items per page. If it is less than 1, it means the page size is
  66. * infinite, and thus a single page contains all items.
  67. *
  68. * @author Qiang Xue <qiang.xue@gmail.com>
  69. * @since 2.0
  70. */
  71. class Pagination extends Object implements Linkable
  72. {
  73. const LINK_NEXT = 'next';
  74. const LINK_PREV = 'prev';
  75. const LINK_FIRST = 'first';
  76. const LINK_LAST = 'last';
  77. /**
  78. * @var string name of the parameter storing the current page index.
  79. * @see params
  80. */
  81. public $pageParam = 'page';
  82. /**
  83. * @var string name of the parameter storing the page size.
  84. * @see params
  85. */
  86. public $pageSizeParam = 'per-page';
  87. /**
  88. * @var boolean whether to always have the page parameter in the URL created by [[createUrl()]].
  89. * If false and [[page]] is 0, the page parameter will not be put in the URL.
  90. */
  91. public $forcePageParam = true;
  92. /**
  93. * @var string the route of the controller action for displaying the paged contents.
  94. * If not set, it means using the currently requested route.
  95. */
  96. public $route;
  97. /**
  98. * @var array parameters (name => value) that should be used to obtain the current page number
  99. * and to create new pagination URLs. If not set, all parameters from $_GET will be used instead.
  100. *
  101. * In order to add hash to all links use `array_merge($_GET, ['#' => 'my-hash'])`.
  102. *
  103. * The array element indexed by [[pageParam]] is considered to be the current page number (defaults to 0);
  104. * while the element indexed by [[pageSizeParam]] is treated as the page size (defaults to [[defaultPageSize]]).
  105. */
  106. public $params;
  107. /**
  108. * @var \yii\web\UrlManager the URL manager used for creating pagination URLs. If not set,
  109. * the "urlManager" application component will be used.
  110. */
  111. public $urlManager;
  112. /**
  113. * @var boolean whether to check if [[page]] is within valid range.
  114. * When this property is true, the value of [[page]] will always be between 0 and ([[pageCount]]-1).
  115. * Because [[pageCount]] relies on the correct value of [[totalCount]] which may not be available
  116. * in some cases (e.g. MongoDB), you may want to set this property to be false to disable the page
  117. * number validation. By doing so, [[page]] will return the value indexed by [[pageParam]] in [[params]].
  118. */
  119. public $validatePage = true;
  120. /**
  121. * @var integer total number of items.
  122. */
  123. public $totalCount = 0;
  124. /**
  125. * @var integer the default page size. This property will be returned by [[pageSize]] when page size
  126. * cannot be determined by [[pageSizeParam]] from [[params]].
  127. */
  128. public $defaultPageSize = 20;
  129. /**
  130. * @var array|false the page size limits. The first array element stands for the minimal page size, and the second
  131. * the maximal page size. If this is false, it means [[pageSize]] should always return the value of [[defaultPageSize]].
  132. */
  133. public $pageSizeLimit = [1, 50];
  134. /**
  135. * @var integer number of items on each page.
  136. * If it is less than 1, it means the page size is infinite, and thus a single page contains all items.
  137. */
  138. private $_pageSize;
  139. /**
  140. * @return integer number of pages
  141. */
  142. public function getPageCount()
  143. {
  144. $pageSize = $this->getPageSize();
  145. if ($pageSize < 1) {
  146. return $this->totalCount > 0 ? 1 : 0;
  147. } else {
  148. $totalCount = $this->totalCount < 0 ? 0 : (int) $this->totalCount;
  149. return (int) (($totalCount + $pageSize - 1) / $pageSize);
  150. }
  151. }
  152. private $_page;
  153. /**
  154. * Returns the zero-based current page number.
  155. * @param boolean $recalculate whether to recalculate the current page based on the page size and item count.
  156. * @return integer the zero-based current page number.
  157. */
  158. public function getPage($recalculate = false)
  159. {
  160. if ($this->_page === null || $recalculate) {
  161. $page = (int) $this->getQueryParam($this->pageParam, 1) - 1;
  162. $this->setPage($page, true);
  163. }
  164. return $this->_page;
  165. }
  166. /**
  167. * Sets the current page number.
  168. * @param integer $value the zero-based index of the current page.
  169. * @param boolean $validatePage whether to validate the page number. Note that in order
  170. * to validate the page number, both [[validatePage]] and this parameter must be true.
  171. */
  172. public function setPage($value, $validatePage = false)
  173. {
  174. if ($value === null) {
  175. $this->_page = null;
  176. } else {
  177. $value = (int) $value;
  178. if ($validatePage && $this->validatePage) {
  179. $pageCount = $this->getPageCount();
  180. if ($value >= $pageCount) {
  181. $value = $pageCount - 1;
  182. }
  183. }
  184. if ($value < 0) {
  185. $value = 0;
  186. }
  187. $this->_page = $value;
  188. }
  189. }
  190. /**
  191. * Returns the number of items per page.
  192. * By default, this method will try to determine the page size by [[pageSizeParam]] in [[params]].
  193. * If the page size cannot be determined this way, [[defaultPageSize]] will be returned.
  194. * @return integer the number of items per page. If it is less than 1, it means the page size is infinite,
  195. * and thus a single page contains all items.
  196. * @see pageSizeLimit
  197. */
  198. public function getPageSize()
  199. {
  200. if ($this->_pageSize === null) {
  201. if (empty($this->pageSizeLimit)) {
  202. $pageSize = $this->defaultPageSize;
  203. $this->setPageSize($pageSize);
  204. } else {
  205. $pageSize = (int) $this->getQueryParam($this->pageSizeParam, $this->defaultPageSize);
  206. $this->setPageSize($pageSize, true);
  207. }
  208. }
  209. return $this->_pageSize;
  210. }
  211. /**
  212. * @param integer $value the number of items per page.
  213. * @param boolean $validatePageSize whether to validate page size.
  214. */
  215. public function setPageSize($value, $validatePageSize = false)
  216. {
  217. if ($value === null) {
  218. $this->_pageSize = null;
  219. } else {
  220. $value = (int) $value;
  221. if ($validatePageSize && isset($this->pageSizeLimit[0], $this->pageSizeLimit[1]) && count($this->pageSizeLimit) === 2) {
  222. if ($value < $this->pageSizeLimit[0]) {
  223. $value = $this->pageSizeLimit[0];
  224. } elseif ($value > $this->pageSizeLimit[1]) {
  225. $value = $this->pageSizeLimit[1];
  226. }
  227. }
  228. $this->_pageSize = $value;
  229. }
  230. }
  231. /**
  232. * Creates the URL suitable for pagination with the specified page number.
  233. * This method is mainly called by pagers when creating URLs used to perform pagination.
  234. * @param integer $page the zero-based page number that the URL should point to.
  235. * @param integer $pageSize the number of items on each page. If not set, the value of [[pageSize]] will be used.
  236. * @param boolean $absolute whether to create an absolute URL. Defaults to `false`.
  237. * @return string the created URL
  238. * @see params
  239. * @see forcePageParam
  240. */
  241. public function createUrl($page, $pageSize = null, $absolute = false)
  242. {
  243. $page = (int) $page;
  244. $pageSize = (int) $pageSize;
  245. if (($params = $this->params) === null) {
  246. $request = Yii::$app->getRequest();
  247. $params = $request instanceof Request ? $request->getQueryParams() : [];
  248. }
  249. if ($page > 0 || $page >= 0 && $this->forcePageParam) {
  250. $params[$this->pageParam] = $page + 1;
  251. } else {
  252. unset($params[$this->pageParam]);
  253. }
  254. if ($pageSize <= 0) {
  255. $pageSize = $this->getPageSize();
  256. }
  257. if ($pageSize != $this->defaultPageSize) {
  258. $params[$this->pageSizeParam] = $pageSize;
  259. } else {
  260. unset($params[$this->pageSizeParam]);
  261. }
  262. $params[0] = $this->route === null ? Yii::$app->controller->getRoute() : $this->route;
  263. $urlManager = $this->urlManager === null ? Yii::$app->getUrlManager() : $this->urlManager;
  264. if ($absolute) {
  265. return $urlManager->createAbsoluteUrl($params);
  266. } else {
  267. return $urlManager->createUrl($params);
  268. }
  269. }
  270. /**
  271. * @return integer 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 integer 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 boolean $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. }