Paginator.php 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432
  1. <?php
  2. /**
  3. * CakePHP(tm) : Rapid Development Framework (http://cakephp.org)
  4. * Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org)
  5. *
  6. * Licensed under The MIT License
  7. * For full copyright and license information, please see the LICENSE.txt
  8. * Redistributions of files must retain the above copyright notice.
  9. *
  10. * @copyright Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org)
  11. * @link http://cakephp.org CakePHP(tm) Project
  12. * @since 3.5.0
  13. * @license http://www.opensource.org/licenses/mit-license.php MIT License
  14. */
  15. namespace Cake\Datasource;
  16. use Cake\Core\InstanceConfigTrait;
  17. use Cake\Datasource\Exception\PageOutOfBoundsException;
  18. /**
  19. * This class is used to handle automatic model data pagination.
  20. */
  21. class Paginator implements PaginatorInterface
  22. {
  23. use InstanceConfigTrait;
  24. /**
  25. * Default pagination settings.
  26. *
  27. * When calling paginate() these settings will be merged with the configuration
  28. * you provide.
  29. *
  30. * - `maxLimit` - The maximum limit users can choose to view. Defaults to 100
  31. * - `limit` - The initial number of items per page. Defaults to 20.
  32. * - `page` - The starting page, defaults to 1.
  33. * - `whitelist` - A list of parameters users are allowed to set using request
  34. * parameters. Modifying this list will allow users to have more influence
  35. * over pagination, be careful with what you permit.
  36. *
  37. * @var array
  38. */
  39. protected $_defaultConfig = [
  40. 'page' => 1,
  41. 'limit' => 20,
  42. 'maxLimit' => 100,
  43. 'whitelist' => ['limit', 'sort', 'page', 'direction']
  44. ];
  45. /**
  46. * Paging params after pagination operation is done.
  47. *
  48. * @var array
  49. */
  50. protected $_pagingParams = [];
  51. /**
  52. * Handles automatic pagination of model records.
  53. *
  54. * ### Configuring pagination
  55. *
  56. * When calling `paginate()` you can use the $settings parameter to pass in
  57. * pagination settings. These settings are used to build the queries made
  58. * and control other pagination settings.
  59. *
  60. * If your settings contain a key with the current table's alias. The data
  61. * inside that key will be used. Otherwise the top level configuration will
  62. * be used.
  63. *
  64. * ```
  65. * $settings = [
  66. * 'limit' => 20,
  67. * 'maxLimit' => 100
  68. * ];
  69. * $results = $paginator->paginate($table, $settings);
  70. * ```
  71. *
  72. * The above settings will be used to paginate any repository. You can configure
  73. * repository specific settings by keying the settings with the repository alias.
  74. *
  75. * ```
  76. * $settings = [
  77. * 'Articles' => [
  78. * 'limit' => 20,
  79. * 'maxLimit' => 100
  80. * ],
  81. * 'Comments' => [ ... ]
  82. * ];
  83. * $results = $paginator->paginate($table, $settings);
  84. * ```
  85. *
  86. * This would allow you to have different pagination settings for
  87. * `Articles` and `Comments` repositories.
  88. *
  89. * ### Controlling sort fields
  90. *
  91. * By default CakePHP will automatically allow sorting on any column on the
  92. * repository object being paginated. Often times you will want to allow
  93. * sorting on either associated columns or calculated fields. In these cases
  94. * you will need to define a whitelist of all the columns you wish to allow
  95. * sorting on. You can define the whitelist in the `$settings` parameter:
  96. *
  97. * ```
  98. * $settings = [
  99. * 'Articles' => [
  100. * 'finder' => 'custom',
  101. * 'sortWhitelist' => ['title', 'author_id', 'comment_count'],
  102. * ]
  103. * ];
  104. * ```
  105. *
  106. * Passing an empty array as whitelist disallows sorting altogether.
  107. *
  108. * ### Paginating with custom finders
  109. *
  110. * You can paginate with any find type defined on your table using the
  111. * `finder` option.
  112. *
  113. * ```
  114. * $settings = [
  115. * 'Articles' => [
  116. * 'finder' => 'popular'
  117. * ]
  118. * ];
  119. * $results = $paginator->paginate($table, $settings);
  120. * ```
  121. *
  122. * Would paginate using the `find('popular')` method.
  123. *
  124. * You can also pass an already created instance of a query to this method:
  125. *
  126. * ```
  127. * $query = $this->Articles->find('popular')->matching('Tags', function ($q) {
  128. * return $q->where(['name' => 'CakePHP'])
  129. * });
  130. * $results = $paginator->paginate($query);
  131. * ```
  132. *
  133. * ### Scoping Request parameters
  134. *
  135. * By using request parameter scopes you can paginate multiple queries in
  136. * the same controller action:
  137. *
  138. * ```
  139. * $articles = $paginator->paginate($articlesQuery, ['scope' => 'articles']);
  140. * $tags = $paginator->paginate($tagsQuery, ['scope' => 'tags']);
  141. * ```
  142. *
  143. * Each of the above queries will use different query string parameter sets
  144. * for pagination data. An example URL paginating both results would be:
  145. *
  146. * ```
  147. * /dashboard?articles[page]=1&tags[page]=2
  148. * ```
  149. *
  150. * @param \Cake\Datasource\RepositoryInterface|\Cake\Datasource\QueryInterface $object The table or query to paginate.
  151. * @param array $params Request params
  152. * @param array $settings The settings/configuration used for pagination.
  153. * @return \Cake\Datasource\ResultSetInterface Query results
  154. * @throws \Cake\ORM\Exception\PageOutOfBoundsException
  155. */
  156. public function paginate($object, array $params = [], array $settings = [])
  157. {
  158. $query = null;
  159. if ($object instanceof QueryInterface) {
  160. $query = $object;
  161. $object = $query->repository();
  162. }
  163. $alias = $object->alias();
  164. $defaults = $this->getDefaults($alias, $settings);
  165. $options = $this->mergeOptions($params, $defaults);
  166. $options = $this->validateSort($object, $options);
  167. $options = $this->checkLimit($options);
  168. $options += ['page' => 1, 'scope' => null];
  169. $options['page'] = (int)$options['page'] < 1 ? 1 : (int)$options['page'];
  170. list($finder, $options) = $this->_extractFinder($options);
  171. if (empty($query)) {
  172. $query = $object->find($finder, $options);
  173. } else {
  174. $query->applyOptions($options);
  175. }
  176. $cleanQuery = clone $query;
  177. $results = $query->all();
  178. $numResults = count($results);
  179. $count = $numResults ? $cleanQuery->count() : 0;
  180. $page = $options['page'];
  181. $limit = $options['limit'];
  182. $pageCount = (int)ceil($count / $limit);
  183. $requestedPage = $page;
  184. $page = max(min($page, $pageCount), 1);
  185. $order = (array)$options['order'];
  186. $sortDefault = $directionDefault = false;
  187. if (!empty($defaults['order']) && count($defaults['order']) == 1) {
  188. $sortDefault = key($defaults['order']);
  189. $directionDefault = current($defaults['order']);
  190. }
  191. $paging = [
  192. 'finder' => $finder,
  193. 'page' => $page,
  194. 'current' => $numResults,
  195. 'count' => $count,
  196. 'perPage' => $limit,
  197. 'prevPage' => $page > 1,
  198. 'nextPage' => $count > ($page * $limit),
  199. 'pageCount' => $pageCount,
  200. 'sort' => key($order),
  201. 'direction' => current($order),
  202. 'limit' => $defaults['limit'] != $limit ? $limit : null,
  203. 'sortDefault' => $sortDefault,
  204. 'directionDefault' => $directionDefault,
  205. 'scope' => $options['scope'],
  206. ];
  207. $this->_pagingParams = [$alias => $paging];
  208. if ($requestedPage > $page) {
  209. throw new PageOutOfBoundsException([$requestedPage]);
  210. }
  211. return $results;
  212. }
  213. /**
  214. * Extracts the finder name and options out of the provided pagination options.
  215. *
  216. * @param array $options the pagination options.
  217. * @return array An array containing in the first position the finder name
  218. * and in the second the options to be passed to it.
  219. */
  220. protected function _extractFinder($options)
  221. {
  222. $type = !empty($options['finder']) ? $options['finder'] : 'all';
  223. unset($options['finder'], $options['maxLimit']);
  224. if (is_array($type)) {
  225. $options = (array)current($type) + $options;
  226. $type = key($type);
  227. }
  228. return [$type, $options];
  229. }
  230. /**
  231. * Get paging params after pagination operation.
  232. *
  233. * @return array
  234. */
  235. public function getPagingParams()
  236. {
  237. return $this->_pagingParams;
  238. }
  239. /**
  240. * Merges the various options that Paginator uses.
  241. * Pulls settings together from the following places:
  242. *
  243. * - General pagination settings
  244. * - Model specific settings.
  245. * - Request parameters
  246. *
  247. * The result of this method is the aggregate of all the option sets
  248. * combined together. You can change config value `whitelist` to modify
  249. * which options/values can be set using request parameters.
  250. *
  251. * @param array $params Request params.
  252. * @param array $settings The settings to merge with the request data.
  253. * @return array Array of merged options.
  254. */
  255. public function mergeOptions($params, $settings)
  256. {
  257. if (!empty($settings['scope'])) {
  258. $scope = $settings['scope'];
  259. $params = !empty($params[$scope]) ? (array)$params[$scope] : [];
  260. }
  261. $params = array_intersect_key($params, array_flip($this->config('whitelist')));
  262. return array_merge($settings, $params);
  263. }
  264. /**
  265. * Get the settings for a $model. If there are no settings for a specific
  266. * repository, the general settings will be used.
  267. *
  268. * @param string $alias Model name to get settings for.
  269. * @param array $settings The settings which is used for combining.
  270. * @return array An array of pagination settings for a model,
  271. * or the general settings.
  272. */
  273. public function getDefaults($alias, $settings)
  274. {
  275. if (isset($settings[$alias])) {
  276. $settings = $settings[$alias];
  277. }
  278. $defaults = $this->getConfig();
  279. $maxLimit = isset($settings['maxLimit']) ? $settings['maxLimit'] : $defaults['maxLimit'];
  280. $limit = isset($settings['limit']) ? $settings['limit'] : $defaults['limit'];
  281. if ($limit > $maxLimit) {
  282. $limit = $maxLimit;
  283. }
  284. $settings['maxLimit'] = $maxLimit;
  285. $settings['limit'] = $limit;
  286. return $settings + $defaults;
  287. }
  288. /**
  289. * Validate that the desired sorting can be performed on the $object.
  290. *
  291. * Only fields or virtualFields can be sorted on. The direction param will
  292. * also be sanitized. Lastly sort + direction keys will be converted into
  293. * the model friendly order key.
  294. *
  295. * You can use the whitelist parameter to control which columns/fields are
  296. * available for sorting. This helps prevent users from ordering large
  297. * result sets on un-indexed values.
  298. *
  299. * If you need to sort on associated columns or synthetic properties you
  300. * will need to use a whitelist.
  301. *
  302. * Any columns listed in the sort whitelist will be implicitly trusted.
  303. * You can use this to sort on synthetic columns, or columns added in custom
  304. * find operations that may not exist in the schema.
  305. *
  306. * @param \Cake\Datasource\RepositoryInterface $object Repository object.
  307. * @param array $options The pagination options being used for this request.
  308. * @return array An array of options with sort + direction removed and
  309. * replaced with order if possible.
  310. */
  311. public function validateSort(RepositoryInterface $object, array $options)
  312. {
  313. if (isset($options['sort'])) {
  314. $direction = null;
  315. if (isset($options['direction'])) {
  316. $direction = strtolower($options['direction']);
  317. }
  318. if (!in_array($direction, ['asc', 'desc'])) {
  319. $direction = 'asc';
  320. }
  321. $options['order'] = [$options['sort'] => $direction];
  322. }
  323. unset($options['sort'], $options['direction']);
  324. if (empty($options['order'])) {
  325. $options['order'] = [];
  326. }
  327. if (!is_array($options['order'])) {
  328. return $options;
  329. }
  330. $inWhitelist = false;
  331. if (isset($options['sortWhitelist'])) {
  332. $field = key($options['order']);
  333. $inWhitelist = in_array($field, $options['sortWhitelist'], true);
  334. if (!$inWhitelist) {
  335. $options['order'] = [];
  336. return $options;
  337. }
  338. }
  339. $options['order'] = $this->_prefix($object, $options['order'], $inWhitelist);
  340. return $options;
  341. }
  342. /**
  343. * Prefixes the field with the table alias if possible.
  344. *
  345. * @param \Cake\Datasource\RepositoryInterface $object Repository object.
  346. * @param array $order Order array.
  347. * @param bool $whitelisted Whether or not the field was whitelisted.
  348. * @return array Final order array.
  349. */
  350. protected function _prefix(RepositoryInterface $object, $order, $whitelisted = false)
  351. {
  352. $tableAlias = $object->alias();
  353. $tableOrder = [];
  354. foreach ($order as $key => $value) {
  355. if (is_numeric($key)) {
  356. $tableOrder[] = $value;
  357. continue;
  358. }
  359. $field = $key;
  360. $alias = $tableAlias;
  361. if (strpos($key, '.') !== false) {
  362. list($alias, $field) = explode('.', $key);
  363. }
  364. $correctAlias = ($tableAlias === $alias);
  365. if ($correctAlias && $whitelisted) {
  366. // Disambiguate fields in schema. As id is quite common.
  367. if ($object->hasField($field)) {
  368. $field = $alias . '.' . $field;
  369. }
  370. $tableOrder[$field] = $value;
  371. } elseif ($correctAlias && $object->hasField($field)) {
  372. $tableOrder[$tableAlias . '.' . $field] = $value;
  373. } elseif (!$correctAlias && $whitelisted) {
  374. $tableOrder[$alias . '.' . $field] = $value;
  375. }
  376. }
  377. return $tableOrder;
  378. }
  379. /**
  380. * Check the limit parameter and ensure it's within the maxLimit bounds.
  381. *
  382. * @param array $options An array of options with a limit key to be checked.
  383. * @return array An array of options for pagination.
  384. */
  385. public function checkLimit(array $options)
  386. {
  387. $options['limit'] = (int)$options['limit'];
  388. if (empty($options['limit']) || $options['limit'] < 1) {
  389. $options['limit'] = 1;
  390. }
  391. $options['limit'] = max(min($options['limit'], $options['maxLimit']), 1);
  392. return $options;
  393. }
  394. }