PaginatorComponent.php 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406
  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. */
  121. public function paginate($object = null, $scope = array(), $whitelist = array()) {
  122. if (is_array($object)) {
  123. $whitelist = $scope;
  124. $scope = $object;
  125. $object = null;
  126. }
  127. $object = $this->_getObject($object);
  128. if (!is_object($object)) {
  129. throw new MissingModelException($object);
  130. }
  131. $options = $this->mergeOptions($object->alias);
  132. $options = $this->validateSort($object, $options, $whitelist);
  133. $options = $this->checkLimit($options);
  134. $conditions = $fields = $order = $limit = $page = $recursive = null;
  135. if (!isset($options['conditions'])) {
  136. $options['conditions'] = array();
  137. }
  138. $type = 'all';
  139. if (isset($options[0])) {
  140. $type = $options[0];
  141. unset($options[0]);
  142. }
  143. extract($options);
  144. if (is_array($scope) && !empty($scope)) {
  145. $conditions = array_merge($conditions, $scope);
  146. } elseif (is_string($scope)) {
  147. $conditions = array($conditions, $scope);
  148. }
  149. if ($recursive === null) {
  150. $recursive = $object->recursive;
  151. }
  152. $extra = array_diff_key($options, compact(
  153. 'conditions', 'fields', 'order', 'limit', 'page', 'recursive'
  154. ));
  155. if (!empty($extra['findType'])) {
  156. $type = $extra['findType'];
  157. unset($extra['findType']);
  158. }
  159. if ($type !== 'all') {
  160. $extra['type'] = $type;
  161. }
  162. if (intval($page) < 1) {
  163. $page = 1;
  164. }
  165. $page = $options['page'] = (int)$page;
  166. if ($object->hasMethod('paginate')) {
  167. $results = $object->paginate(
  168. $conditions, $fields, $order, $limit, $page, $recursive, $extra
  169. );
  170. } else {
  171. $parameters = compact('conditions', 'fields', 'order', 'limit', 'page');
  172. if ($recursive != $object->recursive) {
  173. $parameters['recursive'] = $recursive;
  174. }
  175. $results = $object->find($type, array_merge($parameters, $extra));
  176. }
  177. $defaults = $this->getDefaults($object->alias);
  178. unset($defaults[0]);
  179. if ($object->hasMethod('paginateCount')) {
  180. $count = $object->paginateCount($conditions, $recursive, $extra);
  181. } else {
  182. $parameters = compact('conditions');
  183. if ($recursive != $object->recursive) {
  184. $parameters['recursive'] = $recursive;
  185. }
  186. $count = $object->find('count', array_merge($parameters, $extra));
  187. }
  188. $pageCount = intval(ceil($count / $limit));
  189. $page = max(min($page, $pageCount), 1);
  190. $paging = array(
  191. 'page' => $page,
  192. 'current' => count($results),
  193. 'count' => $count,
  194. 'prevPage' => ($page > 1),
  195. 'nextPage' => ($count > ($page * $limit)),
  196. 'pageCount' => $pageCount,
  197. 'order' => $order,
  198. 'limit' => $limit,
  199. 'options' => Hash::diff($options, $defaults),
  200. 'paramType' => $options['paramType']
  201. );
  202. if (!isset($this->Controller->request['paging'])) {
  203. $this->Controller->request['paging'] = array();
  204. }
  205. $this->Controller->request['paging'] = array_merge(
  206. (array)$this->Controller->request['paging'],
  207. array($object->alias => $paging)
  208. );
  209. if (
  210. !in_array('Paginator', $this->Controller->helpers) &&
  211. !array_key_exists('Paginator', $this->Controller->helpers)
  212. ) {
  213. $this->Controller->helpers[] = 'Paginator';
  214. }
  215. return $results;
  216. }
  217. /**
  218. * Get the object pagination will occur on.
  219. *
  220. * @param string|Model $object The object you are looking for.
  221. * @return mixed The model object to paginate on.
  222. */
  223. protected function _getObject($object) {
  224. if (is_string($object)) {
  225. $assoc = null;
  226. if (strpos($object, '.') !== false) {
  227. list($object, $assoc) = pluginSplit($object);
  228. }
  229. if ($assoc && isset($this->Controller->{$object}->{$assoc})) {
  230. return $this->Controller->{$object}->{$assoc};
  231. }
  232. if ($assoc && isset($this->Controller->{$this->Controller->modelClass}->{$assoc})) {
  233. return $this->Controller->{$this->Controller->modelClass}->{$assoc};
  234. }
  235. if (isset($this->Controller->{$object})) {
  236. return $this->Controller->{$object};
  237. }
  238. if (isset($this->Controller->{$this->Controller->modelClass}->{$object})) {
  239. return $this->Controller->{$this->Controller->modelClass}->{$object};
  240. }
  241. }
  242. if (empty($object) || $object === null) {
  243. if (isset($this->Controller->{$this->Controller->modelClass})) {
  244. return $this->Controller->{$this->Controller->modelClass};
  245. }
  246. $className = null;
  247. $name = $this->Controller->uses[0];
  248. if (strpos($this->Controller->uses[0], '.') !== false) {
  249. list($name, $className) = explode('.', $this->Controller->uses[0]);
  250. }
  251. if ($className) {
  252. return $this->Controller->{$className};
  253. }
  254. return $this->Controller->{$name};
  255. }
  256. return $object;
  257. }
  258. /**
  259. * Merges the various options that Pagination uses.
  260. * Pulls settings together from the following places:
  261. *
  262. * - General pagination settings
  263. * - Model specific settings.
  264. * - Request parameters
  265. *
  266. * The result of this method is the aggregate of all the option sets combined together. You can change
  267. * PaginatorComponent::$whitelist to modify which options/values can be set using request parameters.
  268. *
  269. * @param string $alias Model alias being paginated, if the general settings has a key with this value
  270. * that key's settings will be used for pagination instead of the general ones.
  271. * @return array Array of merged options.
  272. */
  273. public function mergeOptions($alias) {
  274. $defaults = $this->getDefaults($alias);
  275. switch ($defaults['paramType']) {
  276. case 'named':
  277. $request = $this->Controller->request->params['named'];
  278. break;
  279. case 'querystring':
  280. $request = $this->Controller->request->query;
  281. break;
  282. }
  283. $request = array_intersect_key($request, array_flip($this->whitelist));
  284. return array_merge($defaults, $request);
  285. }
  286. /**
  287. * Get the default settings for a $model. If there are no settings for a specific model, the general settings
  288. * will be used.
  289. *
  290. * @param string $alias Model name to get default settings for.
  291. * @return array An array of pagination defaults for a model, or the general settings.
  292. */
  293. public function getDefaults($alias) {
  294. $defaults = $this->settings;
  295. if (isset($this->settings[$alias])) {
  296. $defaults = $this->settings[$alias];
  297. }
  298. if (isset($defaults['limit']) &&
  299. (empty($defaults['maxLimit']) || $defaults['limit'] > $defaults['maxLimit'])
  300. ) {
  301. $defaults['maxLimit'] = $defaults['limit'];
  302. }
  303. return array_merge(
  304. array('page' => 1, 'limit' => 20, 'maxLimit' => 100, 'paramType' => 'named'),
  305. $defaults
  306. );
  307. }
  308. /**
  309. * Validate that the desired sorting can be performed on the $object. Only fields or
  310. * virtualFields can be sorted on. The direction param will also be sanitized. Lastly
  311. * sort + direction keys will be converted into the model friendly order key.
  312. *
  313. * You can use the whitelist parameter to control which columns/fields are available for sorting.
  314. * This helps prevent users from ordering large result sets on un-indexed values.
  315. *
  316. * @param Model $object The model being paginated.
  317. * @param array $options The pagination options being used for this request.
  318. * @param array $whitelist The list of columns that can be used for sorting. If empty all keys are allowed.
  319. * @return array An array of options with sort + direction removed and replaced with order if possible.
  320. */
  321. public function validateSort(Model $object, array $options, array $whitelist = array()) {
  322. if (isset($options['sort'])) {
  323. $direction = null;
  324. if (isset($options['direction'])) {
  325. $direction = strtolower($options['direction']);
  326. }
  327. if (!in_array($direction, array('asc', 'desc'))) {
  328. $direction = 'asc';
  329. }
  330. $options['order'] = array($options['sort'] => $direction);
  331. }
  332. if (!empty($whitelist) && isset($options['order']) && is_array($options['order'])) {
  333. $field = key($options['order']);
  334. if (!in_array($field, $whitelist)) {
  335. $options['order'] = null;
  336. }
  337. }
  338. if (!empty($options['order']) && is_array($options['order'])) {
  339. $order = array();
  340. foreach ($options['order'] as $key => $value) {
  341. $field = $key;
  342. $alias = $object->alias;
  343. if (strpos($key, '.') !== false) {
  344. list($alias, $field) = explode('.', $key);
  345. }
  346. if ($object->hasField($field)) {
  347. $order[$alias . '.' . $field] = $value;
  348. } elseif ($object->hasField($key, true)) {
  349. $order[$field] = $value;
  350. } elseif (isset($object->{$alias}) && $object->{$alias}->hasField($field, true)) {
  351. $order[$alias . '.' . $field] = $value;
  352. }
  353. }
  354. $options['order'] = $order;
  355. }
  356. return $options;
  357. }
  358. /**
  359. * Check the limit parameter and ensure its within the maxLimit bounds.
  360. *
  361. * @param array $options An array of options with a limit key to be checked.
  362. * @return array An array of options for pagination
  363. */
  364. public function checkLimit(array $options) {
  365. $options['limit'] = (int)$options['limit'];
  366. if (empty($options['limit']) || $options['limit'] < 1) {
  367. $options['limit'] = 1;
  368. }
  369. $options['limit'] = min($options['limit'], $options['maxLimit']);
  370. return $options;
  371. }
  372. }