PageRenderTime 39ms CodeModel.GetById 17ms RepoModel.GetById 0ms app.codeStats 0ms

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

https://bitbucket.org/npitts/easyuat2.0
PHP | 428 lines | 289 code | 24 blank | 115 comment | 83 complexity | b1a12ae68b977c05609523bb83688bd3 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-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. /**
  22. * Behavior to allow for dynamic and atomic manipulation of a Model's associations
  23. * used for a find call. Most useful for limiting the amount of associations and
  24. * data returned.
  25. *
  26. * @package Cake.Model.Behavior
  27. * @link http://book.cakephp.org/2.0/en/core-libraries/behaviors/containable.html
  28. */
  29. class ContainableBehavior extends ModelBehavior {
  30. /**
  31. * Types of relationships available for models
  32. *
  33. * @var array
  34. */
  35. public $types = array('belongsTo', 'hasOne', 'hasMany', 'hasAndBelongsToMany');
  36. /**
  37. * Runtime configuration for this behavior
  38. *
  39. * @var array
  40. */
  41. public $runtime = array();
  42. /**
  43. * Initiate behavior for the model using specified settings.
  44. *
  45. * Available settings:
  46. *
  47. * - recursive: (boolean, optional) set to true to allow containable to automatically
  48. * determine the recursiveness level needed to fetch specified models,
  49. * and set the model recursiveness to this level. setting it to false
  50. * disables this feature. DEFAULTS TO: true
  51. * - notices: (boolean, optional) issues E_NOTICES for bindings referenced in a
  52. * containable call that are not valid. DEFAULTS TO: true
  53. * - autoFields: (boolean, optional) auto-add needed fields to fetch requested
  54. * bindings. DEFAULTS TO: true
  55. *
  56. * @param Model $Model Model using the behavior
  57. * @param array $settings Settings to override for model.
  58. * @return void
  59. */
  60. public function setup(Model $Model, $settings = array()) {
  61. if (!isset($this->settings[$Model->alias])) {
  62. $this->settings[$Model->alias] = array('recursive' => true, 'notices' => true, 'autoFields' => true);
  63. }
  64. $this->settings[$Model->alias] = array_merge($this->settings[$Model->alias], $settings);
  65. }
  66. /**
  67. * Runs before a find() operation. Used to allow 'contain' setting
  68. * as part of the find call, like this:
  69. *
  70. * `Model->find('all', array('contain' => array('Model1', 'Model2')));`
  71. *
  72. * {{{
  73. * Model->find('all', array('contain' => array(
  74. * 'Model1' => array('Model11', 'Model12'),
  75. * 'Model2',
  76. * 'Model3' => array(
  77. * 'Model31' => 'Model311',
  78. * 'Model32',
  79. * 'Model33' => array('Model331', 'Model332')
  80. * )));
  81. * }}}
  82. *
  83. * @param Model $Model Model using the behavior
  84. * @param array $query Query parameters as set by cake
  85. * @return array
  86. */
  87. public function beforeFind(Model $Model, $query) {
  88. $reset = (isset($query['reset']) ? $query['reset'] : true);
  89. $noContain = (
  90. (isset($this->runtime[$Model->alias]['contain']) && empty($this->runtime[$Model->alias]['contain'])) ||
  91. (isset($query['contain']) && empty($query['contain']))
  92. );
  93. $contain = array();
  94. if (isset($this->runtime[$Model->alias]['contain'])) {
  95. $contain = $this->runtime[$Model->alias]['contain'];
  96. unset($this->runtime[$Model->alias]['contain']);
  97. }
  98. if (isset($query['contain'])) {
  99. $contain = array_merge($contain, (array)$query['contain']);
  100. }
  101. if (
  102. $noContain || !$contain || in_array($contain, array(null, false), true) ||
  103. (isset($contain[0]) && $contain[0] === null)
  104. ) {
  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 $name => $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'])) ? $query['recursive'] : $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 = 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 $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. }