Paginator.php 9.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413
  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. unset($_GET['page']);
  113. $parameter = http_build_query($_GET);
  114. $parameterUrl = $parameter ? $url . $this->buildFragment() . '&' . $parameter : $url . $this->buildFragment();
  115. return $parameterUrl;
  116. }
  117. /**
  118. * 自动获取当前页码
  119. * @param string $varPage
  120. * @param int $default
  121. * @return int
  122. */
  123. public static function getCurrentPage($varPage = 'page', $default = 1)
  124. {
  125. $page = (int) Request::instance()->param($varPage);
  126. if (filter_var($page, FILTER_VALIDATE_INT) !== false && $page >= 1) {
  127. return $page;
  128. }
  129. return $default;
  130. }
  131. /**
  132. * 自动获取当前的path
  133. * @return string
  134. */
  135. public static function getCurrentPath()
  136. {
  137. return Request::instance()->baseUrl();
  138. }
  139. public function total()
  140. {
  141. if ($this->simple) {
  142. throw new \DomainException('not support total');
  143. }
  144. return $this->total;
  145. }
  146. public function listRows()
  147. {
  148. return $this->listRows;
  149. }
  150. public function currentPage()
  151. {
  152. return $this->currentPage;
  153. }
  154. public function lastPage()
  155. {
  156. if ($this->simple) {
  157. throw new \DomainException('not support last');
  158. }
  159. return $this->lastPage;
  160. }
  161. /**
  162. * 数据是否足够分页
  163. * @return boolean
  164. */
  165. public function hasPages()
  166. {
  167. return !(1 == $this->currentPage && !$this->hasMore);
  168. }
  169. /**
  170. * 创建一组分页链接
  171. *
  172. * @param int $start
  173. * @param int $end
  174. * @return array
  175. */
  176. public function getUrlRange($start, $end)
  177. {
  178. $urls = [];
  179. for ($page = $start; $page <= $end; $page++) {
  180. $urls[$page] = $this->url($page);
  181. }
  182. return $urls;
  183. }
  184. /**
  185. * 设置URL锚点
  186. *
  187. * @param string|null $fragment
  188. * @return $this
  189. */
  190. public function fragment($fragment)
  191. {
  192. $this->options['fragment'] = $fragment;
  193. return $this;
  194. }
  195. /**
  196. * 添加URL参数
  197. *
  198. * @param array|string $key
  199. * @param string|null $value
  200. * @return $this
  201. */
  202. public function appends($key, $value = null)
  203. {
  204. if (!is_array($key)) {
  205. $queries = [$key => $value];
  206. } else {
  207. $queries = $key;
  208. }
  209. foreach ($queries as $k => $v) {
  210. if ($k !== $this->options['var_page']) {
  211. $this->options['query'][$k] = $v;
  212. }
  213. }
  214. return $this;
  215. }
  216. /**
  217. * 构造锚点字符串
  218. *
  219. * @return string
  220. */
  221. protected function buildFragment()
  222. {
  223. return $this->options['fragment'] ? '#' . $this->options['fragment'] : '';
  224. }
  225. /**
  226. * 渲染分页html
  227. * @return mixed
  228. */
  229. abstract public function render();
  230. public function items()
  231. {
  232. return $this->items->all();
  233. }
  234. public function getCollection()
  235. {
  236. return $this->items;
  237. }
  238. public function isEmpty()
  239. {
  240. return $this->items->isEmpty();
  241. }
  242. /**
  243. * 给每个元素执行个回调
  244. *
  245. * @param callable $callback
  246. * @return $this
  247. */
  248. public function each(callable $callback)
  249. {
  250. foreach ($this->items as $key => $item) {
  251. $result = $callback($item, $key);
  252. if (false === $result) {
  253. break;
  254. } elseif (!is_object($item)) {
  255. $this->items[$key] = $result;
  256. }
  257. }
  258. return $this;
  259. }
  260. /**
  261. * Retrieve an external iterator
  262. * @return Traversable An instance of an object implementing <b>Iterator</b> or
  263. * <b>Traversable</b>
  264. */
  265. public function getIterator()
  266. {
  267. return new ArrayIterator($this->items->all());
  268. }
  269. /**
  270. * Whether a offset exists
  271. * @param mixed $offset
  272. * @return bool
  273. */
  274. public function offsetExists($offset)
  275. {
  276. return $this->items->offsetExists($offset);
  277. }
  278. /**
  279. * Offset to retrieve
  280. * @param mixed $offset
  281. * @return mixed
  282. */
  283. public function offsetGet($offset)
  284. {
  285. return $this->items->offsetGet($offset);
  286. }
  287. /**
  288. * Offset to set
  289. * @param mixed $offset
  290. * @param mixed $value
  291. */
  292. public function offsetSet($offset, $value)
  293. {
  294. $this->items->offsetSet($offset, $value);
  295. }
  296. /**
  297. * Offset to unset
  298. * @param mixed $offset
  299. * @return void
  300. * @since 5.0.0
  301. */
  302. public function offsetUnset($offset)
  303. {
  304. $this->items->offsetUnset($offset);
  305. }
  306. /**
  307. * Count elements of an object
  308. */
  309. public function count()
  310. {
  311. return $this->items->count();
  312. }
  313. public function __toString()
  314. {
  315. return (string) $this->render();
  316. }
  317. public function toArray()
  318. {
  319. if ($this->simple) {
  320. return [
  321. 'per_page' => $this->listRows,
  322. 'current_page' => $this->currentPage,
  323. 'has_more' => $this->hasMore,
  324. 'next_item' => $this->nextItem,
  325. 'data' => $this->items->toArray(),
  326. ];
  327. } else {
  328. return [
  329. 'total' => $this->total,
  330. 'per_page' => $this->listRows,
  331. 'current_page' => $this->currentPage,
  332. 'last_page' => $this->lastPage,
  333. 'data' => $this->items->toArray(),
  334. ];
  335. }
  336. }
  337. /**
  338. * Specify data which should be serialized to JSON
  339. */
  340. public function jsonSerialize()
  341. {
  342. return $this->toArray();
  343. }
  344. public function __call($name, $arguments)
  345. {
  346. $collection = $this->getCollection();
  347. $result = call_user_func_array([$collection, $name], $arguments);
  348. if ($result === $collection) {
  349. return $this;
  350. }
  351. return $result;
  352. }
  353. }