cake/libs/model/behaviors/containable.php

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