ContainableBehavior.php 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434
  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 (c) Cake Software Foundation, Inc. (http://cakefoundation.org)
  11. *
  12. * Licensed under The MIT License
  13. * For full copyright and license information, please see the LICENSE.txt
  14. * Redistributions of files must retain the above copyright notice.
  15. *
  16. * @copyright Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org)
  17. * @link http://cakephp.org CakePHP(tm) Project
  18. * @since CakePHP(tm) v 1.2.0.5669
  19. * @license http://www.opensource.org/licenses/mit-license.php MIT License
  20. */
  21. namespace Cake\Model\Behavior;
  22. use Cake\Model\Model;
  23. use Cake\Model\ModelBehavior;
  24. use Cake\Utility\Hash;
  25. /**
  26. * Behavior to allow for dynamic and atomic manipulation of a Model's associations
  27. * used for a find call. Most useful for limiting the amount of associations and
  28. * data returned.
  29. *
  30. * @link http://book.cakephp.org/2.0/en/core-libraries/behaviors/containable.html
  31. */
  32. class ContainableBehavior extends ModelBehavior {
  33. /**
  34. * Types of relationships available for models
  35. *
  36. * @var array
  37. */
  38. public $types = array('belongsTo', 'hasOne', 'hasMany', 'hasAndBelongsToMany');
  39. /**
  40. * Runtime configuration for this behavior
  41. *
  42. * @var array
  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 Model $Model Model using the behavior
  60. * @param array $settings Settings to override for model.
  61. * @return void
  62. */
  63. public function setup(Model $Model, $settings = array()) {
  64. if (!isset($this->settings[$Model->alias])) {
  65. $this->settings[$Model->alias] = array('recursive' => true, 'notices' => true, 'autoFields' => true);
  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 Model $Model Model using the behavior
  87. * @param array $query Query parameters as set by cake
  88. * @return array
  89. */
  90. public function beforeFind(Model $Model, $query) {
  91. $reset = (isset($query['reset']) ? $query['reset'] : true);
  92. $noContain = false;
  93. $contain = array();
  94. if (isset($this->runtime[$Model->alias]['contain'])) {
  95. $noContain = empty($this->runtime[$Model->alias]['contain']);
  96. $contain = $this->runtime[$Model->alias]['contain'];
  97. unset($this->runtime[$Model->alias]['contain']);
  98. }
  99. if (isset($query['contain'])) {
  100. $noContain = $noContain || empty($query['contain']);
  101. if ($query['contain'] !== false) {
  102. $contain = array_merge($contain, (array)$query['contain']);
  103. }
  104. }
  105. $noContain = $noContain && empty($contain);
  106. if ($noContain || empty($contain)) {
  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 $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. } elseif ($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'])) ? max($query['recursive'], $containments['depth']) : $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. } elseif (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/2.0/en/core-libraries/behaviors/containable.html#using-containable
  217. */
  218. public function contain(Model $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 $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 Whether non-existent bindings show throw errors
  252. * @return array Containments
  253. */
  254. public function containments(Model $Model, $contain, $containments = array(), $throwErrors = null) {
  255. $options = array('className', 'joinTable', 'with', 'foreignKey', 'associationForeignKey', 'conditions', 'fields', 'order', 'limit', 'offset', 'unique', 'finderQuery');
  256. $keep = array();
  257. if ($throwErrors === null) {
  258. $throwErrors = (empty($this->settings[$Model->alias]) ? true : $this->settings[$Model->alias]['notices']);
  259. }
  260. foreach ((array)$contain as $name => $children) {
  261. if (is_numeric($name)) {
  262. $name = $children;
  263. $children = array();
  264. }
  265. if (preg_match('/(?<!\.)\(/', $name)) {
  266. $name = str_replace('(', '.(', $name);
  267. }
  268. if (strpos($name, '.') !== false) {
  269. $chain = explode('.', $name);
  270. $name = array_shift($chain);
  271. $children = array(implode('.', $chain) => $children);
  272. }
  273. $children = (array)$children;
  274. foreach ($children as $key => $val) {
  275. if (is_string($key) && is_string($val) && !in_array($key, $options, true)) {
  276. $children[$key] = (array)$val;
  277. }
  278. }
  279. $keys = array_keys($children);
  280. if ($keys && isset($children[0])) {
  281. $keys = array_merge(array_values($children), $keys);
  282. }
  283. foreach ($keys as $i => $key) {
  284. if (is_array($key)) {
  285. continue;
  286. }
  287. $optionKey = in_array($key, $options, true);
  288. if (!$optionKey && is_string($key) && preg_match('/^[a-z(]/', $key) && (!isset($Model->{$key}) || !is_object($Model->{$key}))) {
  289. $option = 'fields';
  290. $val = array($key);
  291. if ($key{0} === '(') {
  292. $val = preg_split('/\s*,\s*/', substr($key, 1, -1));
  293. } elseif (preg_match('/ASC|DESC$/', $key)) {
  294. $option = 'order';
  295. $val = $Model->{$name}->alias . '.' . $key;
  296. } elseif (preg_match('/[ =!]/', $key)) {
  297. $option = 'conditions';
  298. $val = $Model->{$name}->alias . '.' . $key;
  299. }
  300. $children[$option] = is_array($val) ? $val : array($val);
  301. $newChildren = null;
  302. if (!empty($name) && !empty($children[$key])) {
  303. $newChildren = $children[$key];
  304. }
  305. unset($children[$key], $children[$i]);
  306. $key = $option;
  307. $optionKey = true;
  308. if (!empty($newChildren)) {
  309. $children = Hash::merge($children, $newChildren);
  310. }
  311. }
  312. if ($optionKey && isset($children[$key])) {
  313. if (!empty($keep[$name][$key]) && is_array($keep[$name][$key])) {
  314. $keep[$name][$key] = array_merge((isset($keep[$name][$key]) ? $keep[$name][$key] : array()), (array)$children[$key]);
  315. } else {
  316. $keep[$name][$key] = $children[$key];
  317. }
  318. unset($children[$key]);
  319. }
  320. }
  321. if (!isset($Model->{$name}) || !is_object($Model->{$name})) {
  322. if ($throwErrors) {
  323. trigger_error(__d('cake_dev', 'Model "%s" is not associated with model "%s"', $Model->alias, $name), E_USER_WARNING);
  324. }
  325. continue;
  326. }
  327. $containments = $this->containments($Model->{$name}, $children, $containments);
  328. $depths[] = $containments['depth'] + 1;
  329. if (!isset($keep[$name])) {
  330. $keep[$name] = array();
  331. }
  332. }
  333. if (!isset($containments['models'][$Model->alias])) {
  334. $containments['models'][$Model->alias] = array('keep' => array(), 'instance' => &$Model);
  335. }
  336. $containments['models'][$Model->alias]['keep'] = array_merge($containments['models'][$Model->alias]['keep'], $keep);
  337. $containments['depth'] = empty($depths) ? 0 : max($depths);
  338. return $containments;
  339. }
  340. /**
  341. * Calculate needed fields to fetch the required bindings for the given model.
  342. *
  343. * @param Model $Model Model
  344. * @param array $map Map of relations for given model
  345. * @param array|boolean $fields If array, fields to initially load, if false use $Model as primary model
  346. * @return array Fields
  347. */
  348. public function fieldDependencies(Model $Model, $map, $fields = array()) {
  349. if ($fields === false) {
  350. foreach ($map as $parent => $children) {
  351. foreach ($children as $type => $bindings) {
  352. foreach ($bindings as $dependency) {
  353. if ($type === 'hasAndBelongsToMany') {
  354. $fields[$parent][] = '--primaryKey--';
  355. } elseif ($type === 'belongsTo') {
  356. $fields[$parent][] = $dependency . '.--primaryKey--';
  357. }
  358. }
  359. }
  360. }
  361. return $fields;
  362. }
  363. if (empty($map[$Model->alias])) {
  364. return $fields;
  365. }
  366. foreach ($map[$Model->alias] as $type => $bindings) {
  367. foreach ($bindings as $dependency) {
  368. $innerFields = array();
  369. switch ($type) {
  370. case 'belongsTo':
  371. $fields[] = $Model->{$type}[$dependency]['foreignKey'];
  372. break;
  373. case 'hasOne':
  374. case 'hasMany':
  375. $innerFields[] = $Model->$dependency->primaryKey;
  376. $fields[] = $Model->primaryKey;
  377. break;
  378. }
  379. if (!empty($innerFields) && !empty($Model->{$type}[$dependency]['fields'])) {
  380. $Model->{$type}[$dependency]['fields'] = array_unique(array_merge($Model->{$type}[$dependency]['fields'], $innerFields));
  381. }
  382. }
  383. }
  384. return array_unique($fields);
  385. }
  386. /**
  387. * Build the map of containments
  388. *
  389. * @param array $containments Containments
  390. * @return array Built containments
  391. */
  392. public function containmentsMap($containments) {
  393. $map = array();
  394. foreach ($containments['models'] as $name => $model) {
  395. $instance = $model['instance'];
  396. foreach ($this->types as $type) {
  397. foreach ($instance->{$type} as $assoc => $options) {
  398. if (isset($model['keep'][$assoc])) {
  399. $map[$name][$type] = isset($map[$name][$type]) ? array_merge($map[$name][$type], (array)$assoc) : (array)$assoc;
  400. }
  401. }
  402. }
  403. }
  404. return $map;
  405. }
  406. }