PageRenderTime 49ms CodeModel.GetById 18ms RepoModel.GetById 0ms app.codeStats 0ms

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

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