CakePHP
  • Documentation
    • Book
    • API
    • Videos
    • Reporting Security Issues
    • Privacy Policy
    • Logos & Trademarks
  • Business Solutions
  • Swag
  • Road Trip
  • Team
  • Community
    • Community
    • Get Involved
    • Issues (GitHub)
    • Bakery
    • Featured Resources
    • Training
    • Meetups
    • My CakePHP
    • CakeFest
    • Newsletter
    • Linkedin
    • YouTube
    • Facebook
    • Twitter
    • Mastodon
    • Help & Support
    • Forum
    • Stack Overflow
    • Slack
    • Paid Support
CakePHP

C CakePHP 2.3 API

  • Overview
  • Tree
  • Deprecated
  • Version:
    • 2.3
      • 4.2
      • 4.1
      • 4.0
      • 3.9
      • 3.8
      • 3.7
      • 3.6
      • 3.5
      • 3.4
      • 3.3
      • 3.2
      • 3.1
      • 3.0
      • 2.10
      • 2.9
      • 2.8
      • 2.7
      • 2.6
      • 2.5
      • 2.4
      • 2.3
      • 2.2
      • 2.1
      • 2.0
      • 1.3
      • 1.2

Packages

  • Cake
    • Cache
      • Engine
    • Configure
    • Console
      • Command
        • Task
    • Controller
      • Component
        • Acl
        • Auth
    • Core
    • Error
    • Event
    • I18n
    • Log
      • Engine
    • Model
      • Behavior
      • Datasource
        • Database
        • Session
      • Validator
    • Network
      • Email
      • Http
    • Routing
      • Filter
      • Route
    • TestSuite
      • Coverage
      • Fixture
      • Reporter
    • Utility
    • View
      • Helper

Classes

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

Generated using CakePHP API Docs