ContainableBehavior.php 15 KB

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