PageRenderTime 57ms CodeModel.GetById 20ms RepoModel.GetById 0ms app.codeStats 0ms

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

https://bitbucket.org/udeshika/fake_twitter
PHP | 380 lines | 215 code | 30 blank | 135 comment | 49 complexity | f94b7705f88549872c8242158564c4e9 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-2011, 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-2011, 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. /**
  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 convenience 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.Controller.Component
  52. * @link http://book.cakephp.org/2.0/en/core-libraries/components/pagination.html
  53. */
  54. class PaginatorComponent extends Component {
  55. /**
  56. * Pagination settings. These settings control pagination at a general level.
  57. * You can also define sub arrays for pagination settings for specific models.
  58. *
  59. * - `maxLimit` The maximum limit users can choose to view. Defaults to 100
  60. * - `limit` The initial number of items per page. Defaults to 20.
  61. * - `page` The starting page, defaults to 1.
  62. * - `paramType` What type of parameters you want pagination to use?
  63. * - `named` Use named parameters / routed parameters.
  64. * - `querystring` Use query string parameters.
  65. *
  66. * @var array
  67. */
  68. public $settings = array(
  69. 'page' => 1,
  70. 'limit' => 20,
  71. 'maxLimit' => 100,
  72. 'paramType' => 'named'
  73. );
  74. /**
  75. * A list of parameters users are allowed to set using request parameters. Modifying
  76. * this list will allow users to have more influence over pagination,
  77. * be careful with what you permit.
  78. *
  79. * @var array
  80. */
  81. public $whitelist = array(
  82. 'limit', 'sort', 'page', 'direction'
  83. );
  84. /**
  85. * Constructor
  86. *
  87. * @param ComponentCollection $collection A ComponentCollection this component can use to lazy load its components
  88. * @param array $settings Array of configuration settings.
  89. */
  90. public function __construct(ComponentCollection $collection, $settings = array()) {
  91. $settings = array_merge($this->settings, (array)$settings);
  92. $this->Controller = $collection->getController();
  93. parent::__construct($collection, $settings);
  94. }
  95. /**
  96. * Handles automatic pagination of model records.
  97. *
  98. * @param mixed $object Model to paginate (e.g: model instance, or 'Model', or 'Model.InnerModel')
  99. * @param mixed $scope Additional find conditions to use while paginating
  100. * @param array $whitelist List of allowed fields for ordering. This allows you to prevent ordering
  101. * on non-indexed, or undesirable columns.
  102. * @return array Model query results
  103. * @throws MissingModelException
  104. */
  105. public function paginate($object = null, $scope = array(), $whitelist = array()) {
  106. if (is_array($object)) {
  107. $whitelist = $scope;
  108. $scope = $object;
  109. $object = null;
  110. }
  111. $object = $this->_getObject($object);
  112. if (!is_object($object)) {
  113. throw new MissingModelException($object);
  114. }
  115. $options = $this->mergeOptions($object->alias);
  116. $options = $this->validateSort($object, $options, $whitelist);
  117. $options = $this->checkLimit($options);
  118. $conditions = $fields = $order = $limit = $page = $recursive = null;
  119. if (!isset($options['conditions'])) {
  120. $options['conditions'] = array();
  121. }
  122. $type = 'all';
  123. if (isset($options[0])) {
  124. $type = $options[0];
  125. unset($options[0]);
  126. }
  127. extract($options);
  128. if (is_array($scope) && !empty($scope)) {
  129. $conditions = array_merge($conditions, $scope);
  130. } elseif (is_string($scope)) {
  131. $conditions = array($conditions, $scope);
  132. }
  133. if ($recursive === null) {
  134. $recursive = $object->recursive;
  135. }
  136. $extra = array_diff_key($options, compact(
  137. 'conditions', 'fields', 'order', 'limit', 'page', 'recursive'
  138. ));
  139. if ($type !== 'all') {
  140. $extra['type'] = $type;
  141. }
  142. if (intval($page) < 1) {
  143. $page = 1;
  144. }
  145. $page = $options['page'] = (int)$page;
  146. if ($object->hasMethod('paginate')) {
  147. $results = $object->paginate(
  148. $conditions, $fields, $order, $limit, $page, $recursive, $extra
  149. );
  150. } else {
  151. $parameters = compact('conditions', 'fields', 'order', 'limit', 'page');
  152. if ($recursive != $object->recursive) {
  153. $parameters['recursive'] = $recursive;
  154. }
  155. $results = $object->find($type, array_merge($parameters, $extra));
  156. }
  157. $defaults = $this->getDefaults($object->alias);
  158. unset($defaults[0]);
  159. if ($object->hasMethod('paginateCount')) {
  160. $count = $object->paginateCount($conditions, $recursive, $extra);
  161. } else {
  162. $parameters = compact('conditions');
  163. if ($recursive != $object->recursive) {
  164. $parameters['recursive'] = $recursive;
  165. }
  166. $count = $object->find('count', array_merge($parameters, $extra));
  167. }
  168. $pageCount = intval(ceil($count / $limit));
  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. $order = array();
  318. foreach ($options['order'] as $key => $value) {
  319. $field = $key;
  320. $alias = $object->alias;
  321. if (strpos($key, '.') !== false) {
  322. list($alias, $field) = explode('.', $key);
  323. }
  324. if ($object->hasField($field)) {
  325. $order[$alias . '.' . $field] = $value;
  326. } elseif ($object->hasField($key, true)) {
  327. $order[$field] = $value;
  328. } elseif (isset($object->{$alias}) && $object->{$alias}->hasField($field, true)) {
  329. $order[$alias . '.' . $field] = $value;
  330. }
  331. }
  332. $options['order'] = $order;
  333. }
  334. return $options;
  335. }
  336. /**
  337. * Check the limit parameter and ensure its within the maxLimit bounds.
  338. *
  339. * @param array $options An array of options with a limit key to be checked.
  340. * @return array An array of options for pagination
  341. */
  342. public function checkLimit($options) {
  343. $options['limit'] = (int) $options['limit'];
  344. if (empty($options['limit']) || $options['limit'] < 1) {
  345. $options['limit'] = 1;
  346. }
  347. $options['limit'] = min((int)$options['limit'], $options['maxLimit']);
  348. return $options;
  349. }
  350. }