ContainableBehavior.php 14 KB

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