ContainableBehavior.php 14 KB

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