PaginatorComponent.php 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427
  1. <?php
  2. /**
  3. * Paginator Component
  4. *
  5. * PHP 5
  6. *
  7. * CakePHP(tm) : Rapid Development Framework (http://cakephp.org)
  8. * Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org)
  9. *
  10. * Licensed under The MIT License
  11. * For full copyright and license information, please see the LICENSE.txt
  12. * Redistributions of files must retain the above copyright notice.
  13. *
  14. * @copyright Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org)
  15. * @link http://cakephp.org CakePHP(tm) Project
  16. * @package Cake.Controller.Component
  17. * @since CakePHP(tm) v 2.0
  18. * @license http://www.opensource.org/licenses/mit-license.php MIT License
  19. */
  20. App::uses('Component', 'Controller');
  21. App::uses('Hash', 'Utility');
  22. /**
  23. * This component is used to handle automatic model data pagination. The primary way to use this
  24. * component is to call the paginate() method. There is a convenience wrapper on Controller as well.
  25. *
  26. * ### Configuring pagination
  27. *
  28. * You configure pagination using the PaginatorComponent::$settings. This allows you to configure
  29. * the default pagination behavior in general or for a specific model. General settings are used when there
  30. * are no specific model configuration, or the model you are paginating does not have specific settings.
  31. *
  32. * {{{
  33. * $this->Paginator->settings = array(
  34. * 'limit' => 20,
  35. * 'maxLimit' => 100
  36. * );
  37. * }}}
  38. *
  39. * The above settings will be used to paginate any model. You can configure model specific settings by
  40. * keying the settings with the model name.
  41. *
  42. * {{{
  43. * $this->Paginator->settings = array(
  44. * 'Post' => array(
  45. * 'limit' => 20,
  46. * 'maxLimit' => 100
  47. * ),
  48. * 'Comment' => array( ... )
  49. * );
  50. * }}}
  51. *
  52. * This would allow you to have different pagination settings for `Comment` and `Post` models.
  53. *
  54. * #### Paginating with custom finders
  55. *
  56. * You can paginate with any find type defined on your model using the `findType` option.
  57. *
  58. * {{{
  59. * $this->Paginator->settings = array(
  60. * 'Post' => array(
  61. * 'findType' => 'popular'
  62. * )
  63. * );
  64. * }}}
  65. *
  66. * Would paginate using the `find('popular')` method.
  67. *
  68. * @package Cake.Controller.Component
  69. * @link http://book.cakephp.org/2.0/en/core-libraries/components/pagination.html
  70. */
  71. class PaginatorComponent extends Component {
  72. /**
  73. * Pagination settings. These settings control pagination at a general level.
  74. * You can also define sub arrays for pagination settings for specific models.
  75. *
  76. * - `maxLimit` The maximum limit users can choose to view. Defaults to 100
  77. * - `limit` The initial number of items per page. Defaults to 20.
  78. * - `page` The starting page, defaults to 1.
  79. * - `paramType` What type of parameters you want pagination to use?
  80. * - `named` Use named parameters / routed parameters.
  81. * - `querystring` Use query string parameters.
  82. *
  83. * @var array
  84. */
  85. public $settings = array(
  86. 'page' => 1,
  87. 'limit' => 20,
  88. 'maxLimit' => 100,
  89. 'paramType' => 'named'
  90. );
  91. /**
  92. * A list of parameters users are allowed to set using request parameters. Modifying
  93. * this list will allow users to have more influence over pagination,
  94. * be careful with what you permit.
  95. *
  96. * @var array
  97. */
  98. public $whitelist = array(
  99. 'limit', 'sort', 'page', 'direction'
  100. );
  101. /**
  102. * Constructor
  103. *
  104. * @param ComponentCollection $collection A ComponentCollection this component can use to lazy load its components
  105. * @param array $settings Array of configuration settings.
  106. */
  107. public function __construct(ComponentCollection $collection, $settings = array()) {
  108. $settings = array_merge($this->settings, (array)$settings);
  109. $this->Controller = $collection->getController();
  110. parent::__construct($collection, $settings);
  111. }
  112. /**
  113. * Handles automatic pagination of model records.
  114. *
  115. * @param Model|string $object Model to paginate (e.g: model instance, or 'Model', or 'Model.InnerModel')
  116. * @param string|array $scope Additional find conditions to use while paginating
  117. * @param array $whitelist List of allowed fields for ordering. This allows you to prevent ordering
  118. * on non-indexed, or undesirable columns. See PaginatorComponent::validateSort() for additional details
  119. * on how the whitelisting and sort field validation works.
  120. * @return array Model query results
  121. * @throws MissingModelException
  122. * @throws NotFoundException
  123. */
  124. public function paginate($object = null, $scope = array(), $whitelist = array()) {
  125. if (is_array($object)) {
  126. $whitelist = $scope;
  127. $scope = $object;
  128. $object = null;
  129. }
  130. $object = $this->_getObject($object);
  131. if (!is_object($object)) {
  132. throw new MissingModelException($object);
  133. }
  134. $options = $this->mergeOptions($object->alias);
  135. $options = $this->validateSort($object, $options, $whitelist);
  136. $options = $this->checkLimit($options);
  137. $conditions = $fields = $order = $limit = $page = $recursive = null;
  138. if (!isset($options['conditions'])) {
  139. $options['conditions'] = array();
  140. }
  141. $type = 'all';
  142. if (isset($options[0])) {
  143. $type = $options[0];
  144. unset($options[0]);
  145. }
  146. extract($options);
  147. if (is_array($scope) && !empty($scope)) {
  148. $conditions = array_merge($conditions, $scope);
  149. } elseif (is_string($scope)) {
  150. $conditions = array($conditions, $scope);
  151. }
  152. if ($recursive === null) {
  153. $recursive = $object->recursive;
  154. }
  155. $extra = array_diff_key($options, compact(
  156. 'conditions', 'fields', 'order', 'limit', 'page', 'recursive'
  157. ));
  158. if (!empty($extra['findType'])) {
  159. $type = $extra['findType'];
  160. unset($extra['findType']);
  161. }
  162. if ($type !== 'all') {
  163. $extra['type'] = $type;
  164. }
  165. if (intval($page) < 1) {
  166. $page = 1;
  167. }
  168. $page = $options['page'] = (int)$page;
  169. if ($object->hasMethod('paginate')) {
  170. $results = $object->paginate(
  171. $conditions, $fields, $order, $limit, $page, $recursive, $extra
  172. );
  173. } else {
  174. $parameters = compact('conditions', 'fields', 'order', 'limit', 'page');
  175. if ($recursive != $object->recursive) {
  176. $parameters['recursive'] = $recursive;
  177. }
  178. $results = $object->find($type, array_merge($parameters, $extra));
  179. }
  180. $defaults = $this->getDefaults($object->alias);
  181. unset($defaults[0]);
  182. if (!$results) {
  183. $count = 0;
  184. } elseif ($object->hasMethod('paginateCount')) {
  185. $count = $object->paginateCount($conditions, $recursive, $extra);
  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. if ($requestedPage > $page) {
  197. throw new NotFoundException();
  198. }
  199. $paging = array(
  200. 'page' => $page,
  201. 'current' => count($results),
  202. 'count' => $count,
  203. 'prevPage' => ($page > 1),
  204. 'nextPage' => ($count > ($page * $limit)),
  205. 'pageCount' => $pageCount,
  206. 'order' => $order,
  207. 'limit' => $limit,
  208. 'options' => Hash::diff($options, $defaults),
  209. 'paramType' => $options['paramType']
  210. );
  211. if (!isset($this->Controller->request['paging'])) {
  212. $this->Controller->request['paging'] = array();
  213. }
  214. $this->Controller->request['paging'] = array_merge(
  215. (array)$this->Controller->request['paging'],
  216. array($object->alias => $paging)
  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. }