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

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

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