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

  • Overview
  • Tree
  • Deprecated
  • Version:
    • 2.2
      • 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

  • 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 = false;
 95:         $contain = array();
 96: 
 97:         if (isset($this->runtime[$Model->alias]['contain'])) {
 98:             $noContain = empty($this->runtime[$Model->alias]['contain']);
 99:             $contain = $this->runtime[$Model->alias]['contain'];
100:             unset($this->runtime[$Model->alias]['contain']);
101:         }
102: 
103:         if (isset($query['contain'])) {
104:             $noContain = $noContain || empty($query['contain']);
105:             if ($query['contain'] !== false) {
106:                 $contain = array_merge($contain, (array)$query['contain']);
107:             }
108:         }
109:         $noContain = $noContain && empty($contain);
110: 
111:         if (
112:             $noContain || empty($contain) || (isset($contain[0]) && $contain[0] === null)
113:         ) {
114:             if ($noContain) {
115:                 $query['recursive'] = -1;
116:             }
117:             return $query;
118:         }
119:         if ((isset($contain[0]) && is_bool($contain[0])) || is_bool(end($contain))) {
120:             $reset = is_bool(end($contain))
121:                 ? array_pop($contain)
122:                 : array_shift($contain);
123:         }
124:         $containments = $this->containments($Model, $contain);
125:         $map = $this->containmentsMap($containments);
126: 
127:         $mandatory = array();
128:         foreach ($containments['models'] as $name => $model) {
129:             $instance = $model['instance'];
130:             $needed = $this->fieldDependencies($instance, $map, false);
131:             if (!empty($needed)) {
132:                 $mandatory = array_merge($mandatory, $needed);
133:             }
134:             if ($contain) {
135:                 $backupBindings = array();
136:                 foreach ($this->types as $relation) {
137:                     if (!empty($instance->__backAssociation[$relation])) {
138:                         $backupBindings[$relation] = $instance->__backAssociation[$relation];
139:                     } else {
140:                         $backupBindings[$relation] = $instance->{$relation};
141:                     }
142:                 }
143:                 foreach ($this->types as $type) {
144:                     $unbind = array();
145:                     foreach ($instance->{$type} as $assoc => $options) {
146:                         if (!isset($model['keep'][$assoc])) {
147:                             $unbind[] = $assoc;
148:                         }
149:                     }
150:                     if (!empty($unbind)) {
151:                         if (!$reset && empty($instance->__backOriginalAssociation)) {
152:                             $instance->__backOriginalAssociation = $backupBindings;
153:                         }
154:                         $instance->unbindModel(array($type => $unbind), $reset);
155:                     }
156:                     foreach ($instance->{$type} as $assoc => $options) {
157:                         if (isset($model['keep'][$assoc]) && !empty($model['keep'][$assoc])) {
158:                             if (isset($model['keep'][$assoc]['fields'])) {
159:                                 $model['keep'][$assoc]['fields'] = $this->fieldDependencies($containments['models'][$assoc]['instance'], $map, $model['keep'][$assoc]['fields']);
160:                             }
161:                             if (!$reset && empty($instance->__backOriginalAssociation)) {
162:                                 $instance->__backOriginalAssociation = $backupBindings;
163:                             } elseif ($reset) {
164:                                 $instance->__backAssociation[$type] = $backupBindings[$type];
165:                             }
166:                             $instance->{$type}[$assoc] = array_merge($instance->{$type}[$assoc], $model['keep'][$assoc]);
167:                         }
168:                         if (!$reset) {
169:                             $instance->__backInnerAssociation[] = $assoc;
170:                         }
171:                     }
172:                 }
173:             }
174:         }
175: 
176:         if ($this->settings[$Model->alias]['recursive']) {
177:             $query['recursive'] = (isset($query['recursive'])) ? $query['recursive'] : $containments['depth'];
178:         }
179: 
180:         $autoFields = ($this->settings[$Model->alias]['autoFields']
181:                     && !in_array($Model->findQueryType, array('list', 'count'))
182:                     && !empty($query['fields']));
183: 
184:         if (!$autoFields) {
185:             return $query;
186:         }
187: 
188:         $query['fields'] = (array)$query['fields'];
189:         foreach (array('hasOne', 'belongsTo') as $type) {
190:             if (!empty($Model->{$type})) {
191:                 foreach ($Model->{$type} as $assoc => $data) {
192:                     if ($Model->useDbConfig == $Model->{$assoc}->useDbConfig && !empty($data['fields'])) {
193:                         foreach ((array)$data['fields'] as $field) {
194:                             $query['fields'][] = (strpos($field, '.') === false ? $assoc . '.' : '') . $field;
195:                         }
196:                     }
197:                 }
198:             }
199:         }
200: 
201:         if (!empty($mandatory[$Model->alias])) {
202:             foreach ($mandatory[$Model->alias] as $field) {
203:                 if ($field == '--primaryKey--') {
204:                     $field = $Model->primaryKey;
205:                 } elseif (preg_match('/^.+\.\-\-[^-]+\-\-$/', $field)) {
206:                     list($modelName, $field) = explode('.', $field);
207:                     if ($Model->useDbConfig == $Model->{$modelName}->useDbConfig) {
208:                         $field = $modelName . '.' . (
209:                             ($field === '--primaryKey--') ? $Model->$modelName->primaryKey : $field
210:                         );
211:                     } else {
212:                         $field = null;
213:                     }
214:                 }
215:                 if ($field !== null) {
216:                     $query['fields'][] = $field;
217:                 }
218:             }
219:         }
220:         $query['fields'] = array_unique($query['fields']);
221:         return $query;
222:     }
223: 
224: /**
225:  * Unbinds all relations from a model except the specified ones. Calling this function without
226:  * parameters unbinds all related models.
227:  *
228:  * @param Model $Model Model on which binding restriction is being applied
229:  * @return void
230:  * @link http://book.cakephp.org/2.0/en/core-libraries/behaviors/containable.html#using-containable
231:  */
232:     public function contain(Model $Model) {
233:         $args = func_get_args();
234:         $contain = call_user_func_array('am', array_slice($args, 1));
235:         $this->runtime[$Model->alias]['contain'] = $contain;
236:     }
237: 
238: /**
239:  * Permanently restore the original binding settings of given model, useful
240:  * for restoring the bindings after using 'reset' => false as part of the
241:  * contain call.
242:  *
243:  * @param Model $Model Model on which to reset bindings
244:  * @return void
245:  */
246:     public function resetBindings(Model $Model) {
247:         if (!empty($Model->__backOriginalAssociation)) {
248:             $Model->__backAssociation = $Model->__backOriginalAssociation;
249:             unset($Model->__backOriginalAssociation);
250:         }
251:         $Model->resetAssociations();
252:         if (!empty($Model->__backInnerAssociation)) {
253:             $assocs = $Model->__backInnerAssociation;
254:             $Model->__backInnerAssociation = array();
255:             foreach ($assocs as $currentModel) {
256:                 $this->resetBindings($Model->$currentModel);
257:             }
258:         }
259:     }
260: 
261: /**
262:  * Process containments for model.
263:  *
264:  * @param Model $Model Model on which binding restriction is being applied
265:  * @param array $contain Parameters to use for restricting this model
266:  * @param array $containments Current set of containments
267:  * @param boolean $throwErrors Whether non-existent bindings show throw errors
268:  * @return array Containments
269:  */
270:     public function containments(Model $Model, $contain, $containments = array(), $throwErrors = null) {
271:         $options = array('className', 'joinTable', 'with', 'foreignKey', 'associationForeignKey', 'conditions', 'fields', 'order', 'limit', 'offset', 'unique', 'finderQuery', 'deleteQuery', 'insertQuery');
272:         $keep = array();
273:         if ($throwErrors === null) {
274:             $throwErrors = (empty($this->settings[$Model->alias]) ? true : $this->settings[$Model->alias]['notices']);
275:         }
276:         foreach ((array)$contain as $name => $children) {
277:             if (is_numeric($name)) {
278:                 $name = $children;
279:                 $children = array();
280:             }
281:             if (preg_match('/(?<!\.)\(/', $name)) {
282:                 $name = str_replace('(', '.(', $name);
283:             }
284:             if (strpos($name, '.') !== false) {
285:                 $chain = explode('.', $name);
286:                 $name = array_shift($chain);
287:                 $children = array(implode('.', $chain) => $children);
288:             }
289: 
290:             $children = (array)$children;
291:             foreach ($children as $key => $val) {
292:                 if (is_string($key) && is_string($val) && !in_array($key, $options, true)) {
293:                     $children[$key] = (array)$val;
294:                 }
295:             }
296: 
297:             $keys = array_keys($children);
298:             if ($keys && isset($children[0])) {
299:                 $keys = array_merge(array_values($children), $keys);
300:             }
301: 
302:             foreach ($keys as $i => $key) {
303:                 if (is_array($key)) {
304:                     continue;
305:                 }
306:                 $optionKey = in_array($key, $options, true);
307:                 if (!$optionKey && is_string($key) && preg_match('/^[a-z(]/', $key) && (!isset($Model->{$key}) || !is_object($Model->{$key}))) {
308:                     $option = 'fields';
309:                     $val = array($key);
310:                     if ($key{0} == '(') {
311:                         $val = preg_split('/\s*,\s*/', substr($key, 1, -1));
312:                     } elseif (preg_match('/ASC|DESC$/', $key)) {
313:                         $option = 'order';
314:                         $val = $Model->{$name}->alias . '.' . $key;
315:                     } elseif (preg_match('/[ =!]/', $key)) {
316:                         $option = 'conditions';
317:                         $val = $Model->{$name}->alias . '.' . $key;
318:                     }
319:                     $children[$option] = is_array($val) ? $val : array($val);
320:                     $newChildren = null;
321:                     if (!empty($name) && !empty($children[$key])) {
322:                         $newChildren = $children[$key];
323:                     }
324:                     unset($children[$key], $children[$i]);
325:                     $key = $option;
326:                     $optionKey = true;
327:                     if (!empty($newChildren)) {
328:                         $children = Hash::merge($children, $newChildren);
329:                     }
330:                 }
331:                 if ($optionKey && isset($children[$key])) {
332:                     if (!empty($keep[$name][$key]) && is_array($keep[$name][$key])) {
333:                         $keep[$name][$key] = array_merge((isset($keep[$name][$key]) ? $keep[$name][$key] : array()), (array)$children[$key]);
334:                     } else {
335:                         $keep[$name][$key] = $children[$key];
336:                     }
337:                     unset($children[$key]);
338:                 }
339:             }
340: 
341:             if (!isset($Model->{$name}) || !is_object($Model->{$name})) {
342:                 if ($throwErrors) {
343:                     trigger_error(__d('cake_dev', 'Model "%s" is not associated with model "%s"', $Model->alias, $name), E_USER_WARNING);
344:                 }
345:                 continue;
346:             }
347: 
348:             $containments = $this->containments($Model->{$name}, $children, $containments);
349:             $depths[] = $containments['depth'] + 1;
350:             if (!isset($keep[$name])) {
351:                 $keep[$name] = array();
352:             }
353:         }
354: 
355:         if (!isset($containments['models'][$Model->alias])) {
356:             $containments['models'][$Model->alias] = array('keep' => array(), 'instance' => &$Model);
357:         }
358: 
359:         $containments['models'][$Model->alias]['keep'] = array_merge($containments['models'][$Model->alias]['keep'], $keep);
360:         $containments['depth'] = empty($depths) ? 0 : max($depths);
361:         return $containments;
362:     }
363: 
364: /**
365:  * Calculate needed fields to fetch the required bindings for the given model.
366:  *
367:  * @param Model $Model Model
368:  * @param array $map Map of relations for given model
369:  * @param array|boolean $fields If array, fields to initially load, if false use $Model as primary model
370:  * @return array Fields
371:  */
372:     public function fieldDependencies(Model $Model, $map, $fields = array()) {
373:         if ($fields === false) {
374:             foreach ($map as $parent => $children) {
375:                 foreach ($children as $type => $bindings) {
376:                     foreach ($bindings as $dependency) {
377:                         if ($type == 'hasAndBelongsToMany') {
378:                             $fields[$parent][] = '--primaryKey--';
379:                         } elseif ($type == 'belongsTo') {
380:                             $fields[$parent][] = $dependency . '.--primaryKey--';
381:                         }
382:                     }
383:                 }
384:             }
385:             return $fields;
386:         }
387:         if (empty($map[$Model->alias])) {
388:             return $fields;
389:         }
390:         foreach ($map[$Model->alias] as $type => $bindings) {
391:             foreach ($bindings as $dependency) {
392:                 $innerFields = array();
393:                 switch ($type) {
394:                     case 'belongsTo':
395:                         $fields[] = $Model->{$type}[$dependency]['foreignKey'];
396:                         break;
397:                     case 'hasOne':
398:                     case 'hasMany':
399:                         $innerFields[] = $Model->$dependency->primaryKey;
400:                         $fields[] = $Model->primaryKey;
401:                         break;
402:                 }
403:                 if (!empty($innerFields) && !empty($Model->{$type}[$dependency]['fields'])) {
404:                     $Model->{$type}[$dependency]['fields'] = array_unique(array_merge($Model->{$type}[$dependency]['fields'], $innerFields));
405:                 }
406:             }
407:         }
408:         return array_unique($fields);
409:     }
410: 
411: /**
412:  * Build the map of containments
413:  *
414:  * @param array $containments Containments
415:  * @return array Built containments
416:  */
417:     public function containmentsMap($containments) {
418:         $map = array();
419:         foreach ($containments['models'] as $name => $model) {
420:             $instance = $model['instance'];
421:             foreach ($this->types as $type) {
422:                 foreach ($instance->{$type} as $assoc => $options) {
423:                     if (isset($model['keep'][$assoc])) {
424:                         $map[$name][$type] = isset($map[$name][$type]) ? array_merge($map[$name][$type], (array)$assoc) : (array)$assoc;
425:                     }
426:                 }
427:             }
428:         }
429:         return $map;
430:     }
431: 
432: }
433: 
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