PaginatorComponent.php 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415
  1. <?php
  2. /**
  3. * CakePHP(tm) : Rapid Development Framework (http://cakephp.org)
  4. * Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org)
  5. *
  6. * Licensed under The MIT License
  7. * For full copyright and license information, please see the LICENSE.txt
  8. * Redistributions of files must retain the above copyright notice.
  9. *
  10. * @copyright Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org)
  11. * @link http://cakephp.org CakePHP(tm) Project
  12. * @since CakePHP(tm) v 2.0
  13. * @license http://www.opensource.org/licenses/mit-license.php MIT License
  14. */
  15. namespace Cake\Controller\Component;
  16. use Cake\Controller\Component;
  17. use Cake\Controller\ComponentRegistry;
  18. use Cake\Error;
  19. use Cake\Model\Model;
  20. use Cake\Utility\Hash;
  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. * @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. *
  78. * @var array
  79. */
  80. public $settings = array(
  81. 'page' => 1,
  82. 'limit' => 20,
  83. 'maxLimit' => 100,
  84. );
  85. /**
  86. * A list of parameters users are allowed to set using request parameters. Modifying
  87. * this list will allow users to have more influence over pagination,
  88. * be careful with what you permit.
  89. *
  90. * @var array
  91. */
  92. public $whitelist = array(
  93. 'limit', 'sort', 'page', 'direction'
  94. );
  95. /**
  96. * Constructor
  97. *
  98. * @param ComponentRegistry $collection A ComponentRegistry this component can use to lazy load its components
  99. * @param array $settings Array of configuration settings.
  100. */
  101. public function __construct(ComponentRegistry $collection, $settings = array()) {
  102. $settings = array_merge($this->settings, (array)$settings);
  103. $this->Controller = $collection->getController();
  104. parent::__construct($collection, $settings);
  105. }
  106. /**
  107. * Handles automatic pagination of model records.
  108. *
  109. * @param Model|string $object Model to paginate (e.g: model instance, or 'Model', or 'Model.InnerModel')
  110. * @param string|array $scope Additional find conditions to use while paginating
  111. * @param array $whitelist List of allowed fields for ordering. This allows you to prevent ordering
  112. * on non-indexed, or undesirable columns. See PaginatorComponent::validateSort() for additional details
  113. * on how the whitelisting and sort field validation works.
  114. * @return array Model query results
  115. * @throws Cake\Error\MissingModelException
  116. * @throws Cake\Error\NotFoundException
  117. */
  118. public function paginate($object = null, $scope = array(), $whitelist = array()) {
  119. if (is_array($object)) {
  120. $whitelist = $scope;
  121. $scope = $object;
  122. $object = null;
  123. }
  124. $object = $this->_getObject($object);
  125. if (!is_object($object)) {
  126. throw new Error\MissingModelException($object);
  127. }
  128. $options = $this->mergeOptions($object->alias);
  129. $options = $this->validateSort($object, $options, $whitelist);
  130. $options = $this->checkLimit($options);
  131. $conditions = $fields = $order = $limit = $page = $recursive = null;
  132. if (!isset($options['conditions'])) {
  133. $options['conditions'] = array();
  134. }
  135. $type = 'all';
  136. if (isset($options[0])) {
  137. $type = $options[0];
  138. unset($options[0]);
  139. }
  140. extract($options);
  141. if (is_array($scope) && !empty($scope)) {
  142. $conditions = array_merge($conditions, $scope);
  143. } elseif (is_string($scope)) {
  144. $conditions = array($conditions, $scope);
  145. }
  146. if ($recursive === null) {
  147. $recursive = $object->recursive;
  148. }
  149. $extra = array_diff_key($options, compact(
  150. 'conditions', 'fields', 'order', 'limit', 'page', 'recursive'
  151. ));
  152. if (!empty($extra['findType'])) {
  153. $type = $extra['findType'];
  154. unset($extra['findType']);
  155. }
  156. if ($type !== 'all') {
  157. $extra['type'] = $type;
  158. }
  159. if (intval($page) < 1) {
  160. $page = 1;
  161. }
  162. $page = $options['page'] = (int)$page;
  163. if ($object->hasMethod('paginate')) {
  164. $results = $object->paginate(
  165. $conditions, $fields, $order, $limit, $page, $recursive, $extra
  166. );
  167. } else {
  168. $parameters = compact('conditions', 'fields', 'order', 'limit', 'page');
  169. if ($recursive != $object->recursive) {
  170. $parameters['recursive'] = $recursive;
  171. }
  172. $results = $object->find($type, array_merge($parameters, $extra));
  173. }
  174. $defaults = $this->getDefaults($object->alias);
  175. unset($defaults[0]);
  176. if (!$results) {
  177. $count = 0;
  178. } elseif ($object->hasMethod('paginateCount')) {
  179. $count = $object->paginateCount($conditions, $recursive, $extra);
  180. } else {
  181. $parameters = compact('conditions');
  182. if ($recursive != $object->recursive) {
  183. $parameters['recursive'] = $recursive;
  184. }
  185. $count = $object->find('count', array_merge($parameters, $extra));
  186. }
  187. $pageCount = intval(ceil($count / $limit));
  188. $requestedPage = $page;
  189. $page = max(min($page, $pageCount), 1);
  190. if ($requestedPage > $page) {
  191. throw new Error\NotFoundException();
  192. }
  193. reset($order);
  194. $paging = array(
  195. 'findType' => $type,
  196. 'page' => $page,
  197. 'current' => count($results),
  198. 'count' => $count,
  199. 'prevPage' => ($page > 1),
  200. 'nextPage' => ($count > ($page * $limit)),
  201. 'pageCount' => $pageCount,
  202. 'sort' => key($order),
  203. 'direction' => current($order),
  204. 'limit' => $defaults['limit'] != $options['limit'] ? $options['limit'] : null,
  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 (
  214. !in_array('Paginator', $this->Controller->helpers) &&
  215. !array_key_exists('Paginator', $this->Controller->helpers)
  216. ) {
  217. $this->Controller->helpers[] = 'Paginator';
  218. }
  219. return $results;
  220. }
  221. /**
  222. * Get the object pagination will occur on.
  223. *
  224. * @param string|Model $object The object you are looking for.
  225. * @return mixed The model object to paginate on.
  226. */
  227. protected function _getObject($object) {
  228. if (is_string($object)) {
  229. $assoc = null;
  230. if (strpos($object, '.') !== false) {
  231. list($object, $assoc) = pluginSplit($object);
  232. }
  233. if ($assoc && isset($this->Controller->{$object}->{$assoc})) {
  234. return $this->Controller->{$object}->{$assoc};
  235. }
  236. if ($assoc && isset($this->Controller->{$this->Controller->modelClass}->{$assoc})) {
  237. return $this->Controller->{$this->Controller->modelClass}->{$assoc};
  238. }
  239. if (isset($this->Controller->{$object})) {
  240. return $this->Controller->{$object};
  241. }
  242. if (isset($this->Controller->{$this->Controller->modelClass}->{$object})) {
  243. return $this->Controller->{$this->Controller->modelClass}->{$object};
  244. }
  245. }
  246. if (empty($object) || $object === null) {
  247. if (isset($this->Controller->{$this->Controller->modelClass})) {
  248. return $this->Controller->{$this->Controller->modelClass};
  249. }
  250. $className = null;
  251. $name = $this->Controller->uses[0];
  252. if (strpos($this->Controller->uses[0], '.') !== false) {
  253. list($name, $className) = explode('.', $this->Controller->uses[0]);
  254. }
  255. if ($className) {
  256. return $this->Controller->{$className};
  257. }
  258. return $this->Controller->{$name};
  259. }
  260. return $object;
  261. }
  262. /**
  263. * Merges the various options that Pagination uses.
  264. * Pulls settings together from the following places:
  265. *
  266. * - General pagination settings
  267. * - Model specific settings.
  268. * - Request parameters
  269. *
  270. * The result of this method is the aggregate of all the option sets combined together. You can change
  271. * PaginatorComponent::$whitelist to modify which options/values can be set using request parameters.
  272. *
  273. * @param string $alias Model alias being paginated, if the general settings has a key with this value
  274. * that key's settings will be used for pagination instead of the general ones.
  275. * @return array Array of merged options.
  276. */
  277. public function mergeOptions($alias) {
  278. $defaults = $this->getDefaults($alias);
  279. $request = $this->Controller->request->query;
  280. $request = array_intersect_key($request, array_flip($this->whitelist));
  281. return array_merge($defaults, $request);
  282. }
  283. /**
  284. * Get the default settings for a $model. If there are no settings for a specific model, the general settings
  285. * will be used.
  286. *
  287. * @param string $alias Model name to get default settings for.
  288. * @return array An array of pagination defaults for a model, or the general settings.
  289. */
  290. public function getDefaults($alias) {
  291. $defaults = $this->settings;
  292. if (isset($this->settings[$alias])) {
  293. $defaults = $this->settings[$alias];
  294. }
  295. if (isset($defaults['limit']) &&
  296. (empty($defaults['maxLimit']) || $defaults['limit'] > $defaults['maxLimit'])
  297. ) {
  298. $defaults['maxLimit'] = $defaults['limit'];
  299. }
  300. return array_merge(
  301. array('page' => 1, 'limit' => 20, 'maxLimit' => 100),
  302. $defaults
  303. );
  304. }
  305. /**
  306. * Validate that the desired sorting can be performed on the $object. Only fields or
  307. * virtualFields can be sorted on. The direction param will also be sanitized. Lastly
  308. * sort + direction keys will be converted into the model friendly order key.
  309. *
  310. * You can use the whitelist parameter to control which columns/fields are available for sorting.
  311. * This helps prevent users from ordering large result sets on un-indexed values.
  312. *
  313. * Any columns listed in the sort whitelist will be implicitly trusted. You can use this to sort
  314. * on synthetic columns, or columns added in custom find operations that may not exist in the schema.
  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 (empty($options['order']) && is_array($object->order)) {
  323. $options['order'] = $object->order;
  324. }
  325. if (isset($options['sort'])) {
  326. $direction = null;
  327. if (isset($options['direction'])) {
  328. $direction = strtolower($options['direction']);
  329. }
  330. if (!in_array($direction, array('asc', 'desc'))) {
  331. $direction = 'asc';
  332. }
  333. $options['order'] = array($options['sort'] => $direction);
  334. }
  335. if (!empty($whitelist) && isset($options['order']) && is_array($options['order'])) {
  336. $field = key($options['order']);
  337. $inWhitelist = in_array($field, $whitelist, true);
  338. if (!$inWhitelist) {
  339. $options['order'] = null;
  340. }
  341. return $options;
  342. }
  343. if (!empty($options['order']) && is_array($options['order'])) {
  344. $order = array();
  345. foreach ($options['order'] as $key => $value) {
  346. $field = $key;
  347. $alias = $object->alias;
  348. if (strpos($key, '.') !== false) {
  349. list($alias, $field) = explode('.', $key);
  350. }
  351. $correctAlias = ($object->alias == $alias);
  352. if ($correctAlias && $object->hasField($field)) {
  353. $order[$object->alias . '.' . $field] = $value;
  354. } elseif ($correctAlias && $object->hasField($key, true)) {
  355. $order[$field] = $value;
  356. } elseif (isset($object->{$alias}) && $object->{$alias}->hasField($field, true)) {
  357. $order[$alias . '.' . $field] = $value;
  358. }
  359. }
  360. $options['order'] = $order;
  361. }
  362. return $options;
  363. }
  364. /**
  365. * Check the limit parameter and ensure its within the maxLimit bounds.
  366. *
  367. * @param array $options An array of options with a limit key to be checked.
  368. * @return array An array of options for pagination
  369. */
  370. public function checkLimit(array $options) {
  371. $options['limit'] = (int)$options['limit'];
  372. if (empty($options['limit']) || $options['limit'] < 1) {
  373. $options['limit'] = 1;
  374. }
  375. $options['limit'] = min($options['limit'], $options['maxLimit']);
  376. return $options;
  377. }
  378. }