ContainableBehavior.php 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445
  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 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. * 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. public $types = array('belongsTo', 'hasOne', 'hasMany', 'hasAndBelongsToMany');
  38. /**
  39. * Runtime configuration for this behavior
  40. *
  41. * @var array
  42. * @access private
  43. */
  44. public $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. */
  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. */
  92. public function beforeFind(&$Model, $query) {
  93. $reset = (isset($query['reset']) ? $query['reset'] : true);
  94. $noContain = ((isset($this->runtime[$Model->alias]['contain']) && empty($this->runtime[$Model->alias]['contain'])) || (isset($query['contain']) && empty($query['contain'])));
  95. $contain = array();
  96. if (isset($this->runtime[$Model->alias]['contain'])) {
  97. $contain = $this->runtime[$Model->alias]['contain'];
  98. unset($this->runtime[$Model->alias]['contain']);
  99. }
  100. if (isset($query['contain'])) {
  101. $contain = array_merge($contain, (array)$query['contain']);
  102. }
  103. if ($noContain || !$contain || in_array($contain, array(null, false), true) || (isset($contain[0]) && $contain[0] === null)) {
  104. if ($noContain) {
  105. $query['recursive'] = -1;
  106. }
  107. return $query;
  108. }
  109. if ((isset($contain[0]) && is_bool($contain[0])) || is_bool(end($contain))) {
  110. $reset = is_bool(end($contain))
  111. ? array_pop($contain)
  112. : array_shift($contain);
  113. }
  114. $containments = $this->containments($Model, $contain);
  115. $map = $this->containmentsMap($containments);
  116. $mandatory = array();
  117. foreach ($containments['models'] as $name => $model) {
  118. $instance = $model['instance'];
  119. $needed = $this->fieldDependencies($instance, $map, false);
  120. if (!empty($needed)) {
  121. $mandatory = array_merge($mandatory, $needed);
  122. }
  123. if ($contain) {
  124. $backupBindings = array();
  125. foreach ($this->types as $relation) {
  126. if (!empty($instance->__backAssociation[$relation])) {
  127. $backupBindings[$relation] = $instance->__backAssociation[$relation];
  128. } else {
  129. $backupBindings[$relation] = $instance->{$relation};
  130. }
  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] = $backupBindings[$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. foreach (array('hasOne', 'belongsTo') as $type) {
  177. if (!empty($Model->{$type})) {
  178. foreach ($Model->{$type} as $assoc => $data) {
  179. if ($Model->useDbConfig == $Model->{$assoc}->useDbConfig && !empty($data['fields'])) {
  180. foreach ((array) $data['fields'] as $field) {
  181. $query['fields'][] = (strpos($field, '.') === false ? $assoc . '.' : '') . $field;
  182. }
  183. }
  184. }
  185. }
  186. }
  187. if (!empty($mandatory[$Model->alias])) {
  188. foreach ($mandatory[$Model->alias] as $field) {
  189. if ($field == '--primaryKey--') {
  190. $field = $Model->primaryKey;
  191. } else if (preg_match('/^.+\.\-\-[^-]+\-\-$/', $field)) {
  192. list($modelName, $field) = explode('.', $field);
  193. if ($Model->useDbConfig == $Model->{$modelName}->useDbConfig) {
  194. $field = $modelName . '.' . (
  195. ($field === '--primaryKey--') ? $Model->$modelName->primaryKey : $field
  196. );
  197. } else {
  198. $field = null;
  199. }
  200. }
  201. if ($field !== null) {
  202. $query['fields'][] = $field;
  203. }
  204. }
  205. }
  206. $query['fields'] = array_unique($query['fields']);
  207. return $query;
  208. }
  209. /**
  210. * Resets original associations on models that may have receive multiple,
  211. * subsequent unbindings.
  212. *
  213. * @param object $Model Model on which we are resetting
  214. * @param array $results Results of the find operation
  215. * @param bool $primary true if this is the primary model that issued the find operation, false otherwise
  216. */
  217. public function afterFind(&$Model, $results, $primary) {
  218. if (!empty($Model->__backContainableAssociation)) {
  219. foreach ($Model->__backContainableAssociation as $relation => $bindings) {
  220. $Model->{$relation} = $bindings;
  221. unset($Model->__backContainableAssociation);
  222. }
  223. }
  224. }
  225. /**
  226. * Unbinds all relations from a model except the specified ones. Calling this function without
  227. * parameters unbinds all related models.
  228. *
  229. * @param object $Model Model on which binding restriction is being applied
  230. * @return void
  231. * @link http://book.cakephp.org/view/1323/Containable#Using-Containable-1324
  232. */
  233. public function contain(&$Model) {
  234. $args = func_get_args();
  235. $contain = call_user_func_array('am', array_slice($args, 1));
  236. $this->runtime[$Model->alias]['contain'] = $contain;
  237. }
  238. /**
  239. * Permanently restore the original binding settings of given model, useful
  240. * for restoring the bindings after using 'reset' => false as part of the
  241. * contain call.
  242. *
  243. * @param object $Model Model on which to reset bindings
  244. * @return void
  245. */
  246. public function resetBindings(&$Model) {
  247. if (!empty($Model->__backOriginalAssociation)) {
  248. $Model->__backAssociation = $Model->__backOriginalAssociation;
  249. unset($Model->__backOriginalAssociation);
  250. }
  251. $Model->resetAssociations();
  252. if (!empty($Model->__backInnerAssociation)) {
  253. $assocs = $Model->__backInnerAssociation;
  254. unset($Model->__backInnerAssociation);
  255. foreach ($assocs as $currentModel) {
  256. $this->resetBindings($Model->$currentModel);
  257. }
  258. }
  259. }
  260. /**
  261. * Process containments for model.
  262. *
  263. * @param object $Model Model on which binding restriction is being applied
  264. * @param array $contain Parameters to use for restricting this model
  265. * @param array $containments Current set of containments
  266. * @param bool $throwErrors Wether unexisting bindings show throw errors
  267. * @return array Containments
  268. */
  269. public function containments(&$Model, $contain, $containments = array(), $throwErrors = null) {
  270. $options = array('className', 'joinTable', 'with', 'foreignKey', 'associationForeignKey', 'conditions', 'fields', 'order', 'limit', 'offset', 'unique', 'finderQuery', 'deleteQuery', 'insertQuery');
  271. $keep = array();
  272. $depth = array();
  273. if ($throwErrors === null) {
  274. $throwErrors = (empty($this->settings[$Model->alias]) ? true : $this->settings[$Model->alias]['notices']);
  275. }
  276. foreach ((array)$contain as $name => $children) {
  277. if (is_numeric($name)) {
  278. $name = $children;
  279. $children = array();
  280. }
  281. if (preg_match('/(?<!\.)\(/', $name)) {
  282. $name = str_replace('(', '.(', $name);
  283. }
  284. if (strpos($name, '.') !== false) {
  285. $chain = explode('.', $name);
  286. $name = array_shift($chain);
  287. $children = array(implode('.', $chain) => $children);
  288. }
  289. $children = (array)$children;
  290. foreach ($children as $key => $val) {
  291. if (is_string($key) && is_string($val) && !in_array($key, $options, true)) {
  292. $children[$key] = (array) $val;
  293. }
  294. }
  295. $keys = array_keys($children);
  296. if ($keys && isset($children[0])) {
  297. $keys = array_merge(array_values($children), $keys);
  298. }
  299. foreach ($keys as $i => $key) {
  300. if (is_array($key)) {
  301. continue;
  302. }
  303. $optionKey = in_array($key, $options, true);
  304. if (!$optionKey && is_string($key) && preg_match('/^[a-z(]/', $key) && (!isset($Model->{$key}) || !is_object($Model->{$key}))) {
  305. $option = 'fields';
  306. $val = array($key);
  307. if ($key{0} == '(') {
  308. $val = preg_split('/\s*,\s*/', substr(substr($key, 1), 0, -1));
  309. } elseif (preg_match('/ASC|DESC$/', $key)) {
  310. $option = 'order';
  311. $val = $Model->{$name}->alias.'.'.$key;
  312. } elseif (preg_match('/[ =!]/', $key)) {
  313. $option = 'conditions';
  314. $val = $Model->{$name}->alias.'.'.$key;
  315. }
  316. $children[$option] = is_array($val) ? $val : array($val);
  317. $newChildren = null;
  318. if (!empty($name) && !empty($children[$key])) {
  319. $newChildren = $children[$key];
  320. }
  321. unset($children[$key], $children[$i]);
  322. $key = $option;
  323. $optionKey = true;
  324. if (!empty($newChildren)) {
  325. $children = Set::merge($children, $newChildren);
  326. }
  327. }
  328. if ($optionKey && isset($children[$key])) {
  329. if (!empty($keep[$name][$key]) && is_array($keep[$name][$key])) {
  330. $keep[$name][$key] = array_merge((isset($keep[$name][$key]) ? $keep[$name][$key] : array()), (array) $children[$key]);
  331. } else {
  332. $keep[$name][$key] = $children[$key];
  333. }
  334. unset($children[$key]);
  335. }
  336. }
  337. if (!isset($Model->{$name}) || !is_object($Model->{$name})) {
  338. if ($throwErrors) {
  339. trigger_error(__('Model "%s" is not associated with model "%s"', $Model->alias, $name), E_USER_WARNING);
  340. }
  341. continue;
  342. }
  343. $containments = $this->containments($Model->{$name}, $children, $containments);
  344. $depths[] = $containments['depth'] + 1;
  345. if (!isset($keep[$name])) {
  346. $keep[$name] = array();
  347. }
  348. }
  349. if (!isset($containments['models'][$Model->alias])) {
  350. $containments['models'][$Model->alias] = array('keep' => array(),'instance' => &$Model);
  351. }
  352. $containments['models'][$Model->alias]['keep'] = array_merge($containments['models'][$Model->alias]['keep'], $keep);
  353. $containments['depth'] = empty($depths) ? 0 : max($depths);
  354. return $containments;
  355. }
  356. /**
  357. * Calculate needed fields to fetch the required bindings for the given model.
  358. *
  359. * @param object $Model Model
  360. * @param array $map Map of relations for given model
  361. * @param mixed $fields If array, fields to initially load, if false use $Model as primary model
  362. * @return array Fields
  363. */
  364. public function fieldDependencies(&$Model, $map, $fields = array()) {
  365. if ($fields === false) {
  366. foreach ($map as $parent => $children) {
  367. foreach ($children as $type => $bindings) {
  368. foreach ($bindings as $dependency) {
  369. if ($type == 'hasAndBelongsToMany') {
  370. $fields[$parent][] = '--primaryKey--';
  371. } else if ($type == 'belongsTo') {
  372. $fields[$parent][] = $dependency . '.--primaryKey--';
  373. }
  374. }
  375. }
  376. }
  377. return $fields;
  378. }
  379. if (empty($map[$Model->alias])) {
  380. return $fields;
  381. }
  382. foreach ($map[$Model->alias] as $type => $bindings) {
  383. foreach ($bindings as $dependency) {
  384. $innerFields = array();
  385. switch ($type) {
  386. case 'belongsTo':
  387. $fields[] = $Model->{$type}[$dependency]['foreignKey'];
  388. break;
  389. case 'hasOne':
  390. case 'hasMany':
  391. $innerFields[] = $Model->$dependency->primaryKey;
  392. $fields[] = $Model->primaryKey;
  393. break;
  394. }
  395. if (!empty($innerFields) && !empty($Model->{$type}[$dependency]['fields'])) {
  396. $Model->{$type}[$dependency]['fields'] = array_unique(array_merge($Model->{$type}[$dependency]['fields'], $innerFields));
  397. }
  398. }
  399. }
  400. return array_unique($fields);
  401. }
  402. /**
  403. * Build the map of containments
  404. *
  405. * @param array $containments Containments
  406. * @return array Built containments
  407. */
  408. public function containmentsMap($containments) {
  409. $map = array();
  410. foreach ($containments['models'] as $name => $model) {
  411. $instance = $model['instance'];
  412. foreach ($this->types as $type) {
  413. foreach ($instance->{$type} as $assoc => $options) {
  414. if (isset($model['keep'][$assoc])) {
  415. $map[$name][$type] = isset($map[$name][$type]) ? array_merge($map[$name][$type], (array)$assoc) : (array)$assoc;
  416. }
  417. }
  418. }
  419. }
  420. return $map;
  421. }
  422. }