PageRenderTime 58ms CodeModel.GetById 23ms RepoModel.GetById 0ms app.codeStats 0ms

/lib/Cake/Controller/Component/PaginatorComponent.php

https://github.com/Bancha/cakephp
PHP | 379 lines | 215 code | 31 blank | 133 comment | 50 complexity | d949002e3e632024aa4dfbdb5e9fe9df MD5 | raw file
  1. <?php
  2. /**
  3. * Paginator Component
  4. *
  5. * PHP 5
  6. *
  7. * CakePHP(tm) : Rapid Development Framework (http://cakephp.org)
  8. * Copyright 2005-2010, 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-2010, Cake Software Foundation, Inc. (http://cakefoundation.org)
  14. * @link http://cakephp.org CakePHP(tm) Project
  15. * @package cake.libs.controller.components
  16. * @since CakePHP(tm) v 2.0
  17. * @license MIT License (http://www.opensource.org/licenses/mit-license.php)
  18. */
  19. /**
  20. * This component is used to handle automatic model data pagination. The primary way to use this
  21. * component is to call the paginate() method. There is a convience wrapper on Controller as well.
  22. *
  23. * ### Configuring pagination
  24. *
  25. * You configure pagination using the PaginatorComponent::$settings. This allows you to configure
  26. * the default pagination behavior in general or for a specific model. General settings are used when there
  27. * are no specific model configuration, or the model you are paginating does not have specific settings.
  28. *
  29. * {{{
  30. * $this->Paginator->settings = array(
  31. * 'limit' => 20,
  32. * 'maxLimit' => 100
  33. * );
  34. * }}}
  35. *
  36. * The above settings will be used to paginate any model. You can configure model specific settings by
  37. * keying the settings with the model name.
  38. *
  39. * {{{
  40. * $this->Paginator->settings = array(
  41. * 'Post' => array(
  42. * 'limit' => 20,
  43. * 'maxLimit' => 100
  44. * ),
  45. * 'Comment' => array( ... )
  46. * );
  47. * }}}
  48. *
  49. * This would allow you to have different pagination settings for `Comment` and `Post` models.
  50. *
  51. * @package cake.libs.controller.components
  52. */
  53. class PaginatorComponent extends Component {
  54. /**
  55. * Pagination settings. These settings control pagination at a general level.
  56. * You can also define sub arrays for pagination settings for specific models.
  57. *
  58. * - `maxLimit` The maximum limit users can choose to view. Defaults to 100
  59. * - `limit` The initial number of items per page. Defaults to 20.
  60. * - `page` The starting page, defaults to 1.
  61. * - `paramType` What type of parameters you want pagination to use?
  62. * - `named` Use named parameters / routed parameters.
  63. * - `querystring` Use query string parameters.
  64. *
  65. * @var array
  66. */
  67. public $settings = array(
  68. 'page' => 1,
  69. 'limit' => 20,
  70. 'maxLimit' => 100,
  71. 'paramType' => 'named'
  72. );
  73. /**
  74. * A list of parameters users are allowed to set using request parameters. Modifying
  75. * this list will allow users to have more influence over pagination,
  76. * be careful with what you permit.
  77. *
  78. * @var array
  79. */
  80. public $whitelist = array(
  81. 'limit', 'sort', 'page', 'direction'
  82. );
  83. /**
  84. * Constructor
  85. *
  86. * @param ComponentCollection $collection A ComponentCollection this component can use to lazy load its components
  87. * @param array $settings Array of configuration settings.
  88. */
  89. public function __construct(ComponentCollection $collection, $settings = array()) {
  90. $settings = array_merge($this->settings, (array)$settings);
  91. $this->Controller = $collection->getController();
  92. parent::__construct($collection, $settings);
  93. }
  94. /**
  95. * Handles automatic pagination of model records.
  96. *
  97. * @param mixed $object Model to paginate (e.g: model instance, or 'Model', or 'Model.InnerModel')
  98. * @param mixed $scope Additional find conditions to use while paginating
  99. * @param array $whitelist List of allowed fields for ordering. This allows you to prevent ordering
  100. * on non-indexed, or undesirable columns.
  101. * @return array Model query results
  102. */
  103. public function paginate($object = null, $scope = array(), $whitelist = array()) {
  104. if (is_array($object)) {
  105. $whitelist = $scope;
  106. $scope = $object;
  107. $object = null;
  108. }
  109. $object = $this->_getObject($object);
  110. if (!is_object($object)) {
  111. throw new MissingModelException($object);
  112. }
  113. $options = $this->mergeOptions($object->alias);
  114. $options = $this->validateSort($object, $options, $whitelist);
  115. $options = $this->checkLimit($options);
  116. $conditions = $fields = $order = $limit = $page = $recursive = null;
  117. if (!isset($options['conditions'])) {
  118. $options['conditions'] = array();
  119. }
  120. $type = 'all';
  121. if (isset($options[0])) {
  122. $type = $options[0];
  123. unset($options[0]);
  124. }
  125. extract($options);
  126. if (is_array($scope) && !empty($scope)) {
  127. $conditions = array_merge($conditions, $scope);
  128. } elseif (is_string($scope)) {
  129. $conditions = array($conditions, $scope);
  130. }
  131. if ($recursive === null) {
  132. $recursive = $object->recursive;
  133. }
  134. $extra = array_diff_key($options, compact(
  135. 'conditions', 'fields', 'order', 'limit', 'page', 'recursive'
  136. ));
  137. if ($type !== 'all') {
  138. $extra['type'] = $type;
  139. }
  140. if ($object->hasMethod('paginateCount')) {
  141. $count = $object->paginateCount($conditions, $recursive, $extra);
  142. } else {
  143. $parameters = compact('conditions');
  144. if ($recursive != $object->recursive) {
  145. $parameters['recursive'] = $recursive;
  146. }
  147. $count = $object->find('count', array_merge($parameters, $extra));
  148. }
  149. $pageCount = intval(ceil($count / $limit));
  150. if ($page === 'last' || $page >= $pageCount) {
  151. $options['page'] = $page = $pageCount;
  152. } elseif (intval($page) < 1) {
  153. $options['page'] = $page = 1;
  154. }
  155. $page = $options['page'] = (int)$page;
  156. if ($object->hasMethod('paginate')) {
  157. $results = $object->paginate(
  158. $conditions, $fields, $order, $limit, $page, $recursive, $extra
  159. );
  160. } else {
  161. $parameters = compact('conditions', 'fields', 'order', 'limit', 'page');
  162. if ($recursive != $object->recursive) {
  163. $parameters['recursive'] = $recursive;
  164. }
  165. $results = $object->find($type, array_merge($parameters, $extra));
  166. }
  167. $defaults = $this->getDefaults($object->alias);
  168. unset($defaults[0]);
  169. $paging = array(
  170. 'page' => $page,
  171. 'current' => count($results),
  172. 'count' => $count,
  173. 'prevPage' => ($page > 1),
  174. 'nextPage' => ($count > ($page * $limit)),
  175. 'pageCount' => $pageCount,
  176. 'order' => $order,
  177. 'limit' => $limit,
  178. 'options' => Set::diff($options, $defaults),
  179. 'paramType' => $options['paramType']
  180. );
  181. if (!isset($this->Controller->request['paging'])) {
  182. $this->Controller->request['paging'] = array();
  183. }
  184. $this->Controller->request['paging'] = array_merge(
  185. (array)$this->Controller->request['paging'],
  186. array($object->alias => $paging)
  187. );
  188. if (
  189. !in_array('Paginator', $this->Controller->helpers) &&
  190. !array_key_exists('Paginator', $this->Controller->helpers)
  191. ) {
  192. $this->Controller->helpers[] = 'Paginator';
  193. }
  194. return $results;
  195. }
  196. /**
  197. * Get the object pagination will occur on.
  198. *
  199. * @param mixed $object The object you are looking for.
  200. * @return mixed The model object to paginate on.
  201. */
  202. protected function _getObject($object) {
  203. if (is_string($object)) {
  204. $assoc = null;
  205. if (strpos($object, '.') !== false) {
  206. list($object, $assoc) = pluginSplit($object);
  207. }
  208. if ($assoc && isset($this->Controller->{$object}->{$assoc})) {
  209. $object = $this->Controller->{$object}->{$assoc};
  210. } elseif (
  211. $assoc && isset($this->Controller->{$this->Controller->modelClass}) &&
  212. isset($this->Controller->{$this->Controller->modelClass}->{$assoc}
  213. )) {
  214. $object = $this->Controller->{$this->Controller->modelClass}->{$assoc};
  215. } elseif (isset($this->Controller->{$object})) {
  216. $object = $this->Controller->{$object};
  217. } elseif (
  218. isset($this->Controller->{$this->Controller->modelClass}) && isset($this->Controller->{$this->Controller->modelClass}->{$object}
  219. )) {
  220. $object = $this->Controller->{$this->Controller->modelClass}->{$object};
  221. }
  222. } elseif (empty($object) || $object === null) {
  223. if (isset($this->Controller->{$this->Controller->modelClass})) {
  224. $object = $this->Controller->{$this->Controller->modelClass};
  225. } else {
  226. $className = null;
  227. $name = $this->Controller->uses[0];
  228. if (strpos($this->Controller->uses[0], '.') !== false) {
  229. list($name, $className) = explode('.', $this->Controller->uses[0]);
  230. }
  231. if ($className) {
  232. $object = $this->Controller->{$className};
  233. } else {
  234. $object = $this->Controller->{$name};
  235. }
  236. }
  237. }
  238. return $object;
  239. }
  240. /**
  241. * Merges the various options that Pagination uses.
  242. * Pulls settings together from the following places:
  243. *
  244. * - General pagination settings
  245. * - Model specific settings.
  246. * - Request parameters
  247. *
  248. * The result of this method is the aggregate of all the option sets combined together. You can change
  249. * PaginatorComponent::$whitelist to modify which options/values can be set using request parameters.
  250. *
  251. * @param string $alias Model alias being paginated, if the general settings has a key with this value
  252. * that key's settings will be used for pagination instead of the general ones.
  253. * @return array Array of merged options.
  254. */
  255. public function mergeOptions($alias) {
  256. $defaults = $this->getDefaults($alias);
  257. switch ($defaults['paramType']) {
  258. case 'named':
  259. $request = $this->Controller->request->params['named'];
  260. break;
  261. case 'querystring':
  262. $request = $this->Controller->request->query;
  263. break;
  264. }
  265. $request = array_intersect_key($request, array_flip($this->whitelist));
  266. return array_merge($defaults, $request);
  267. }
  268. /**
  269. * Get the default settings for a $model. If there are no settings for a specific model, the general settings
  270. * will be used.
  271. *
  272. * @param string $alias Model name to get default settings for.
  273. * @return array An array of pagination defaults for a model, or the general settings.
  274. */
  275. public function getDefaults($alias) {
  276. if (isset($this->settings[$alias])) {
  277. $defaults = $this->settings[$alias];
  278. } else {
  279. $defaults = $this->settings;
  280. }
  281. return array_merge(
  282. array('page' => 1, 'limit' => 20, 'maxLimit' => 100, 'paramType' => 'named'),
  283. $defaults
  284. );
  285. }
  286. /**
  287. * Validate that the desired sorting can be performed on the $object. Only fields or
  288. * virtualFields can be sorted on. The direction param will also be sanitized. Lastly
  289. * sort + direction keys will be converted into the model friendly order key.
  290. *
  291. * You can use the whitelist parameter to control which columns/fields are available for sorting.
  292. * This helps prevent users from ordering large result sets on un-indexed values.
  293. *
  294. * @param Model $object The model being paginated.
  295. * @param array $options The pagination options being used for this request.
  296. * @param array $whitelist The list of columns that can be used for sorting. If empty all keys are allowed.
  297. * @return array An array of options with sort + direction removed and replaced with order if possible.
  298. */
  299. public function validateSort($object, $options, $whitelist = array()) {
  300. if (isset($options['sort'])) {
  301. $direction = null;
  302. if (isset($options['direction'])) {
  303. $direction = strtolower($options['direction']);
  304. }
  305. if ($direction != 'asc' && $direction != 'desc') {
  306. $direction = 'asc';
  307. }
  308. $options['order'] = array($options['sort'] => $direction);
  309. }
  310. if (!empty($whitelist)) {
  311. $field = key($options['order']);
  312. if (!in_array($field, $whitelist)) {
  313. $options['order'] = null;
  314. }
  315. }
  316. if (!empty($options['order']) && is_array($options['order'])) {
  317. $alias = $object->alias ;
  318. $key = $field = key($options['order']);
  319. if (strpos($key, '.') !== false) {
  320. list($alias, $field) = explode('.', $key);
  321. }
  322. $value = $options['order'][$key];
  323. unset($options['order'][$key]);
  324. if ($object->hasField($field)) {
  325. $options['order'][$alias . '.' . $field] = $value;
  326. } elseif ($object->hasField($field, true)) {
  327. $options['order'][$field] = $value;
  328. } elseif (isset($object->{$alias}) && $object->{$alias}->hasField($field)) {
  329. $options['order'][$alias . '.' . $field] = $value;
  330. }
  331. }
  332. return $options;
  333. }
  334. /**
  335. * Check the limit parameter and ensure its within the maxLimit bounds.
  336. *
  337. * @param array $options An array of options with a limit key to be checked.
  338. * @return array An array of options for pagination
  339. */
  340. public function checkLimit($options) {
  341. $options['limit'] = (int) $options['limit'];
  342. if (empty($options['limit']) || $options['limit'] < 1) {
  343. $options['limit'] = 1;
  344. }
  345. $options['limit'] = min((int)$options['limit'], $options['maxLimit']);
  346. return $options;
  347. }
  348. }