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

  • Overview
  • Tree
  • Deprecated
  • Version:
    • 2.1
      • 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
    • 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-2012, 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-2012, 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:         $page = max(min($page, $pageCount), 1);
188: 
189:         $paging = array(
190:             'page' => $page,
191:             'current' => count($results),
192:             'count' => $count,
193:             'prevPage' => ($page > 1),
194:             'nextPage' => ($count > ($page * $limit)),
195:             'pageCount' => $pageCount,
196:             'order' => $order,
197:             'limit' => $limit,
198:             'options' => Set::diff($options, $defaults),
199:             'paramType' => $options['paramType']
200:         );
201:         if (!isset($this->Controller->request['paging'])) {
202:             $this->Controller->request['paging'] = array();
203:         }
204:         $this->Controller->request['paging'] = array_merge(
205:             (array)$this->Controller->request['paging'],
206:             array($object->alias => $paging)
207:         );
208: 
209:         if (
210:             !in_array('Paginator', $this->Controller->helpers) &&
211:             !array_key_exists('Paginator', $this->Controller->helpers)
212:         ) {
213:             $this->Controller->helpers[] = 'Paginator';
214:         }
215:         return $results;
216:     }
217: 
218: /**
219:  * Get the object pagination will occur on.
220:  *
221:  * @param mixed $object The object you are looking for.
222:  * @return mixed The model object to paginate on.
223:  */
224:     protected function _getObject($object) {
225:         if (is_string($object)) {
226:             $assoc = null;
227:             if (strpos($object, '.') !== false) {
228:                 list($object, $assoc) = pluginSplit($object);
229:             }
230: 
231:             if ($assoc && isset($this->Controller->{$object}->{$assoc})) {
232:                 $object = $this->Controller->{$object}->{$assoc};
233:             } elseif (
234:                 $assoc && isset($this->Controller->{$this->Controller->modelClass}) &&
235:                 isset($this->Controller->{$this->Controller->modelClass}->{$assoc}
236:             )) {
237:                 $object = $this->Controller->{$this->Controller->modelClass}->{$assoc};
238:             } elseif (isset($this->Controller->{$object})) {
239:                 $object = $this->Controller->{$object};
240:             } elseif (
241:                 isset($this->Controller->{$this->Controller->modelClass}) && isset($this->Controller->{$this->Controller->modelClass}->{$object}
242:             )) {
243:                 $object = $this->Controller->{$this->Controller->modelClass}->{$object};
244:             }
245:         } elseif (empty($object) || $object === null) {
246:             if (isset($this->Controller->{$this->Controller->modelClass})) {
247:                 $object = $this->Controller->{$this->Controller->modelClass};
248:             } else {
249:                 $className = null;
250:                 $name = $this->Controller->uses[0];
251:                 if (strpos($this->Controller->uses[0], '.') !== false) {
252:                     list($name, $className) = explode('.', $this->Controller->uses[0]);
253:                 }
254:                 if ($className) {
255:                     $object = $this->Controller->{$className};
256:                 } else {
257:                     $object = $this->Controller->{$name};
258:                 }
259:             }
260:         }
261:         return $object;
262:     }
263: 
264: /**
265:  * Merges the various options that Pagination uses.
266:  * Pulls settings together from the following places:
267:  *
268:  * - General pagination settings
269:  * - Model specific settings.
270:  * - Request parameters
271:  *
272:  * The result of this method is the aggregate of all the option sets combined together.  You can change
273:  * PaginatorComponent::$whitelist to modify which options/values can be set using request parameters.
274:  *
275:  * @param string $alias Model alias being paginated, if the general settings has a key with this value
276:  *   that key's settings will be used for pagination instead of the general ones.
277:  * @return array Array of merged options.
278:  */
279:     public function mergeOptions($alias) {
280:         $defaults = $this->getDefaults($alias);
281:         switch ($defaults['paramType']) {
282:             case 'named':
283:                 $request = $this->Controller->request->params['named'];
284:                 break;
285:             case 'querystring':
286:                 $request = $this->Controller->request->query;
287:                 break;
288:         }
289:         $request = array_intersect_key($request, array_flip($this->whitelist));
290:         return array_merge($defaults, $request);
291:     }
292: 
293: /**
294:  * Get the default settings for a $model.  If there are no settings for a specific model, the general settings
295:  * will be used.
296:  *
297:  * @param string $alias Model name to get default settings for.
298:  * @return array An array of pagination defaults for a model, or the general settings.
299:  */
300:     public function getDefaults($alias) {
301:         if (isset($this->settings[$alias])) {
302:             $defaults = $this->settings[$alias];
303:         } else {
304:             $defaults = $this->settings;
305:         }
306:         return array_merge(
307:             array('page' => 1, 'limit' => 20, 'maxLimit' => 100, 'paramType' => 'named'),
308:             $defaults
309:         );
310:     }
311: 
312: /**
313:  * Validate that the desired sorting can be performed on the $object.  Only fields or
314:  * virtualFields can be sorted on.  The direction param will also be sanitized.  Lastly
315:  * sort + direction keys will be converted into the model friendly order key.
316:  *
317:  * You can use the whitelist parameter to control which columns/fields are available for sorting.
318:  * This helps prevent users from ordering large result sets on un-indexed values.
319:  *
320:  * @param Model $object The model being paginated.
321:  * @param array $options The pagination options being used for this request.
322:  * @param array $whitelist The list of columns that can be used for sorting.  If empty all keys are allowed.
323:  * @return array An array of options with sort + direction removed and replaced with order if possible.
324:  */
325:     public function validateSort($object, $options, $whitelist = array()) {
326:         if (isset($options['sort'])) {
327:             $direction = null;
328:             if (isset($options['direction'])) {
329:                 $direction = strtolower($options['direction']);
330:             }
331:             if ($direction != 'asc' && $direction != 'desc') {
332:                 $direction = 'asc';
333:             }
334:             $options['order'] = array($options['sort'] => $direction);
335:         }
336: 
337:         if (!empty($whitelist) && isset($options['order']) && is_array($options['order'])) {
338:             $field = key($options['order']);
339:             if (!in_array($field, $whitelist)) {
340:                 $options['order'] = null;
341:             }
342:         }
343: 
344:         if (!empty($options['order']) && is_array($options['order'])) {
345:             $order = array();
346:             foreach ($options['order'] as $key => $value) {
347:                 $field = $key;
348:                 $alias = $object->alias;
349:                 if (strpos($key, '.') !== false) {
350:                     list($alias, $field) = explode('.', $key);
351:                 }
352: 
353:                 if ($object->hasField($field)) {
354:                     $order[$alias . '.' . $field] = $value;
355:                 } elseif ($object->hasField($key, true)) {
356:                     $order[$field] = $value;
357:                 } elseif (isset($object->{$alias}) && $object->{$alias}->hasField($field, true)) {
358:                     $order[$alias . '.' . $field] = $value;
359:                 }
360:             }
361:             $options['order'] = $order;
362:         }
363: 
364:         return $options;
365:     }
366: 
367: /**
368:  * Check the limit parameter and ensure its within the maxLimit bounds.
369:  *
370:  * @param array $options An array of options with a limit key to be checked.
371:  * @return array An array of options for pagination
372:  */
373:     public function checkLimit($options) {
374:         $options['limit'] = (int)$options['limit'];
375:         if (empty($options['limit']) || $options['limit'] < 1) {
376:             $options['limit'] = 1;
377:         }
378:         $options['limit'] = min($options['limit'], $options['maxLimit']);
379:         return $options;
380:     }
381: 
382: }
383: 
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