PageRenderTime 53ms CodeModel.GetById 24ms RepoModel.GetById 0ms app.codeStats 0ms

/cake/libs/model/behaviors/containable.php

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