PageRenderTime 32ms CodeModel.GetById 16ms RepoModel.GetById 0ms app.codeStats 0ms

/lib/Cake/Controller/Component/PaginatorComponent.php

https://gitlab.com/manuperazafa/elsartenbackend
PHP | 428 lines | 237 code | 38 blank | 153 comment | 57 complexity | 57a989323d2c056cb33ff16329122104 MD5 | raw file
  1. <?php
  2. /**
  3. * Paginator Component
  4. *
  5. * CakePHP(tm) : Rapid Development Framework (http://cakephp.org)
  6. * Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org)
  7. *
  8. * Licensed under The MIT License
  9. * For full copyright and license information, please see the LICENSE.txt
  10. * Redistributions of files must retain the above copyright notice.
  11. *
  12. * @copyright Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org)
  13. * @link http://cakephp.org CakePHP(tm) Project
  14. * @package Cake.Controller.Component
  15. * @since CakePHP(tm) v 2.0
  16. * @license http://www.opensource.org/licenses/mit-license.php MIT License
  17. */
  18. App::uses('Component', 'Controller');
  19. App::uses('Hash', 'Utility');
  20. /**
  21. * This component is used to handle automatic model data pagination. The primary way to use this
  22. * component is to call the paginate() method. There is a convenience wrapper on Controller as well.
  23. *
  24. * ### Configuring pagination
  25. *
  26. * You configure pagination using the PaginatorComponent::$settings. This allows you to configure
  27. * the default pagination behavior in general or for a specific model. General settings are used when there
  28. * are no specific model configuration, or the model you are paginating does not have specific settings.
  29. *
  30. * {{{
  31. * $this->Paginator->settings = array(
  32. * 'limit' => 20,
  33. * 'maxLimit' => 100
  34. * );
  35. * }}}
  36. *
  37. * The above settings will be used to paginate any model. You can configure model specific settings by
  38. * keying the settings with the model name.
  39. *
  40. * {{{
  41. * $this->Paginator->settings = array(
  42. * 'Post' => array(
  43. * 'limit' => 20,
  44. * 'maxLimit' => 100
  45. * ),
  46. * 'Comment' => array( ... )
  47. * );
  48. * }}}
  49. *
  50. * This would allow you to have different pagination settings for `Comment` and `Post` models.
  51. *
  52. * #### Paginating with custom finders
  53. *
  54. * You can paginate with any find type defined on your model using the `findType` option.
  55. *
  56. * {{{
  57. * $this->Paginator->settings = array(
  58. * 'Post' => array(
  59. * 'findType' => 'popular'
  60. * )
  61. * );
  62. * }}}
  63. *
  64. * Would paginate using the `find('popular')` method.
  65. *
  66. * @package Cake.Controller.Component
  67. * @link http://book.cakephp.org/2.0/en/core-libraries/components/pagination.html
  68. */
  69. class PaginatorComponent extends Component {
  70. /**
  71. * Pagination settings. These settings control pagination at a general level.
  72. * You can also define sub arrays for pagination settings for specific models.
  73. *
  74. * - `maxLimit` The maximum limit users can choose to view. Defaults to 100
  75. * - `limit` The initial number of items per page. Defaults to 20.
  76. * - `page` The starting page, defaults to 1.
  77. * - `paramType` What type of parameters you want pagination to use?
  78. * - `named` Use named parameters / routed parameters.
  79. * - `querystring` Use query string parameters.
  80. *
  81. * @var array
  82. */
  83. public $settings = array(
  84. 'page' => 1,
  85. 'limit' => 20,
  86. 'maxLimit' => 100,
  87. 'paramType' => 'named'
  88. );
  89. /**
  90. * A list of parameters users are allowed to set using request parameters. Modifying
  91. * this list will allow users to have more influence over pagination,
  92. * be careful with what you permit.
  93. *
  94. * @var array
  95. */
  96. public $whitelist = array(
  97. 'limit', 'sort', 'page', 'direction'
  98. );
  99. /**
  100. * Constructor
  101. *
  102. * @param ComponentCollection $collection A ComponentCollection this component can use to lazy load its components
  103. * @param array $settings Array of configuration settings.
  104. */
  105. public function __construct(ComponentCollection $collection, $settings = array()) {
  106. $settings = array_merge($this->settings, (array)$settings);
  107. $this->Controller = $collection->getController();
  108. parent::__construct($collection, $settings);
  109. }
  110. /**
  111. * Handles automatic pagination of model records.
  112. *
  113. * @param Model|string $object Model to paginate (e.g: model instance, or 'Model', or 'Model.InnerModel')
  114. * @param string|array $scope Additional find conditions to use while paginating
  115. * @param array $whitelist List of allowed fields for ordering. This allows you to prevent ordering
  116. * on non-indexed, or undesirable columns. See PaginatorComponent::validateSort() for additional details
  117. * on how the whitelisting and sort field validation works.
  118. * @return array Model query results
  119. * @throws MissingModelException
  120. * @throws NotFoundException
  121. */
  122. public function paginate($object = null, $scope = array(), $whitelist = array()) {
  123. if (is_array($object)) {
  124. $whitelist = $scope;
  125. $scope = $object;
  126. $object = null;
  127. }
  128. $object = $this->_getObject($object);
  129. if (!is_object($object)) {
  130. throw new MissingModelException($object);
  131. }
  132. $options = $this->mergeOptions($object->alias);
  133. $options = $this->validateSort($object, $options, $whitelist);
  134. $options = $this->checkLimit($options);
  135. $conditions = $fields = $order = $limit = $page = $recursive = null;
  136. if (!isset($options['conditions'])) {
  137. $options['conditions'] = array();
  138. }
  139. $type = 'all';
  140. if (isset($options[0])) {
  141. $type = $options[0];
  142. unset($options[0]);
  143. }
  144. extract($options);
  145. if (is_array($scope) && !empty($scope)) {
  146. $conditions = array_merge($conditions, $scope);
  147. } elseif (is_string($scope)) {
  148. $conditions = array($conditions, $scope);
  149. }
  150. if ($recursive === null) {
  151. $recursive = $object->recursive;
  152. }
  153. $extra = array_diff_key($options, compact(
  154. 'conditions', 'fields', 'order', 'limit', 'page', 'recursive'
  155. ));
  156. if (!empty($extra['findType'])) {
  157. $type = $extra['findType'];
  158. unset($extra['findType']);
  159. }
  160. if ($type !== 'all') {
  161. $extra['type'] = $type;
  162. }
  163. if (intval($page) < 1) {
  164. $page = 1;
  165. }
  166. $page = $options['page'] = (int)$page;
  167. if ($object->hasMethod('paginate')) {
  168. $results = $object->paginate(
  169. $conditions, $fields, $order, $limit, $page, $recursive, $extra
  170. );
  171. } else {
  172. $parameters = compact('conditions', 'fields', 'order', 'limit', 'page');
  173. if ($recursive != $object->recursive) {
  174. $parameters['recursive'] = $recursive;
  175. }
  176. $results = $object->find($type, array_merge($parameters, $extra));
  177. }
  178. $defaults = $this->getDefaults($object->alias);
  179. unset($defaults[0]);
  180. if (!$results) {
  181. $count = 0;
  182. } elseif ($object->hasMethod('paginateCount')) {
  183. $count = $object->paginateCount($conditions, $recursive, $extra);
  184. } elseif ($page === 1 && count($results) < $limit) {
  185. $count = count($results);
  186. } else {
  187. $parameters = compact('conditions');
  188. if ($recursive != $object->recursive) {
  189. $parameters['recursive'] = $recursive;
  190. }
  191. $count = $object->find('count', array_merge($parameters, $extra));
  192. }
  193. $pageCount = intval(ceil($count / $limit));
  194. $requestedPage = $page;
  195. $page = max(min($page, $pageCount), 1);
  196. $paging = array(
  197. 'page' => $page,
  198. 'current' => count($results),
  199. 'count' => $count,
  200. 'prevPage' => ($page > 1),
  201. 'nextPage' => ($count > ($page * $limit)),
  202. 'pageCount' => $pageCount,
  203. 'order' => $order,
  204. 'limit' => $limit,
  205. 'options' => Hash::diff($options, $defaults),
  206. 'paramType' => $options['paramType']
  207. );
  208. if (!isset($this->Controller->request['paging'])) {
  209. $this->Controller->request['paging'] = array();
  210. }
  211. $this->Controller->request['paging'] = array_merge(
  212. (array)$this->Controller->request['paging'],
  213. array($object->alias => $paging)
  214. );
  215. if ($requestedPage > $page) {
  216. throw new NotFoundException();
  217. }
  218. if (
  219. !in_array('Paginator', $this->Controller->helpers) &&
  220. !array_key_exists('Paginator', $this->Controller->helpers)
  221. ) {
  222. $this->Controller->helpers[] = 'Paginator';
  223. }
  224. return $results;
  225. }
  226. /**
  227. * Get the object pagination will occur on.
  228. *
  229. * @param string|Model $object The object you are looking for.
  230. * @return mixed The model object to paginate on.
  231. */
  232. protected function _getObject($object) {
  233. if (is_string($object)) {
  234. $assoc = null;
  235. if (strpos($object, '.') !== false) {
  236. list($object, $assoc) = pluginSplit($object);
  237. }
  238. if ($assoc && isset($this->Controller->{$object}->{$assoc})) {
  239. return $this->Controller->{$object}->{$assoc};
  240. }
  241. if ($assoc && isset($this->Controller->{$this->Controller->modelClass}->{$assoc})) {
  242. return $this->Controller->{$this->Controller->modelClass}->{$assoc};
  243. }
  244. if (isset($this->Controller->{$object})) {
  245. return $this->Controller->{$object};
  246. }
  247. if (isset($this->Controller->{$this->Controller->modelClass}->{$object})) {
  248. return $this->Controller->{$this->Controller->modelClass}->{$object};
  249. }
  250. }
  251. if (empty($object) || $object === null) {
  252. if (isset($this->Controller->{$this->Controller->modelClass})) {
  253. return $this->Controller->{$this->Controller->modelClass};
  254. }
  255. $className = null;
  256. $name = $this->Controller->uses[0];
  257. if (strpos($this->Controller->uses[0], '.') !== false) {
  258. list($name, $className) = explode('.', $this->Controller->uses[0]);
  259. }
  260. if ($className) {
  261. return $this->Controller->{$className};
  262. }
  263. return $this->Controller->{$name};
  264. }
  265. return $object;
  266. }
  267. /**
  268. * Merges the various options that Pagination uses.
  269. * Pulls settings together from the following places:
  270. *
  271. * - General pagination settings
  272. * - Model specific settings.
  273. * - Request parameters
  274. *
  275. * The result of this method is the aggregate of all the option sets combined together. You can change
  276. * PaginatorComponent::$whitelist to modify which options/values can be set using request parameters.
  277. *
  278. * @param string $alias Model alias being paginated, if the general settings has a key with this value
  279. * that key's settings will be used for pagination instead of the general ones.
  280. * @return array Array of merged options.
  281. */
  282. public function mergeOptions($alias) {
  283. $defaults = $this->getDefaults($alias);
  284. switch ($defaults['paramType']) {
  285. case 'named':
  286. $request = $this->Controller->request->params['named'];
  287. break;
  288. case 'querystring':
  289. $request = $this->Controller->request->query;
  290. break;
  291. }
  292. $request = array_intersect_key($request, array_flip($this->whitelist));
  293. return array_merge($defaults, $request);
  294. }
  295. /**
  296. * Get the default settings for a $model. If there are no settings for a specific model, the general settings
  297. * will be used.
  298. *
  299. * @param string $alias Model name to get default settings for.
  300. * @return array An array of pagination defaults for a model, or the general settings.
  301. */
  302. public function getDefaults($alias) {
  303. $defaults = $this->settings;
  304. if (isset($this->settings[$alias])) {
  305. $defaults = $this->settings[$alias];
  306. }
  307. if (isset($defaults['limit']) &&
  308. (empty($defaults['maxLimit']) || $defaults['limit'] > $defaults['maxLimit'])
  309. ) {
  310. $defaults['maxLimit'] = $defaults['limit'];
  311. }
  312. return array_merge(
  313. array('page' => 1, 'limit' => 20, 'maxLimit' => 100, 'paramType' => 'named'),
  314. $defaults
  315. );
  316. }
  317. /**
  318. * Validate that the desired sorting can be performed on the $object. Only fields or
  319. * virtualFields can be sorted on. The direction param will also be sanitized. Lastly
  320. * sort + direction keys will be converted into the model friendly order key.
  321. *
  322. * You can use the whitelist parameter to control which columns/fields are available for sorting.
  323. * This helps prevent users from ordering large result sets on un-indexed values.
  324. *
  325. * Any columns listed in the sort whitelist will be implicitly trusted. You can use this to sort
  326. * on synthetic columns, or columns added in custom find operations that may not exist in the schema.
  327. *
  328. * @param Model $object The model being paginated.
  329. * @param array $options The pagination options being used for this request.
  330. * @param array $whitelist The list of columns that can be used for sorting. If empty all keys are allowed.
  331. * @return array An array of options with sort + direction removed and replaced with order if possible.
  332. */
  333. public function validateSort(Model $object, array $options, array $whitelist = array()) {
  334. if (empty($options['order']) && is_array($object->order)) {
  335. $options['order'] = $object->order;
  336. }
  337. if (isset($options['sort'])) {
  338. $direction = null;
  339. if (isset($options['direction'])) {
  340. $direction = strtolower($options['direction']);
  341. }
  342. if (!in_array($direction, array('asc', 'desc'))) {
  343. $direction = 'asc';
  344. }
  345. $options['order'] = array($options['sort'] => $direction);
  346. }
  347. if (!empty($whitelist) && isset($options['order']) && is_array($options['order'])) {
  348. $field = key($options['order']);
  349. $inWhitelist = in_array($field, $whitelist, true);
  350. if (!$inWhitelist) {
  351. $options['order'] = null;
  352. }
  353. return $options;
  354. }
  355. if (!empty($options['order']) && is_array($options['order'])) {
  356. $order = array();
  357. foreach ($options['order'] as $key => $value) {
  358. $field = $key;
  359. $alias = $object->alias;
  360. if (strpos($key, '.') !== false) {
  361. list($alias, $field) = explode('.', $key);
  362. }
  363. $correctAlias = ($object->alias === $alias);
  364. if ($correctAlias && $object->hasField($field)) {
  365. $order[$object->alias . '.' . $field] = $value;
  366. } elseif ($correctAlias && $object->hasField($key, true)) {
  367. $order[$field] = $value;
  368. } elseif (isset($object->{$alias}) && $object->{$alias}->hasField($field, true)) {
  369. $order[$alias . '.' . $field] = $value;
  370. }
  371. }
  372. $options['order'] = $order;
  373. }
  374. return $options;
  375. }
  376. /**
  377. * Check the limit parameter and ensure its within the maxLimit bounds.
  378. *
  379. * @param array $options An array of options with a limit key to be checked.
  380. * @return array An array of options for pagination
  381. */
  382. public function checkLimit(array $options) {
  383. $options['limit'] = (int)$options['limit'];
  384. if (empty($options['limit']) || $options['limit'] < 1) {
  385. $options['limit'] = 1;
  386. }
  387. $options['limit'] = min($options['limit'], $options['maxLimit']);
  388. return $options;
  389. }
  390. }