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

  • AclBehavior
  • ContainableBehavior
  • TranslateBehavior
  • TreeBehavior
  1: <?php
  2: /**
  3:  * Behavior for binding management.
  4:  *
  5:  * Behavior to simplify manipulating a model's bindings when doing a find operation
  6:  *
  7:  * PHP 5
  8:  *
  9:  * CakePHP(tm) : Rapid Development Framework (http://cakephp.org)
 10:  * Copyright 2005-2012, Cake Software Foundation, Inc. (http://cakefoundation.org)
 11:  *
 12:  * Licensed under The MIT License
 13:  * Redistributions of files must retain the above copyright notice.
 14:  *
 15:  * @copyright     Copyright 2005-2012, Cake Software Foundation, Inc. (http://cakefoundation.org)
 16:  * @link          http://cakephp.org CakePHP(tm) Project
 17:  * @package       Cake.Model.Behavior
 18:  * @since         CakePHP(tm) v 1.2.0.5669
 19:  * @license       MIT License (http://www.opensource.org/licenses/mit-license.php)
 20:  */
 21: 
 22: /**
 23:  * Behavior to allow for dynamic and atomic manipulation of a Model's associations 
 24:  * used for a find call. Most useful for limiting the amount of associations and 
 25:  * data returned.
 26:  *
 27:  * @package       Cake.Model.Behavior
 28:  * @link http://book.cakephp.org/2.0/en/core-libraries/behaviors/containable.html
 29:  */
 30: class ContainableBehavior extends ModelBehavior {
 31: 
 32: /**
 33:  * Types of relationships available for models
 34:  *
 35:  * @var array
 36:  */
 37:     public $types = array('belongsTo', 'hasOne', 'hasMany', 'hasAndBelongsToMany');
 38: 
 39: /**
 40:  * Runtime configuration for this behavior
 41:  *
 42:  * @var array
 43:  */
 44:     public $runtime = array();
 45: 
 46: /**
 47:  * Initiate behavior for the model using specified settings.
 48:  *
 49:  * Available settings:
 50:  *
 51:  * - recursive: (boolean, optional) set to true to allow containable to automatically
 52:  *   determine the recursiveness level needed to fetch specified models,
 53:  *   and set the model recursiveness to this level. setting it to false
 54:  *   disables this feature. DEFAULTS TO: true
 55:  * - notices: (boolean, optional) issues E_NOTICES for bindings referenced in a
 56:  *   containable call that are not valid. DEFAULTS TO: true
 57:  * - autoFields: (boolean, optional) auto-add needed fields to fetch requested
 58:  *   bindings. DEFAULTS TO: true
 59:  *
 60:  * @param Model $Model Model using the behavior
 61:  * @param array $settings Settings to override for model.
 62:  * @return void
 63:  */
 64:     public function setup(Model $Model, $settings = array()) {
 65:         if (!isset($this->settings[$Model->alias])) {
 66:             $this->settings[$Model->alias] = array('recursive' => true, 'notices' => true, 'autoFields' => true);
 67:         }
 68:         $this->settings[$Model->alias] = array_merge($this->settings[$Model->alias], $settings);
 69:     }
 70: 
 71: /**
 72:  * Runs before a find() operation. Used to allow 'contain' setting
 73:  * as part of the find call, like this:
 74:  *
 75:  * `Model->find('all', array('contain' => array('Model1', 'Model2')));`
 76:  *
 77:  * {{{
 78:  * Model->find('all', array('contain' => array(
 79:  *  'Model1' => array('Model11', 'Model12'),
 80:  *  'Model2',
 81:  *  'Model3' => array(
 82:  *      'Model31' => 'Model311',
 83:  *      'Model32',
 84:  *      'Model33' => array('Model331', 'Model332')
 85:  * )));
 86:  * }}}
 87:  *
 88:  * @param Model $Model  Model using the behavior
 89:  * @param array $query Query parameters as set by cake
 90:  * @return array
 91:  */
 92:     public function beforeFind(Model $Model, $query) {
 93:         $reset = (isset($query['reset']) ? $query['reset'] : true);
 94:         $noContain = (
 95:             (isset($this->runtime[$Model->alias]['contain']) && empty($this->runtime[$Model->alias]['contain'])) ||
 96:             (isset($query['contain']) && empty($query['contain']))
 97:         );
 98:         $contain = array();
 99:         if (isset($this->runtime[$Model->alias]['contain'])) {
100:             $contain = $this->runtime[$Model->alias]['contain'];
101:             unset($this->runtime[$Model->alias]['contain']);
102:         }
103:         if (isset($query['contain'])) {
104:             $contain = array_merge($contain, (array)$query['contain']);
105:         }
106:         if (
107:             $noContain || !$contain || in_array($contain, array(null, false), true) ||
108:             (isset($contain[0]) && $contain[0] === null)
109:         ) {
110:             if ($noContain) {
111:                 $query['recursive'] = -1;
112:             }
113:             return $query;
114:         }
115:         if ((isset($contain[0]) && is_bool($contain[0])) || is_bool(end($contain))) {
116:             $reset = is_bool(end($contain))
117:                 ? array_pop($contain)
118:                 : array_shift($contain);
119:         }
120:         $containments = $this->containments($Model, $contain);
121:         $map = $this->containmentsMap($containments);
122: 
123:         $mandatory = array();
124:         foreach ($containments['models'] as $name => $model) {
125:             $instance = $model['instance'];
126:             $needed = $this->fieldDependencies($instance, $map, false);
127:             if (!empty($needed)) {
128:                 $mandatory = array_merge($mandatory, $needed);
129:             }
130:             if ($contain) {
131:                 $backupBindings = array();
132:                 foreach ($this->types as $relation) {
133:                     if (!empty($instance->__backAssociation[$relation])) {
134:                         $backupBindings[$relation] = $instance->__backAssociation[$relation];
135:                     } else {
136:                         $backupBindings[$relation] = $instance->{$relation};
137:                     }
138:                 }
139:                 foreach ($this->types as $type) {
140:                     $unbind = array();
141:                     foreach ($instance->{$type} as $assoc => $options) {
142:                         if (!isset($model['keep'][$assoc])) {
143:                             $unbind[] = $assoc;
144:                         }
145:                     }
146:                     if (!empty($unbind)) {
147:                         if (!$reset && empty($instance->__backOriginalAssociation)) {
148:                             $instance->__backOriginalAssociation = $backupBindings;
149:                         }
150:                         $instance->unbindModel(array($type => $unbind), $reset);
151:                     }
152:                     foreach ($instance->{$type} as $assoc => $options) {
153:                         if (isset($model['keep'][$assoc]) && !empty($model['keep'][$assoc])) {
154:                             if (isset($model['keep'][$assoc]['fields'])) {
155:                                 $model['keep'][$assoc]['fields'] = $this->fieldDependencies($containments['models'][$assoc]['instance'], $map, $model['keep'][$assoc]['fields']);
156:                             }
157:                             if (!$reset && empty($instance->__backOriginalAssociation)) {
158:                                 $instance->__backOriginalAssociation = $backupBindings;
159:                             } elseif ($reset) {
160:                                 $instance->__backAssociation[$type] = $backupBindings[$type];
161:                             }
162:                             $instance->{$type}[$assoc] = array_merge($instance->{$type}[$assoc], $model['keep'][$assoc]);
163:                         }
164:                         if (!$reset) {
165:                             $instance->__backInnerAssociation[] = $assoc;
166:                         }
167:                     }
168:                 }
169:             }
170:         }
171: 
172:         if ($this->settings[$Model->alias]['recursive']) {
173:             $query['recursive'] = (isset($query['recursive'])) ? $query['recursive'] : $containments['depth'];
174:         }
175: 
176:         $autoFields = ($this->settings[$Model->alias]['autoFields']
177:                     && !in_array($Model->findQueryType, array('list', 'count'))
178:                     && !empty($query['fields']));
179: 
180:         if (!$autoFields) {
181:             return $query;
182:         }
183: 
184:         $query['fields'] = (array)$query['fields'];
185:         foreach (array('hasOne', 'belongsTo') as $type) {
186:             if (!empty($Model->{$type})) {
187:                 foreach ($Model->{$type} as $assoc => $data) {
188:                     if ($Model->useDbConfig == $Model->{$assoc}->useDbConfig && !empty($data['fields'])) {
189:                         foreach ((array)$data['fields'] as $field) {
190:                             $query['fields'][] = (strpos($field, '.') === false ? $assoc . '.' : '') . $field;
191:                         }
192:                     }
193:                 }
194:             }
195:         }
196: 
197:         if (!empty($mandatory[$Model->alias])) {
198:             foreach ($mandatory[$Model->alias] as $field) {
199:                 if ($field == '--primaryKey--') {
200:                     $field = $Model->primaryKey;
201:                 } elseif (preg_match('/^.+\.\-\-[^-]+\-\-$/', $field)) {
202:                     list($modelName, $field) = explode('.', $field);
203:                     if ($Model->useDbConfig == $Model->{$modelName}->useDbConfig) {
204:                         $field = $modelName . '.' . (
205:                             ($field === '--primaryKey--') ? $Model->$modelName->primaryKey : $field
206:                         );
207:                     } else {
208:                         $field = null;
209:                     }
210:                 }
211:                 if ($field !== null) {
212:                     $query['fields'][] = $field;
213:                 }
214:             }
215:         }
216:         $query['fields'] = array_unique($query['fields']);
217:         return $query;
218:     }
219: 
220: /**
221:  * Unbinds all relations from a model except the specified ones. Calling this function without
222:  * parameters unbinds all related models.
223:  *
224:  * @param Model $Model Model on which binding restriction is being applied
225:  * @return void
226:  * @link http://book.cakephp.org/2.0/en/core-libraries/behaviors/containable.html#using-containable
227:  */
228:     public function contain(Model $Model) {
229:         $args = func_get_args();
230:         $contain = call_user_func_array('am', array_slice($args, 1));
231:         $this->runtime[$Model->alias]['contain'] = $contain;
232:     }
233: 
234: /**
235:  * Permanently restore the original binding settings of given model, useful
236:  * for restoring the bindings after using 'reset' => false as part of the
237:  * contain call.
238:  *
239:  * @param Model $Model Model on which to reset bindings
240:  * @return void
241:  */
242:     public function resetBindings(Model $Model) {
243:         if (!empty($Model->__backOriginalAssociation)) {
244:             $Model->__backAssociation = $Model->__backOriginalAssociation;
245:             unset($Model->__backOriginalAssociation);
246:         }
247:         $Model->resetAssociations();
248:         if (!empty($Model->__backInnerAssociation)) {
249:             $assocs = $Model->__backInnerAssociation;
250:             $Model->__backInnerAssociation = array();
251:             foreach ($assocs as $currentModel) {
252:                 $this->resetBindings($Model->$currentModel);
253:             }
254:         }
255:     }
256: 
257: /**
258:  * Process containments for model.
259:  *
260:  * @param Model $Model Model on which binding restriction is being applied
261:  * @param array $contain Parameters to use for restricting this model
262:  * @param array $containments Current set of containments
263:  * @param boolean $throwErrors Whether non-existent bindings show throw errors
264:  * @return array Containments
265:  */
266:     public function containments(Model $Model, $contain, $containments = array(), $throwErrors = null) {
267:         $options = array('className', 'joinTable', 'with', 'foreignKey', 'associationForeignKey', 'conditions', 'fields', 'order', 'limit', 'offset', 'unique', 'finderQuery', 'deleteQuery', 'insertQuery');
268:         $keep = array();
269:         if ($throwErrors === null) {
270:             $throwErrors = (empty($this->settings[$Model->alias]) ? true : $this->settings[$Model->alias]['notices']);
271:         }
272:         foreach ((array)$contain as $name => $children) {
273:             if (is_numeric($name)) {
274:                 $name = $children;
275:                 $children = array();
276:             }
277:             if (preg_match('/(?<!\.)\(/', $name)) {
278:                 $name = str_replace('(', '.(', $name);
279:             }
280:             if (strpos($name, '.') !== false) {
281:                 $chain = explode('.', $name);
282:                 $name = array_shift($chain);
283:                 $children = array(implode('.', $chain) => $children);
284:             }
285: 
286:             $children = (array)$children;
287:             foreach ($children as $key => $val) {
288:                 if (is_string($key) && is_string($val) && !in_array($key, $options, true)) {
289:                     $children[$key] = (array)$val;
290:                 }
291:             }
292: 
293:             $keys = array_keys($children);
294:             if ($keys && isset($children[0])) {
295:                 $keys = array_merge(array_values($children), $keys);
296:             }
297: 
298:             foreach ($keys as $i => $key) {
299:                 if (is_array($key)) {
300:                     continue;
301:                 }
302:                 $optionKey = in_array($key, $options, true);
303:                 if (!$optionKey && is_string($key) && preg_match('/^[a-z(]/', $key) && (!isset($Model->{$key}) || !is_object($Model->{$key}))) {
304:                     $option = 'fields';
305:                     $val = array($key);
306:                     if ($key{0} == '(') {
307:                         $val = preg_split('/\s*,\s*/', substr($key, 1, -1));
308:                     } elseif (preg_match('/ASC|DESC$/', $key)) {
309:                         $option = 'order';
310:                         $val = $Model->{$name}->alias . '.' . $key;
311:                     } elseif (preg_match('/[ =!]/', $key)) {
312:                         $option = 'conditions';
313:                         $val = $Model->{$name}->alias . '.' . $key;
314:                     }
315:                     $children[$option] = is_array($val) ? $val : array($val);
316:                     $newChildren = null;
317:                     if (!empty($name) && !empty($children[$key])) {
318:                         $newChildren = $children[$key];
319:                     }
320:                     unset($children[$key], $children[$i]);
321:                     $key = $option;
322:                     $optionKey = true;
323:                     if (!empty($newChildren)) {
324:                         $children = Set::merge($children, $newChildren);
325:                     }
326:                 }
327:                 if ($optionKey && isset($children[$key])) {
328:                     if (!empty($keep[$name][$key]) && is_array($keep[$name][$key])) {
329:                         $keep[$name][$key] = array_merge((isset($keep[$name][$key]) ? $keep[$name][$key] : array()), (array)$children[$key]);
330:                     } else {
331:                         $keep[$name][$key] = $children[$key];
332:                     }
333:                     unset($children[$key]);
334:                 }
335:             }
336: 
337:             if (!isset($Model->{$name}) || !is_object($Model->{$name})) {
338:                 if ($throwErrors) {
339:                     trigger_error(__d('cake_dev', 'Model "%s" is not associated with model "%s"', $Model->alias, $name), E_USER_WARNING);
340:                 }
341:                 continue;
342:             }
343: 
344:             $containments = $this->containments($Model->{$name}, $children, $containments);
345:             $depths[] = $containments['depth'] + 1;
346:             if (!isset($keep[$name])) {
347:                 $keep[$name] = array();
348:             }
349:         }
350: 
351:         if (!isset($containments['models'][$Model->alias])) {
352:             $containments['models'][$Model->alias] = array('keep' => array(), 'instance' => &$Model);
353:         }
354: 
355:         $containments['models'][$Model->alias]['keep'] = array_merge($containments['models'][$Model->alias]['keep'], $keep);
356:         $containments['depth'] = empty($depths) ? 0 : max($depths);
357:         return $containments;
358:     }
359: 
360: /**
361:  * Calculate needed fields to fetch the required bindings for the given model.
362:  *
363:  * @param Model $Model Model
364:  * @param array $map Map of relations for given model
365:  * @param mixed $fields If array, fields to initially load, if false use $Model as primary model
366:  * @return array Fields
367:  */
368:     public function fieldDependencies(Model $Model, $map, $fields = array()) {
369:         if ($fields === false) {
370:             foreach ($map as $parent => $children) {
371:                 foreach ($children as $type => $bindings) {
372:                     foreach ($bindings as $dependency) {
373:                         if ($type == 'hasAndBelongsToMany') {
374:                             $fields[$parent][] = '--primaryKey--';
375:                         } elseif ($type == 'belongsTo') {
376:                             $fields[$parent][] = $dependency . '.--primaryKey--';
377:                         }
378:                     }
379:                 }
380:             }
381:             return $fields;
382:         }
383:         if (empty($map[$Model->alias])) {
384:             return $fields;
385:         }
386:         foreach ($map[$Model->alias] as $type => $bindings) {
387:             foreach ($bindings as $dependency) {
388:                 $innerFields = array();
389:                 switch ($type) {
390:                     case 'belongsTo':
391:                         $fields[] = $Model->{$type}[$dependency]['foreignKey'];
392:                         break;
393:                     case 'hasOne':
394:                     case 'hasMany':
395:                         $innerFields[] = $Model->$dependency->primaryKey;
396:                         $fields[] = $Model->primaryKey;
397:                         break;
398:                 }
399:                 if (!empty($innerFields) && !empty($Model->{$type}[$dependency]['fields'])) {
400:                     $Model->{$type}[$dependency]['fields'] = array_unique(array_merge($Model->{$type}[$dependency]['fields'], $innerFields));
401:                 }
402:             }
403:         }
404:         return array_unique($fields);
405:     }
406: 
407: /**
408:  * Build the map of containments
409:  *
410:  * @param array $containments Containments
411:  * @return array Built containments
412:  */
413:     public function containmentsMap($containments) {
414:         $map = array();
415:         foreach ($containments['models'] as $name => $model) {
416:             $instance = $model['instance'];
417:             foreach ($this->types as $type) {
418:                 foreach ($instance->{$type} as $assoc => $options) {
419:                     if (isset($model['keep'][$assoc])) {
420:                         $map[$name][$type] = isset($map[$name][$type]) ? array_merge($map[$name][$type], (array)$assoc) : (array)$assoc;
421:                     }
422:                 }
423:             }
424:         }
425:         return $map;
426:     }
427: 
428: }
429: 
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