PageRenderTime 27ms CodeModel.GetById 13ms RepoModel.GetById 0ms app.codeStats 0ms

/lib/Cake/Model/Behavior/ContainableBehavior.php

https://bitbucket.org/luobailiang/cake
PHP | 427 lines | 290 code | 23 blank | 114 comment | 89 complexity | 8cf6b9dd14f353561e75f2533789260f MD5 | raw file
  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/2.0/en/core-libraries/behaviors/containable.html
  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. $this->settings[$Model->alias] = array_merge($this->settings[$Model->alias], $settings);
  64. }
  65. /**
  66. * Runs before a find() operation. Used to allow 'contain' setting
  67. * as part of the find call, like this:
  68. *
  69. * `Model->find('all', array('contain' => array('Model1', 'Model2')));`
  70. *
  71. * {{{
  72. * Model->find('all', array('contain' => array(
  73. * 'Model1' => array('Model11', 'Model12'),
  74. * 'Model2',
  75. * 'Model3' => array(
  76. * 'Model31' => 'Model311',
  77. * 'Model32',
  78. * 'Model33' => array('Model331', 'Model332')
  79. * )));
  80. * }}}
  81. *
  82. * @param Model $Model Model using the behavior
  83. * @param array $query Query parameters as set by cake
  84. * @return array
  85. */
  86. public function beforeFind($Model, $query) {
  87. $reset = (isset($query['reset']) ? $query['reset'] : true);
  88. $noContain = (
  89. (isset($this->runtime[$Model->alias]['contain']) && empty($this->runtime[$Model->alias]['contain'])) ||
  90. (isset($query['contain']) && empty($query['contain']))
  91. );
  92. $contain = array();
  93. if (isset($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. $contain = array_merge($contain, (array)$query['contain']);
  99. }
  100. if (
  101. $noContain || !$contain || in_array($contain, array(null, false), true) ||
  102. (isset($contain[0]) && $contain[0] === null)
  103. ) {
  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. }
  143. $instance->unbindModel(array($type => $unbind), $reset);
  144. }
  145. foreach ($instance->{$type} as $assoc => $options) {
  146. if (isset($model['keep'][$assoc]) && !empty($model['keep'][$assoc])) {
  147. if (isset($model['keep'][$assoc]['fields'])) {
  148. $model['keep'][$assoc]['fields'] = $this->fieldDependencies($containments['models'][$assoc]['instance'], $map, $model['keep'][$assoc]['fields']);
  149. }
  150. if (!$reset && empty($instance->__backOriginalAssociation)) {
  151. $instance->__backOriginalAssociation = $backupBindings;
  152. } else if ($reset) {
  153. $instance->__backAssociation[$type] = $backupBindings[$type];
  154. }
  155. $instance->{$type}[$assoc] = array_merge($instance->{$type}[$assoc], $model['keep'][$assoc]);
  156. }
  157. if (!$reset) {
  158. $instance->__backInnerAssociation[] = $assoc;
  159. }
  160. }
  161. }
  162. }
  163. }
  164. if ($this->settings[$Model->alias]['recursive']) {
  165. $query['recursive'] = (isset($query['recursive'])) ? $query['recursive'] : $containments['depth'];
  166. }
  167. $autoFields = ($this->settings[$Model->alias]['autoFields']
  168. && !in_array($Model->findQueryType, array('list', 'count'))
  169. && !empty($query['fields']));
  170. if (!$autoFields) {
  171. return $query;
  172. }
  173. $query['fields'] = (array)$query['fields'];
  174. foreach (array('hasOne', 'belongsTo') as $type) {
  175. if (!empty($Model->{$type})) {
  176. foreach ($Model->{$type} as $assoc => $data) {
  177. if ($Model->useDbConfig == $Model->{$assoc}->useDbConfig && !empty($data['fields'])) {
  178. foreach ((array) $data['fields'] as $field) {
  179. $query['fields'][] = (strpos($field, '.') === false ? $assoc . '.' : '') . $field;
  180. }
  181. }
  182. }
  183. }
  184. }
  185. if (!empty($mandatory[$Model->alias])) {
  186. foreach ($mandatory[$Model->alias] as $field) {
  187. if ($field == '--primaryKey--') {
  188. $field = $Model->primaryKey;
  189. } else if (preg_match('/^.+\.\-\-[^-]+\-\-$/', $field)) {
  190. list($modelName, $field) = explode('.', $field);
  191. if ($Model->useDbConfig == $Model->{$modelName}->useDbConfig) {
  192. $field = $modelName . '.' . (
  193. ($field === '--primaryKey--') ? $Model->$modelName->primaryKey : $field
  194. );
  195. } else {
  196. $field = null;
  197. }
  198. }
  199. if ($field !== null) {
  200. $query['fields'][] = $field;
  201. }
  202. }
  203. }
  204. $query['fields'] = array_unique($query['fields']);
  205. return $query;
  206. }
  207. /**
  208. * Unbinds all relations from a model except the specified ones. Calling this function without
  209. * parameters unbinds all related models.
  210. *
  211. * @param Model $Model Model on which binding restriction is being applied
  212. * @return void
  213. * @link http://book.cakephp.org/2.0/en/core-libraries/behaviors/containable.html#using-containable
  214. */
  215. public function contain($Model) {
  216. $args = func_get_args();
  217. $contain = call_user_func_array('am', array_slice($args, 1));
  218. $this->runtime[$Model->alias]['contain'] = $contain;
  219. }
  220. /**
  221. * Permanently restore the original binding settings of given model, useful
  222. * for restoring the bindings after using 'reset' => false as part of the
  223. * contain call.
  224. *
  225. * @param Model $Model Model on which to reset bindings
  226. * @return void
  227. */
  228. public function resetBindings($Model) {
  229. if (!empty($Model->__backOriginalAssociation)) {
  230. $Model->__backAssociation = $Model->__backOriginalAssociation;
  231. unset($Model->__backOriginalAssociation);
  232. }
  233. $Model->resetAssociations();
  234. if (!empty($Model->__backInnerAssociation)) {
  235. $assocs = $Model->__backInnerAssociation;
  236. $Model->__backInnerAssociation = array();
  237. foreach ($assocs as $currentModel) {
  238. $this->resetBindings($Model->$currentModel);
  239. }
  240. }
  241. }
  242. /**
  243. * Process containments for model.
  244. *
  245. * @param Model $Model Model on which binding restriction is being applied
  246. * @param array $contain Parameters to use for restricting this model
  247. * @param array $containments Current set of containments
  248. * @param boolean $throwErrors Wether unexisting bindings show throw errors
  249. * @return array Containments
  250. */
  251. public function containments($Model, $contain, $containments = array(), $throwErrors = null) {
  252. $options = array('className', 'joinTable', 'with', 'foreignKey', 'associationForeignKey', 'conditions', 'fields', 'order', 'limit', 'offset', 'unique', 'finderQuery', 'deleteQuery', 'insertQuery');
  253. $keep = array();
  254. $depth = 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(substr($key, 1), 0, -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 = Set::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 mixed $fields If array, fields to initially load, if false use $Model as primary model
  344. * @return array Fields
  345. */
  346. public function fieldDependencies($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. } else if ($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. }