PaginatorComponent.php 13 KB

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