Paginator.php 9.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409
  1. <?php
  2. // +----------------------------------------------------------------------
  3. // | ThinkPHP [ WE CAN DO IT JUST THINK ]
  4. // +----------------------------------------------------------------------
  5. // | Copyright (c) 2006~2018 http://thinkphp.cn All rights reserved.
  6. // +----------------------------------------------------------------------
  7. // | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
  8. // +----------------------------------------------------------------------
  9. // | Author: zhangyajun <448901948@qq.com>
  10. // +----------------------------------------------------------------------
  11. namespace think;
  12. use ArrayAccess;
  13. use ArrayIterator;
  14. use Countable;
  15. use IteratorAggregate;
  16. use JsonSerializable;
  17. use Traversable;
  18. abstract class Paginator implements ArrayAccess, Countable, IteratorAggregate, JsonSerializable
  19. {
  20. /** @var bool 是否为简洁模式 */
  21. protected $simple = false;
  22. /** @var Collection 数据集 */
  23. protected $items;
  24. /** @var integer 当前页 */
  25. protected $currentPage;
  26. /** @var integer 最后一页 */
  27. protected $lastPage;
  28. /** @var integer|null 数据总数 */
  29. protected $total;
  30. /** @var integer 每页的数量 */
  31. protected $listRows;
  32. /** @var bool 是否有下一页 */
  33. protected $hasMore;
  34. /** @var array 一些配置 */
  35. protected $options = [
  36. 'var_page' => 'page',
  37. 'path' => '/',
  38. 'query' => [],
  39. 'fragment' => '',
  40. ];
  41. /** @var mixed simple模式下的下个元素 */
  42. protected $nextItem;
  43. public function __construct($items, $listRows, $currentPage = null, $total = null, $simple = false, $options = [])
  44. {
  45. $this->options = array_merge($this->options, $options);
  46. $this->options['path'] = '/' != $this->options['path'] ? rtrim($this->options['path'], '/') : $this->options['path'];
  47. $this->simple = $simple;
  48. $this->listRows = $listRows;
  49. if (!$items instanceof Collection) {
  50. $items = Collection::make($items);
  51. }
  52. if ($simple) {
  53. $this->currentPage = $this->setCurrentPage($currentPage);
  54. $this->hasMore = count($items) > ($this->listRows);
  55. if ($this->hasMore) {
  56. $this->nextItem = $items->slice($this->listRows, 1);
  57. }
  58. $items = $items->slice(0, $this->listRows);
  59. } else {
  60. $this->total = $total;
  61. $this->lastPage = (int) ceil($total / $listRows);
  62. $this->currentPage = $this->setCurrentPage($currentPage);
  63. $this->hasMore = $this->currentPage < $this->lastPage;
  64. }
  65. $this->items = $items;
  66. }
  67. /**
  68. * @param $items
  69. * @param $listRows
  70. * @param null $currentPage
  71. * @param bool $simple
  72. * @param null $total
  73. * @param array $options
  74. * @return Paginator
  75. */
  76. public static function make($items, $listRows, $currentPage = null, $total = null, $simple = false, $options = [])
  77. {
  78. return new static($items, $listRows, $currentPage, $total, $simple, $options);
  79. }
  80. protected function setCurrentPage($currentPage)
  81. {
  82. if (!$this->simple && $currentPage > $this->lastPage) {
  83. return $this->lastPage > 0 ? $this->lastPage : 1;
  84. }
  85. return $currentPage;
  86. }
  87. /**
  88. * 获取页码对应的链接
  89. *
  90. * @param $page
  91. * @return string
  92. */
  93. protected function url($page)
  94. {
  95. if ($page <= 0) {
  96. $page = 1;
  97. }
  98. if (strpos($this->options['path'], '[PAGE]') === false) {
  99. $parameters = [$this->options['var_page'] => $page];
  100. $path = $this->options['path'];
  101. } else {
  102. $parameters = [];
  103. $path = str_replace('[PAGE]', $page, $this->options['path']);
  104. }
  105. if (count($this->options['query']) > 0) {
  106. $parameters = array_merge($this->options['query'], $parameters);
  107. }
  108. $url = $path;
  109. if (!empty($parameters)) {
  110. $url .= '?' . http_build_query($parameters, null, '&');
  111. }
  112. return $url . $this->buildFragment();
  113. }
  114. /**
  115. * 自动获取当前页码
  116. * @param string $varPage
  117. * @param int $default
  118. * @return int
  119. */
  120. public static function getCurrentPage($varPage = 'page', $default = 1)
  121. {
  122. $page = (int) Request::instance()->param($varPage);
  123. if (filter_var($page, FILTER_VALIDATE_INT) !== false && $page >= 1) {
  124. return $page;
  125. }
  126. return $default;
  127. }
  128. /**
  129. * 自动获取当前的path
  130. * @return string
  131. */
  132. public static function getCurrentPath()
  133. {
  134. return Request::instance()->baseUrl();
  135. }
  136. public function total()
  137. {
  138. if ($this->simple) {
  139. throw new \DomainException('not support total');
  140. }
  141. return $this->total;
  142. }
  143. public function listRows()
  144. {
  145. return $this->listRows;
  146. }
  147. public function currentPage()
  148. {
  149. return $this->currentPage;
  150. }
  151. public function lastPage()
  152. {
  153. if ($this->simple) {
  154. throw new \DomainException('not support last');
  155. }
  156. return $this->lastPage;
  157. }
  158. /**
  159. * 数据是否足够分页
  160. * @return boolean
  161. */
  162. public function hasPages()
  163. {
  164. return !(1 == $this->currentPage && !$this->hasMore);
  165. }
  166. /**
  167. * 创建一组分页链接
  168. *
  169. * @param int $start
  170. * @param int $end
  171. * @return array
  172. */
  173. public function getUrlRange($start, $end)
  174. {
  175. $urls = [];
  176. for ($page = $start; $page <= $end; $page++) {
  177. $urls[$page] = $this->url($page);
  178. }
  179. return $urls;
  180. }
  181. /**
  182. * 设置URL锚点
  183. *
  184. * @param string|null $fragment
  185. * @return $this
  186. */
  187. public function fragment($fragment)
  188. {
  189. $this->options['fragment'] = $fragment;
  190. return $this;
  191. }
  192. /**
  193. * 添加URL参数
  194. *
  195. * @param array|string $key
  196. * @param string|null $value
  197. * @return $this
  198. */
  199. public function appends($key, $value = null)
  200. {
  201. if (!is_array($key)) {
  202. $queries = [$key => $value];
  203. } else {
  204. $queries = $key;
  205. }
  206. foreach ($queries as $k => $v) {
  207. if ($k !== $this->options['var_page']) {
  208. $this->options['query'][$k] = $v;
  209. }
  210. }
  211. return $this;
  212. }
  213. /**
  214. * 构造锚点字符串
  215. *
  216. * @return string
  217. */
  218. protected function buildFragment()
  219. {
  220. return $this->options['fragment'] ? '#' . $this->options['fragment'] : '';
  221. }
  222. /**
  223. * 渲染分页html
  224. * @return mixed
  225. */
  226. abstract public function render();
  227. public function items()
  228. {
  229. return $this->items->all();
  230. }
  231. public function getCollection()
  232. {
  233. return $this->items;
  234. }
  235. public function isEmpty()
  236. {
  237. return $this->items->isEmpty();
  238. }
  239. /**
  240. * 给每个元素执行个回调
  241. *
  242. * @param callable $callback
  243. * @return $this
  244. */
  245. public function each(callable $callback)
  246. {
  247. foreach ($this->items as $key => $item) {
  248. $result = $callback($item, $key);
  249. if (false === $result) {
  250. break;
  251. } elseif (!is_object($item)) {
  252. $this->items[$key] = $result;
  253. }
  254. }
  255. return $this;
  256. }
  257. /**
  258. * Retrieve an external iterator
  259. * @return Traversable An instance of an object implementing <b>Iterator</b> or
  260. * <b>Traversable</b>
  261. */
  262. public function getIterator()
  263. {
  264. return new ArrayIterator($this->items->all());
  265. }
  266. /**
  267. * Whether a offset exists
  268. * @param mixed $offset
  269. * @return bool
  270. */
  271. public function offsetExists($offset)
  272. {
  273. return $this->items->offsetExists($offset);
  274. }
  275. /**
  276. * Offset to retrieve
  277. * @param mixed $offset
  278. * @return mixed
  279. */
  280. public function offsetGet($offset)
  281. {
  282. return $this->items->offsetGet($offset);
  283. }
  284. /**
  285. * Offset to set
  286. * @param mixed $offset
  287. * @param mixed $value
  288. */
  289. public function offsetSet($offset, $value)
  290. {
  291. $this->items->offsetSet($offset, $value);
  292. }
  293. /**
  294. * Offset to unset
  295. * @param mixed $offset
  296. * @return void
  297. * @since 5.0.0
  298. */
  299. public function offsetUnset($offset)
  300. {
  301. $this->items->offsetUnset($offset);
  302. }
  303. /**
  304. * Count elements of an object
  305. */
  306. public function count()
  307. {
  308. return $this->items->count();
  309. }
  310. public function __toString()
  311. {
  312. return (string) $this->render();
  313. }
  314. public function toArray()
  315. {
  316. if ($this->simple) {
  317. return [
  318. 'per_page' => $this->listRows,
  319. 'current_page' => $this->currentPage,
  320. 'has_more' => $this->hasMore,
  321. 'next_item' => $this->nextItem,
  322. 'data' => $this->items->toArray(),
  323. ];
  324. } else {
  325. return [
  326. 'total' => $this->total,
  327. 'per_page' => $this->listRows,
  328. 'current_page' => $this->currentPage,
  329. 'last_page' => $this->lastPage,
  330. 'data' => $this->items->toArray(),
  331. ];
  332. }
  333. }
  334. /**
  335. * Specify data which should be serialized to JSON
  336. */
  337. public function jsonSerialize()
  338. {
  339. return $this->toArray();
  340. }
  341. public function __call($name, $arguments)
  342. {
  343. $collection = $this->getCollection();
  344. $result = call_user_func_array([$collection, $name], $arguments);
  345. if ($result === $collection) {
  346. return $this;
  347. }
  348. return $result;
  349. }
  350. }