containable.php

Go to the documentation of this file.
00001 <?php
00002 /* SVN FILE: $Id: containable.php 8265 2009-07-31 02:08:20Z renan.saddam $ */
00003 /**
00004  * Behavior for binding management.
00005  *
00006  * Behavior to simplify manipulating a model's bindings when doing a find operation
00007  *
00008  * PHP versions 4 and 5
00009  *
00010  * CakePHP(tm) :  Rapid Development Framework (http://www.cakephp.org)
00011  * Copyright 2005-2008, Cake Software Foundation, Inc. (http://www.cakefoundation.org)
00012  *
00013  * Licensed under The MIT License
00014  * Redistributions of files must retain the above copyright notice.
00015  *
00016  * @filesource
00017  * @copyright     Copyright 2005-2008, Cake Software Foundation, Inc. (http://www.cakefoundation.org)
00018  * @link          http://www.cakefoundation.org/projects/info/cakephp CakePHP(tm) Project
00019  * @package       cake
00020  * @subpackage    cake.cake.console.libs
00021  * @since         CakePHP(tm) v 1.2.0.5669
00022  * @version       $Revision: 8265 $
00023  * @modifiedby    $LastChangedBy: renan.saddam $
00024  * @lastmodified  $Date: 2009-07-30 22:08:20 -0400 (Thu, 30 Jul 2009) $
00025  * @license       http://www.opensource.org/licenses/mit-license.php The MIT License
00026  */
00027 /**
00028  * Behavior to allow for dynamic and atomic manipulation of a Model's associations used for a find call. Most useful for limiting
00029  * the amount of associations and data returned.
00030  *
00031  * @package       cake
00032  * @subpackage    cake.cake.console.libs
00033  */
00034 class ContainableBehavior extends ModelBehavior {
00035 /**
00036  * Types of relationships available for models
00037  *
00038  * @var array
00039  * @access private
00040  */
00041     var $types = array('belongsTo', 'hasOne', 'hasMany', 'hasAndBelongsToMany');
00042 /**
00043  * Runtime configuration for this behavior
00044  *
00045  * @var array
00046  * @access private
00047  */
00048     var $runtime = array();
00049 /**
00050  * Initiate behavior for the model using specified settings.
00051  *
00052  * Available settings:
00053  *
00054  * - recursive: (boolean, optional) set to true to allow containable to automatically
00055  *   determine the recursiveness level needed to fetch specified models,
00056  *   and set the model recursiveness to this level. setting it to false
00057  *   disables this feature. DEFAULTS TO: true
00058  * - notices: (boolean, optional) issues E_NOTICES for bindings referenced in a
00059  *   containable call that are not valid. DEFAULTS TO: true
00060  * - autoFields: (boolean, optional) auto-add needed fields to fetch requested
00061  *   bindings. DEFAULTS TO: true
00062  *
00063  * @param object $Model Model using the behavior
00064  * @param array $settings Settings to override for model.
00065  * @access public
00066  */
00067     function setup(&$Model, $settings = array()) {
00068         if (!isset($this->settings[$Model->alias])) {
00069             $this->settings[$Model->alias] = array('recursive' => true, 'notices' => true, 'autoFields' => true);
00070         }
00071         if (!is_array($settings)) {
00072             $settings = array();
00073         }
00074         $this->settings[$Model->alias] = array_merge($this->settings[$Model->alias], $settings);
00075     }
00076 /**
00077  * Runs before a find() operation. Used to allow 'contain' setting
00078  * as part of the find call, like this:
00079  *
00080  * Model->find('all', array('contain' => array('Model1', 'Model2')));
00081  *
00082  * Model->find('all', array('contain' => array(
00083  *  'Model1' => array('Model11', 'Model12'),
00084  *  'Model2',
00085  *  'Model3' => array(
00086  *      'Model31' => 'Model311',
00087  *      'Model32',
00088  *      'Model33' => array('Model331', 'Model332')
00089  * )));
00090  *
00091  * @param object $Model Model using the behavior
00092  * @param array $query Query parameters as set by cake
00093  * @return array
00094  * @access public
00095  */
00096     function beforeFind(&$Model, $query) {
00097         $reset = (isset($query['reset']) ? $query['reset'] : true);
00098         $noContain = ((isset($this->runtime[$Model->alias]['contain']) && empty($this->runtime[$Model->alias]['contain'])) || (isset($query['contain']) && empty($query['contain'])));
00099         $contain = array();
00100         if (isset($this->runtime[$Model->alias]['contain'])) {
00101             $contain = $this->runtime[$Model->alias]['contain'];
00102             unset($this->runtime[$Model->alias]['contain']);
00103         }
00104         if (isset($query['contain'])) {
00105             $contain = array_merge($contain, (array)$query['contain']);
00106         }
00107         if ($noContain || !$contain || in_array($contain, array(null, false), true) || (isset($contain[0]) && $contain[0] === null)) {
00108             if ($noContain) {
00109                 $query['recursive'] = -1;
00110             }
00111             return $query;
00112         }
00113         if ((isset($contain[0]) && is_bool($contain[0])) || is_bool(end($contain))) {
00114             $reset = is_bool(end($contain))
00115                 ? array_pop($contain)
00116                 : array_shift($contain);
00117         }
00118         $containments = $this->containments($Model, $contain);
00119         $map = $this->containmentsMap($containments);
00120 
00121         $mandatory = array();
00122         foreach ($containments['models'] as $name => $model) {
00123             $instance =& $model['instance'];
00124             $needed = $this->fieldDependencies($instance, $map, false);
00125             if (!empty($needed)) {
00126                 $mandatory = array_merge($mandatory, $needed);
00127             }
00128             if ($contain) {
00129                 $backupBindings = array();
00130                 foreach ($this->types as $relation) {
00131                     $backupBindings[$relation] = $instance->{$relation};
00132                 }
00133                 foreach ($this->types as $type) {
00134                     $unbind = array();
00135                     foreach ($instance->{$type} as $assoc => $options) {
00136                         if (!isset($model['keep'][$assoc])) {
00137                             $unbind[] = $assoc;
00138                         }
00139                     }
00140                     if (!empty($unbind)) {
00141                         if (!$reset && empty($instance->__backOriginalAssociation)) {
00142                             $instance->__backOriginalAssociation = $backupBindings;
00143                         } else if ($reset && empty($instance->__backContainableAssociation)) {
00144                             $instance->__backContainableAssociation = $backupBindings;
00145                         }
00146                         $instance->unbindModel(array($type => $unbind), $reset);
00147                     }
00148                     foreach ($instance->{$type} as $assoc => $options) {
00149                         if (isset($model['keep'][$assoc]) && !empty($model['keep'][$assoc])) {
00150                             if (isset($model['keep'][$assoc]['fields'])) {
00151                                 $model['keep'][$assoc]['fields'] = $this->fieldDependencies($containments['models'][$assoc]['instance'], $map, $model['keep'][$assoc]['fields']);
00152                             }
00153                             if (!$reset && empty($instance->__backOriginalAssociation)) {
00154                                 $instance->__backOriginalAssociation = $backupBindings;
00155                             } else if ($reset) {
00156                                 $instance->__backAssociation[$type] = $instance->{$type};
00157                             }
00158                             $instance->{$type}[$assoc] = array_merge($instance->{$type}[$assoc], $model['keep'][$assoc]);
00159                         }
00160                         if (!$reset) {
00161                             $instance->__backInnerAssociation[] = $assoc;
00162                         }
00163                     }
00164                 }
00165             }
00166         }
00167 
00168         if ($this->settings[$Model->alias]['recursive']) {
00169             $query['recursive'] = (isset($query['recursive'])) ? $query['recursive'] : $containments['depth'];
00170         }
00171 
00172         $autoFields = ($this->settings[$Model->alias]['autoFields']
00173                     && !in_array($Model->findQueryType, array('list', 'count'))
00174                     && !empty($query['fields']));
00175         if (!$autoFields) {
00176             return $query;
00177         }
00178 
00179         $query['fields'] = (array)$query['fields'];
00180         if (!empty($Model->belongsTo)) {
00181             foreach ($Model->belongsTo as $assoc => $data) {
00182                 if (!empty($data['fields'])) {
00183                     foreach ((array) $data['fields'] as $field) {
00184                         $query['fields'][] = (strpos($field, '.') === false ? $assoc . '.' : '') . $field;
00185                     }
00186                 }
00187             }
00188         }
00189         if (!empty($mandatory[$Model->alias])) {
00190             foreach ($mandatory[$Model->alias] as $field) {
00191                 if ($field == '--primaryKey--') {
00192                     $field = $Model->primaryKey;
00193                 } else if (preg_match('/^.+\.\-\-[^-]+\-\-$/', $field)) {
00194                     list($modelName, $field) = explode('.', $field);
00195                     $field = $modelName . '.' . (($field === '--primaryKey--') ? $Model->$modelName->primaryKey : $field);
00196                 }
00197                 $query['fields'][] = $field;
00198             }
00199         }
00200         $query['fields'] = array_unique($query['fields']);
00201         return $query;
00202     }
00203 /**
00204  * Resets original associations on models that may have receive multiple,
00205  * subsequent unbindings.
00206  *
00207  * @param object $Model Model on which we are resetting
00208  * @param array $results Results of the find operation
00209  * @param bool $primary true if this is the primary model that issued the find operation, false otherwise
00210  * @access public
00211  */
00212     function afterFind(&$Model, $results, $primary) {
00213         if (!empty($Model->__backContainableAssociation)) {
00214             foreach ($Model->__backContainableAssociation as $relation => $bindings) {
00215                 $Model->{$relation} = $bindings;
00216                 unset($Model->__backContainableAssociation);
00217             }
00218         }
00219     }
00220 /**
00221  * Unbinds all relations from a model except the specified ones. Calling this function without
00222  * parameters unbinds all related models.
00223  *
00224  * @param object $Model Model on which binding restriction is being applied
00225  * @return void
00226  * @access public
00227  */
00228     function contain(&$Model) {
00229         $args = func_get_args();
00230         $contain = call_user_func_array('am', array_slice($args, 1));
00231         $this->runtime[$Model->alias]['contain'] = $contain;
00232     }
00233 /**
00234  * Permanently restore the original binding settings of given model, useful
00235  * for restoring the bindings after using 'reset' => false as part of the
00236  * contain call.
00237  *
00238  * @param object $Model Model on which to reset bindings
00239  * @return void
00240  * @access public
00241  */
00242     function resetBindings(&$Model) {
00243         if (!empty($Model->__backOriginalAssociation)) {
00244             $Model->__backAssociation = $Model->__backOriginalAssociation;
00245             unset($Model->__backOriginalAssociation);
00246         }
00247         $Model->resetAssociations();
00248         if (!empty($Model->__backInnerAssociation)) {
00249             $assocs = $Model->__backInnerAssociation;
00250             unset($Model->__backInnerAssociation);
00251             foreach ($assocs as $currentModel) {
00252                 $this->resetBindings($Model->$currentModel);
00253             }
00254         }
00255     }
00256 /**
00257  * Process containments for model.
00258  *
00259  * @param object $Model Model on which binding restriction is being applied
00260  * @param array $contain Parameters to use for restricting this model
00261  * @param array $containments Current set of containments
00262  * @param bool $throwErrors Wether unexisting bindings show throw errors
00263  * @return array Containments
00264  * @access public
00265  */
00266     function containments(&$Model, $contain, $containments = array(), $throwErrors = null) {
00267         $options = array('className', 'joinTable', 'with', 'foreignKey', 'associationForeignKey', 'conditions', 'fields', 'order', 'limit', 'offset', 'unique', 'finderQuery', 'deleteQuery', 'insertQuery');
00268         $keep = array();
00269         $depth = array();
00270         if ($throwErrors === null) {
00271             $throwErrors = (empty($this->settings[$Model->alias]) ? true : $this->settings[$Model->alias]['notices']);
00272         }
00273         foreach ((array)$contain as $name => $children) {
00274             if (is_numeric($name)) {
00275                 $name = $children;
00276                 $children = array();
00277             }
00278             if (preg_match('/(?<!\.)\(/', $name)) {
00279                 $name = str_replace('(', '.(', $name);
00280             }
00281             if (strpos($name, '.') !== false) {
00282                 $chain = explode('.', $name);
00283                 $name = array_shift($chain);
00284                 $children = array(join('.', $chain) => $children);
00285             }
00286 
00287             $children = (array)$children;
00288             foreach ($children as $key => $val) {
00289                 if (is_string($key) && is_string($val) && !in_array($key, $options, true)) {
00290                     $children[$key] = (array) $val;
00291                 }
00292             }
00293 
00294             $keys = array_keys($children);
00295             if ($keys && isset($children[0])) {
00296                 $keys = array_merge(array_values($children), $keys);
00297             }
00298 
00299             foreach ($keys as $i => $key) {
00300                 if (is_array($key)) {
00301                     continue;
00302                 }
00303                 $optionKey = in_array($key, $options, true);
00304                 if (!$optionKey && is_string($key) && preg_match('/^[a-z(]/', $key) && (!isset($Model->{$key}) || !is_object($Model->{$key}))) {
00305                     $option = 'fields';
00306                     $val = array($key);
00307                     if ($key{0} == '(') {
00308                         $val = preg_split('/\s*,\s*/', substr(substr($key, 1), 0, -1));
00309                     } elseif (preg_match('/ASC|DESC$/', $key)) {
00310                         $option = 'order';
00311                         $val = $Model->{$name}->alias.'.'.$key;
00312                     } elseif (preg_match('/[ =!]/', $key)) {
00313                         $option = 'conditions';
00314                         $val = $Model->{$name}->alias.'.'.$key;
00315                     }
00316                     $children[$option] = is_array($val) ? $val : array($val);
00317                     $newChildren = null;
00318                     if (!empty($name) && !empty($children[$key])) {
00319                         $newChildren = $children[$key];
00320                     }
00321                     unset($children[$key], $children[$i]);
00322                     $key = $option;
00323                     $optionKey = true;
00324                     if (!empty($newChildren)) {
00325                         $children = Set::merge($children, $newChildren);
00326                     }
00327                 }
00328                 if ($optionKey && isset($children[$key])) {
00329                     if (!empty($keep[$name][$key]) && is_array($keep[$name][$key])) {
00330                         $keep[$name][$key] = array_merge((isset($keep[$name][$key]) ? $keep[$name][$key] : array()), (array) $children[$key]);
00331                     } else {
00332                         $keep[$name][$key] = $children[$key];
00333                     }
00334                     unset($children[$key]);
00335                 }
00336             }
00337 
00338             if (!isset($Model->{$name}) || !is_object($Model->{$name})) {
00339                 if ($throwErrors) {
00340                     trigger_error(sprintf(__('Model "%s" is not associated with model "%s"', true), $Model->alias, $name), E_USER_WARNING);
00341                 }
00342                 continue;
00343             }
00344 
00345             $containments = $this->containments($Model->{$name}, $children, $containments);
00346             $depths[] = $containments['depth'] + 1;
00347             if (!isset($keep[$name])) {
00348                 $keep[$name] = array();
00349             }
00350         }
00351 
00352         if (!isset($containments['models'][$Model->alias])) {
00353             $containments['models'][$Model->alias] = array('keep' => array(),'instance' => &$Model);
00354         }
00355 
00356         $containments['models'][$Model->alias]['keep'] = array_merge($containments['models'][$Model->alias]['keep'], $keep);
00357         $containments['depth'] = empty($depths) ? 0 : max($depths);
00358         return $containments;
00359     }
00360 /**
00361  * Calculate needed fields to fetch the required bindings for the given model.
00362  *
00363  * @param object $Model Model
00364  * @param array $map Map of relations for given model
00365  * @param mixed $fields If array, fields to initially load, if false use $Model as primary model
00366  * @return array Fields
00367  * @access public
00368  */
00369     function fieldDependencies(&$Model, $map, $fields = array()) {
00370         if ($fields === false) {
00371             foreach ($map as $parent => $children) {
00372                 foreach ($children as $type => $bindings) {
00373                     foreach ($bindings as $dependency) {
00374                         if ($type == 'hasAndBelongsToMany') {
00375                             $fields[$parent][] = '--primaryKey--';
00376                         } else if ($type == 'belongsTo') {
00377                             $fields[$parent][] = $dependency . '.--primaryKey--';
00378                         }
00379                     }
00380                 }
00381             }
00382             return $fields;
00383         }
00384         if (empty($map[$Model->alias])) {
00385             return $fields;
00386         }
00387         foreach ($map[$Model->alias] as $type => $bindings) {
00388             foreach ($bindings as $dependency) {
00389                 $innerFields = array();
00390                 switch ($type) {
00391                     case 'belongsTo':
00392                         $fields[] = $Model->{$type}[$dependency]['foreignKey'];
00393                         break;
00394                     case 'hasOne':
00395                     case 'hasMany':
00396                         $innerFields[] = $Model->$dependency->primaryKey;
00397                         $fields[] = $Model->primaryKey;
00398                         break;
00399                 }
00400                 if (!empty($innerFields) && !empty($Model->{$type}[$dependency]['fields'])) {
00401                     $Model->{$type}[$dependency]['fields'] = array_unique(array_merge($Model->{$type}[$dependency]['fields'], $innerFields));
00402                 }
00403             }
00404         }
00405         return array_unique($fields);
00406     }
00407 /**
00408  * Build the map of containments
00409  *
00410  * @param array $containments Containments
00411  * @return array Built containments
00412  * @access public
00413  */
00414     function containmentsMap($containments) {
00415         $map = array();
00416         foreach ($containments['models'] as $name => $model) {
00417             $instance =& $model['instance'];
00418             foreach ($this->types as $type) {
00419                 foreach ($instance->{$type} as $assoc => $options) {
00420                     if (isset($model['keep'][$assoc])) {
00421                         $map[$name][$type] = isset($map[$name][$type]) ? array_merge($map[$name][$type], (array)$assoc) : (array)$assoc;
00422                     }
00423                 }
00424             }
00425         }
00426         return $map;
00427     }
00428 }
00429 ?>

Generated on Sun Nov 22 00:30:53 2009 for CakePHP 1.2.x.x (v1.2.4.8284) by doxygen 1.4.7