PageRenderTime 48ms CodeModel.GetById 16ms RepoModel.GetById 0ms app.codeStats 1ms

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

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