PageRenderTime 61ms CodeModel.GetById 33ms RepoModel.GetById 0ms app.codeStats 0ms

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

https://gitlab.com/fouzia23chowdhury/cakephpCRUD
PHP | 429 lines | 238 code | 38 blank | 153 comment | 56 complexity | 6f73b6561fd36d2a2f1642a7834a2e22 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 ((int)$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 = (int)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 (!in_array('Paginator', $this->Controller->helpers) &&
  219. !array_key_exists('Paginator', $this->Controller->helpers)
  220. ) {
  221. $this->Controller->helpers[] = 'Paginator';
  222. }
  223. return $results;
  224. }
  225. /**
  226. * Get the object pagination will occur on.
  227. *
  228. * @param string|Model $object The object you are looking for.
  229. * @return mixed The model object to paginate on.
  230. */
  231. protected function _getObject($object) {
  232. if (is_string($object)) {
  233. $assoc = null;
  234. if (strpos($object, '.') !== false) {
  235. list($object, $assoc) = pluginSplit($object);
  236. }
  237. if ($assoc && isset($this->Controller->{$object}->{$assoc})) {
  238. return $this->Controller->{$object}->{$assoc};
  239. }
  240. if ($assoc && isset($this->Controller->{$this->Controller->modelClass}->{$assoc})) {
  241. return $this->Controller->{$this->Controller->modelClass}->{$assoc};
  242. }
  243. if (isset($this->Controller->{$object})) {
  244. return $this->Controller->{$object};
  245. }
  246. if (isset($this->Controller->{$this->Controller->modelClass}->{$object})) {
  247. return $this->Controller->{$this->Controller->modelClass}->{$object};
  248. }
  249. }
  250. if (empty($object) || $object === null) {
  251. if (isset($this->Controller->{$this->Controller->modelClass})) {
  252. return $this->Controller->{$this->Controller->modelClass};
  253. }
  254. $className = null;
  255. $name = $this->Controller->uses[0];
  256. if (strpos($this->Controller->uses[0], '.') !== false) {
  257. list($name, $className) = explode('.', $this->Controller->uses[0]);
  258. }
  259. if ($className) {
  260. return $this->Controller->{$className};
  261. }
  262. return $this->Controller->{$name};
  263. }
  264. return $object;
  265. }
  266. /**
  267. * Merges the various options that Pagination uses.
  268. * Pulls settings together from the following places:
  269. *
  270. * - General pagination settings
  271. * - Model specific settings.
  272. * - Request parameters
  273. *
  274. * The result of this method is the aggregate of all the option sets combined together. You can change
  275. * PaginatorComponent::$whitelist to modify which options/values can be set using request parameters.
  276. *
  277. * @param string $alias Model alias being paginated, if the general settings has a key with this value
  278. * that key's settings will be used for pagination instead of the general ones.
  279. * @return array Array of merged options.
  280. */
  281. public function mergeOptions($alias) {
  282. $defaults = $this->getDefaults($alias);
  283. switch ($defaults['paramType']) {
  284. case 'named':
  285. $request = $this->Controller->request->params['named'];
  286. break;
  287. case 'querystring':
  288. $request = $this->Controller->request->query;
  289. break;
  290. }
  291. $request = array_intersect_key($request, array_flip($this->whitelist));
  292. return array_merge($defaults, $request);
  293. }
  294. /**
  295. * Get the default settings for a $model. If there are no settings for a specific model, the general settings
  296. * will be used.
  297. *
  298. * @param string $alias Model name to get default settings for.
  299. * @return array An array of pagination defaults for a model, or the general settings.
  300. */
  301. public function getDefaults($alias) {
  302. $defaults = $this->settings;
  303. if (isset($this->settings[$alias])) {
  304. $defaults = $this->settings[$alias];
  305. }
  306. $defaults += array(
  307. 'page' => 1,
  308. 'limit' => 20,
  309. 'maxLimit' => 100,
  310. 'paramType' => 'named'
  311. );
  312. return $defaults;
  313. }
  314. /**
  315. * Validate that the desired sorting can be performed on the $object. Only fields or
  316. * virtualFields can be sorted on. The direction param will also be sanitized. Lastly
  317. * sort + direction keys will be converted into the model friendly order key.
  318. *
  319. * You can use the whitelist parameter to control which columns/fields are available for sorting.
  320. * This helps prevent users from ordering large result sets on un-indexed values.
  321. *
  322. * Any columns listed in the sort whitelist will be implicitly trusted. You can use this to sort
  323. * on synthetic columns, or columns added in custom find operations that may not exist in the schema.
  324. *
  325. * @param Model $object The model being paginated.
  326. * @param array $options The pagination options being used for this request.
  327. * @param array $whitelist The list of columns that can be used for sorting. If empty all keys are allowed.
  328. * @return array An array of options with sort + direction removed and replaced with order if possible.
  329. */
  330. public function validateSort(Model $object, array $options, array $whitelist = array()) {
  331. if (empty($options['order']) && is_array($object->order)) {
  332. $options['order'] = $object->order;
  333. }
  334. if (isset($options['sort'])) {
  335. $direction = null;
  336. if (isset($options['direction'])) {
  337. $direction = strtolower($options['direction']);
  338. }
  339. if (!in_array($direction, array('asc', 'desc'))) {
  340. $direction = 'asc';
  341. }
  342. $options['order'] = array($options['sort'] => $direction);
  343. }
  344. if (!empty($whitelist) && isset($options['order']) && is_array($options['order'])) {
  345. $field = key($options['order']);
  346. $inWhitelist = in_array($field, $whitelist, true);
  347. if (!$inWhitelist) {
  348. $options['order'] = null;
  349. }
  350. return $options;
  351. }
  352. if (!empty($options['order']) && is_array($options['order'])) {
  353. $order = array();
  354. foreach ($options['order'] as $key => $value) {
  355. if (is_int($key)) {
  356. $key = $value;
  357. $value = 'asc';
  358. }
  359. $field = $key;
  360. $alias = $object->alias;
  361. if (strpos($key, '.') !== false) {
  362. list($alias, $field) = explode('.', $key);
  363. }
  364. $correctAlias = ($object->alias === $alias);
  365. if ($correctAlias && $object->hasField($field)) {
  366. $order[$object->alias . '.' . $field] = $value;
  367. } elseif ($correctAlias && $object->hasField($key, true)) {
  368. $order[$field] = $value;
  369. } elseif (isset($object->{$alias}) && $object->{$alias}->hasField($field, true)) {
  370. $order[$alias . '.' . $field] = $value;
  371. }
  372. }
  373. $options['order'] = $order;
  374. }
  375. return $options;
  376. }
  377. /**
  378. * Check the limit parameter and ensure its within the maxLimit bounds.
  379. *
  380. * @param array $options An array of options with a limit key to be checked.
  381. * @return array An array of options for pagination
  382. */
  383. public function checkLimit(array $options) {
  384. $options['limit'] = (int)$options['limit'];
  385. if (empty($options['limit']) || $options['limit'] < 1) {
  386. $options['limit'] = 1;
  387. }
  388. $options['limit'] = min($options['limit'], $options['maxLimit']);
  389. return $options;
  390. }
  391. }