PageRenderTime 25ms CodeModel.GetById 12ms RepoModel.GetById 1ms app.codeStats 0ms

/vendor/cakephp/cakephp/src/Controller/Component/PaginatorComponent.php

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