PaginatorComponent.php 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415
  1. <?php
  2. /**
  3. * Paginator Component
  4. *
  5. * PHP 5
  6. *
  7. * CakePHP(tm) : Rapid Development Framework (http://cakephp.org)
  8. * Copyright 2005-2012, Cake Software Foundation, Inc. (http://cakefoundation.org)
  9. *
  10. * Licensed under The MIT License
  11. * Redistributions of files must retain the above copyright notice.
  12. *
  13. * @copyright Copyright 2005-2012, Cake Software Foundation, Inc. (http://cakefoundation.org)
  14. * @link http://cakephp.org CakePHP(tm) Project
  15. * @package Cake.Controller.Component
  16. * @since CakePHP(tm) v 2.0
  17. * @license MIT License (http://www.opensource.org/licenses/mit-license.php)
  18. */
  19. App::uses('Component', 'Controller');
  20. App::uses('Hash', 'Utility');
  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 using the PaginatorComponent::$settings. This allows you to configure
  28. * the default pagination behavior in general or for a specific model. General settings are used when there
  29. * are no specific model configuration, or the model you are paginating does not have specific settings.
  30. *
  31. * {{{
  32. * $this->Paginator->settings = array(
  33. * 'limit' => 20,
  34. * 'maxLimit' => 100
  35. * );
  36. * }}}
  37. *
  38. * The above settings will be used to paginate any model. You can configure model specific settings by
  39. * keying the settings with the model name.
  40. *
  41. * {{{
  42. * $this->Paginator->settings = array(
  43. * 'Post' => array(
  44. * 'limit' => 20,
  45. * 'maxLimit' => 100
  46. * ),
  47. * 'Comment' => array( ... )
  48. * );
  49. * }}}
  50. *
  51. * This would allow you to have different pagination settings for `Comment` and `Post` models.
  52. *
  53. * #### Paginating with custom finders
  54. *
  55. * You can paginate with any find type defined on your model using the `findType` option.
  56. *
  57. * {{{
  58. * $this->Paginator->settings = array(
  59. * 'Post' => array(
  60. * 'findType' => 'popular'
  61. * )
  62. * );
  63. * }}}
  64. *
  65. * Would paginate using the `find('popular')` method.
  66. *
  67. * @package Cake.Controller.Component
  68. * @link http://book.cakephp.org/2.0/en/core-libraries/components/pagination.html
  69. */
  70. class PaginatorComponent extends Component {
  71. /**
  72. * Pagination settings. These settings control pagination at a general level.
  73. * You can also define sub arrays for pagination settings for specific models.
  74. *
  75. * - `maxLimit` The maximum limit users can choose to view. Defaults to 100
  76. * - `limit` The initial number of items per page. Defaults to 20.
  77. * - `page` The starting page, defaults to 1.
  78. * - `paramType` What type of parameters you want pagination to use?
  79. * - `named` Use named parameters / routed parameters.
  80. * - `querystring` Use query string parameters.
  81. *
  82. * @var array
  83. */
  84. public $settings = array(
  85. 'page' => 1,
  86. 'limit' => 20,
  87. 'maxLimit' => 100,
  88. 'paramType' => 'named'
  89. );
  90. /**
  91. * A list of parameters users are allowed to set using request parameters. Modifying
  92. * this list will allow users to have more influence over pagination,
  93. * be careful with what you permit.
  94. *
  95. * @var array
  96. */
  97. public $whitelist = array(
  98. 'limit', 'sort', 'page', 'direction'
  99. );
  100. /**
  101. * Constructor
  102. *
  103. * @param ComponentCollection $collection A ComponentCollection this component can use to lazy load its components
  104. * @param array $settings Array of configuration settings.
  105. */
  106. public function __construct(ComponentCollection $collection, $settings = array()) {
  107. $settings = array_merge($this->settings, (array)$settings);
  108. $this->Controller = $collection->getController();
  109. parent::__construct($collection, $settings);
  110. }
  111. /**
  112. * Handles automatic pagination of model records.
  113. *
  114. * @param Model|string $object Model to paginate (e.g: model instance, or 'Model', or 'Model.InnerModel')
  115. * @param string|array $scope Additional find conditions to use while paginating
  116. * @param array $whitelist List of allowed fields for ordering. This allows you to prevent ordering
  117. * on non-indexed, or undesirable columns.
  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. * @param Model $object The model being paginated.
  324. * @param array $options The pagination options being used for this request.
  325. * @param array $whitelist The list of columns that can be used for sorting. If empty all keys are allowed.
  326. * @return array An array of options with sort + direction removed and replaced with order if possible.
  327. */
  328. public function validateSort(Model $object, array $options, array $whitelist = array()) {
  329. if (isset($options['sort'])) {
  330. $direction = null;
  331. if (isset($options['direction'])) {
  332. $direction = strtolower($options['direction']);
  333. }
  334. if (!in_array($direction, array('asc', 'desc'))) {
  335. $direction = 'asc';
  336. }
  337. $options['order'] = array($options['sort'] => $direction);
  338. }
  339. if (!empty($whitelist) && isset($options['order']) && is_array($options['order'])) {
  340. $field = key($options['order']);
  341. if (!in_array($field, $whitelist)) {
  342. $options['order'] = null;
  343. }
  344. }
  345. if (!empty($options['order']) && is_array($options['order'])) {
  346. $order = array();
  347. foreach ($options['order'] as $key => $value) {
  348. $field = $key;
  349. $alias = $object->alias;
  350. if (strpos($key, '.') !== false) {
  351. list($alias, $field) = explode('.', $key);
  352. }
  353. if ($object->hasField($field)) {
  354. $order[$alias . '.' . $field] = $value;
  355. } elseif ($object->hasField($key, true)) {
  356. $order[$field] = $value;
  357. } elseif (isset($object->{$alias}) && $object->{$alias}->hasField($field, true)) {
  358. $order[$alias . '.' . $field] = $value;
  359. }
  360. }
  361. $options['order'] = $order;
  362. }
  363. return $options;
  364. }
  365. /**
  366. * Check the limit parameter and ensure its within the maxLimit bounds.
  367. *
  368. * @param array $options An array of options with a limit key to be checked.
  369. * @return array An array of options for pagination
  370. */
  371. public function checkLimit(array $options) {
  372. $options['limit'] = (int)$options['limit'];
  373. if (empty($options['limit']) || $options['limit'] < 1) {
  374. $options['limit'] = 1;
  375. }
  376. $options['limit'] = min($options['limit'], $options['maxLimit']);
  377. return $options;
  378. }
  379. }