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.0 API

  • Overview
  • Tree
  • Deprecated
  • Version:
    • 2.0
      • 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
        • Auth
    • Core
    • Error
    • I18n
    • Log
      • Engine
    • Model
      • Behavior
      • Datasource
        • Database
        • Session
    • Network
      • Email
      • Http
    • Routing
      • Route
    • TestSuite
      • Coverage
      • Fixture
      • Reporter
    • Utility
    • View
      • Helper

Classes

  • AclComponent
  • AuthComponent
  • CookieComponent
  • DbAcl
  • EmailComponent
  • IniAcl
  • PaginatorComponent
  • RequestHandlerComponent
  • SecurityComponent
  • SessionComponent

Interfaces

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