PageRenderTime 51ms CodeModel.GetById 23ms RepoModel.GetById 1ms app.codeStats 0ms

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

https://github.com/vgarcias/expediamedicus
PHP | 432 lines | 290 code | 27 blank | 115 comment | 84 complexity | b3e24922cfb1c16a8774985a4ffb7f07 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 = false;
  90. $contain = array();
  91. if (isset($this->runtime[$Model->alias]['contain'])) {
  92. $noContain = empty($this->runtime[$Model->alias]['contain']);
  93. $contain = $this->runtime[$Model->alias]['contain'];
  94. unset($this->runtime[$Model->alias]['contain']);
  95. }
  96. if (isset($query['contain'])) {
  97. $noContain = $noContain || empty($query['contain']);
  98. if ($query['contain'] !== false) {
  99. $contain = array_merge($contain, (array)$query['contain']);
  100. }
  101. }
  102. $noContain = $noContain && empty($contain);
  103. if (
  104. $noContain || empty($contain) || (isset($contain[0]) && $contain[0] === null)
  105. ) {
  106. if ($noContain) {
  107. $query['recursive'] = -1;
  108. }
  109. return $query;
  110. }
  111. if ((isset($contain[0]) && is_bool($contain[0])) || is_bool(end($contain))) {
  112. $reset = is_bool(end($contain))
  113. ? array_pop($contain)
  114. : array_shift($contain);
  115. }
  116. $containments = $this->containments($Model, $contain);
  117. $map = $this->containmentsMap($containments);
  118. $mandatory = array();
  119. foreach ($containments['models'] as $name => $model) {
  120. $instance = $model['instance'];
  121. $needed = $this->fieldDependencies($instance, $map, false);
  122. if (!empty($needed)) {
  123. $mandatory = array_merge($mandatory, $needed);
  124. }
  125. if ($contain) {
  126. $backupBindings = array();
  127. foreach ($this->types as $relation) {
  128. if (!empty($instance->__backAssociation[$relation])) {
  129. $backupBindings[$relation] = $instance->__backAssociation[$relation];
  130. } else {
  131. $backupBindings[$relation] = $instance->{$relation};
  132. }
  133. }
  134. foreach ($this->types as $type) {
  135. $unbind = array();
  136. foreach ($instance->{$type} as $assoc => $options) {
  137. if (!isset($model['keep'][$assoc])) {
  138. $unbind[] = $assoc;
  139. }
  140. }
  141. if (!empty($unbind)) {
  142. if (!$reset && empty($instance->__backOriginalAssociation)) {
  143. $instance->__backOriginalAssociation = $backupBindings;
  144. }
  145. $instance->unbindModel(array($type => $unbind), $reset);
  146. }
  147. foreach ($instance->{$type} as $assoc => $options) {
  148. if (isset($model['keep'][$assoc]) && !empty($model['keep'][$assoc])) {
  149. if (isset($model['keep'][$assoc]['fields'])) {
  150. $model['keep'][$assoc]['fields'] = $this->fieldDependencies($containments['models'][$assoc]['instance'], $map, $model['keep'][$assoc]['fields']);
  151. }
  152. if (!$reset && empty($instance->__backOriginalAssociation)) {
  153. $instance->__backOriginalAssociation = $backupBindings;
  154. } elseif ($reset) {
  155. $instance->__backAssociation[$type] = $backupBindings[$type];
  156. }
  157. $instance->{$type}[$assoc] = array_merge($instance->{$type}[$assoc], $model['keep'][$assoc]);
  158. }
  159. if (!$reset) {
  160. $instance->__backInnerAssociation[] = $assoc;
  161. }
  162. }
  163. }
  164. }
  165. }
  166. if ($this->settings[$Model->alias]['recursive']) {
  167. $query['recursive'] = (isset($query['recursive'])) ? $query['recursive'] : $containments['depth'];
  168. }
  169. $autoFields = ($this->settings[$Model->alias]['autoFields']
  170. && !in_array($Model->findQueryType, array('list', 'count'))
  171. && !empty($query['fields']));
  172. if (!$autoFields) {
  173. return $query;
  174. }
  175. $query['fields'] = (array)$query['fields'];
  176. foreach (array('hasOne', 'belongsTo') as $type) {
  177. if (!empty($Model->{$type})) {
  178. foreach ($Model->{$type} as $assoc => $data) {
  179. if ($Model->useDbConfig == $Model->{$assoc}->useDbConfig && !empty($data['fields'])) {
  180. foreach ((array)$data['fields'] as $field) {
  181. $query['fields'][] = (strpos($field, '.') === false ? $assoc . '.' : '') . $field;
  182. }
  183. }
  184. }
  185. }
  186. }
  187. if (!empty($mandatory[$Model->alias])) {
  188. foreach ($mandatory[$Model->alias] as $field) {
  189. if ($field == '--primaryKey--') {
  190. $field = $Model->primaryKey;
  191. } elseif (preg_match('/^.+\.\-\-[^-]+\-\-$/', $field)) {
  192. list($modelName, $field) = explode('.', $field);
  193. if ($Model->useDbConfig == $Model->{$modelName}->useDbConfig) {
  194. $field = $modelName . '.' . (
  195. ($field === '--primaryKey--') ? $Model->$modelName->primaryKey : $field
  196. );
  197. } else {
  198. $field = null;
  199. }
  200. }
  201. if ($field !== null) {
  202. $query['fields'][] = $field;
  203. }
  204. }
  205. }
  206. $query['fields'] = array_unique($query['fields']);
  207. return $query;
  208. }
  209. /**
  210. * Unbinds all relations from a model except the specified ones. Calling this function without
  211. * parameters unbinds all related models.
  212. *
  213. * @param Model $Model Model on which binding restriction is being applied
  214. * @return void
  215. * @link http://book.cakephp.org/2.0/en/core-libraries/behaviors/containable.html#using-containable
  216. */
  217. public function contain(Model $Model) {
  218. $args = func_get_args();
  219. $contain = call_user_func_array('am', array_slice($args, 1));
  220. $this->runtime[$Model->alias]['contain'] = $contain;
  221. }
  222. /**
  223. * Permanently restore the original binding settings of given model, useful
  224. * for restoring the bindings after using 'reset' => false as part of the
  225. * contain call.
  226. *
  227. * @param Model $Model Model on which to reset bindings
  228. * @return void
  229. */
  230. public function resetBindings(Model $Model) {
  231. if (!empty($Model->__backOriginalAssociation)) {
  232. $Model->__backAssociation = $Model->__backOriginalAssociation;
  233. unset($Model->__backOriginalAssociation);
  234. }
  235. $Model->resetAssociations();
  236. if (!empty($Model->__backInnerAssociation)) {
  237. $assocs = $Model->__backInnerAssociation;
  238. $Model->__backInnerAssociation = array();
  239. foreach ($assocs as $currentModel) {
  240. $this->resetBindings($Model->$currentModel);
  241. }
  242. }
  243. }
  244. /**
  245. * Process containments for model.
  246. *
  247. * @param Model $Model Model on which binding restriction is being applied
  248. * @param array $contain Parameters to use for restricting this model
  249. * @param array $containments Current set of containments
  250. * @param boolean $throwErrors Whether non-existent bindings show throw errors
  251. * @return array Containments
  252. */
  253. public function containments(Model $Model, $contain, $containments = array(), $throwErrors = null) {
  254. $options = array('className', 'joinTable', 'with', 'foreignKey', 'associationForeignKey', 'conditions', 'fields', 'order', 'limit', 'offset', 'unique', 'finderQuery', 'deleteQuery', 'insertQuery');
  255. $keep = array();
  256. if ($throwErrors === null) {
  257. $throwErrors = (empty($this->settings[$Model->alias]) ? true : $this->settings[$Model->alias]['notices']);
  258. }
  259. foreach ((array)$contain as $name => $children) {
  260. if (is_numeric($name)) {
  261. $name = $children;
  262. $children = array();
  263. }
  264. if (preg_match('/(?<!\.)\(/', $name)) {
  265. $name = str_replace('(', '.(', $name);
  266. }
  267. if (strpos($name, '.') !== false) {
  268. $chain = explode('.', $name);
  269. $name = array_shift($chain);
  270. $children = array(implode('.', $chain) => $children);
  271. }
  272. $children = (array)$children;
  273. foreach ($children as $key => $val) {
  274. if (is_string($key) && is_string($val) && !in_array($key, $options, true)) {
  275. $children[$key] = (array)$val;
  276. }
  277. }
  278. $keys = array_keys($children);
  279. if ($keys && isset($children[0])) {
  280. $keys = array_merge(array_values($children), $keys);
  281. }
  282. foreach ($keys as $i => $key) {
  283. if (is_array($key)) {
  284. continue;
  285. }
  286. $optionKey = in_array($key, $options, true);
  287. if (!$optionKey && is_string($key) && preg_match('/^[a-z(]/', $key) && (!isset($Model->{$key}) || !is_object($Model->{$key}))) {
  288. $option = 'fields';
  289. $val = array($key);
  290. if ($key{0} == '(') {
  291. $val = preg_split('/\s*,\s*/', substr($key, 1, -1));
  292. } elseif (preg_match('/ASC|DESC$/', $key)) {
  293. $option = 'order';
  294. $val = $Model->{$name}->alias . '.' . $key;
  295. } elseif (preg_match('/[ =!]/', $key)) {
  296. $option = 'conditions';
  297. $val = $Model->{$name}->alias . '.' . $key;
  298. }
  299. $children[$option] = is_array($val) ? $val : array($val);
  300. $newChildren = null;
  301. if (!empty($name) && !empty($children[$key])) {
  302. $newChildren = $children[$key];
  303. }
  304. unset($children[$key], $children[$i]);
  305. $key = $option;
  306. $optionKey = true;
  307. if (!empty($newChildren)) {
  308. $children = Hash::merge($children, $newChildren);
  309. }
  310. }
  311. if ($optionKey && isset($children[$key])) {
  312. if (!empty($keep[$name][$key]) && is_array($keep[$name][$key])) {
  313. $keep[$name][$key] = array_merge((isset($keep[$name][$key]) ? $keep[$name][$key] : array()), (array)$children[$key]);
  314. } else {
  315. $keep[$name][$key] = $children[$key];
  316. }
  317. unset($children[$key]);
  318. }
  319. }
  320. if (!isset($Model->{$name}) || !is_object($Model->{$name})) {
  321. if ($throwErrors) {
  322. trigger_error(__d('cake_dev', 'Model "%s" is not associated with model "%s"', $Model->alias, $name), E_USER_WARNING);
  323. }
  324. continue;
  325. }
  326. $containments = $this->containments($Model->{$name}, $children, $containments);
  327. $depths[] = $containments['depth'] + 1;
  328. if (!isset($keep[$name])) {
  329. $keep[$name] = array();
  330. }
  331. }
  332. if (!isset($containments['models'][$Model->alias])) {
  333. $containments['models'][$Model->alias] = array('keep' => array(), 'instance' => &$Model);
  334. }
  335. $containments['models'][$Model->alias]['keep'] = array_merge($containments['models'][$Model->alias]['keep'], $keep);
  336. $containments['depth'] = empty($depths) ? 0 : max($depths);
  337. return $containments;
  338. }
  339. /**
  340. * Calculate needed fields to fetch the required bindings for the given model.
  341. *
  342. * @param Model $Model Model
  343. * @param array $map Map of relations for given model
  344. * @param array|boolean $fields If array, fields to initially load, if false use $Model as primary model
  345. * @return array Fields
  346. */
  347. public function fieldDependencies(Model $Model, $map, $fields = array()) {
  348. if ($fields === false) {
  349. foreach ($map as $parent => $children) {
  350. foreach ($children as $type => $bindings) {
  351. foreach ($bindings as $dependency) {
  352. if ($type == 'hasAndBelongsToMany') {
  353. $fields[$parent][] = '--primaryKey--';
  354. } elseif ($type == 'belongsTo') {
  355. $fields[$parent][] = $dependency . '.--primaryKey--';
  356. }
  357. }
  358. }
  359. }
  360. return $fields;
  361. }
  362. if (empty($map[$Model->alias])) {
  363. return $fields;
  364. }
  365. foreach ($map[$Model->alias] as $type => $bindings) {
  366. foreach ($bindings as $dependency) {
  367. $innerFields = array();
  368. switch ($type) {
  369. case 'belongsTo':
  370. $fields[] = $Model->{$type}[$dependency]['foreignKey'];
  371. break;
  372. case 'hasOne':
  373. case 'hasMany':
  374. $innerFields[] = $Model->$dependency->primaryKey;
  375. $fields[] = $Model->primaryKey;
  376. break;
  377. }
  378. if (!empty($innerFields) && !empty($Model->{$type}[$dependency]['fields'])) {
  379. $Model->{$type}[$dependency]['fields'] = array_unique(array_merge($Model->{$type}[$dependency]['fields'], $innerFields));
  380. }
  381. }
  382. }
  383. return array_unique($fields);
  384. }
  385. /**
  386. * Build the map of containments
  387. *
  388. * @param array $containments Containments
  389. * @return array Built containments
  390. */
  391. public function containmentsMap($containments) {
  392. $map = array();
  393. foreach ($containments['models'] as $name => $model) {
  394. $instance = $model['instance'];
  395. foreach ($this->types as $type) {
  396. foreach ($instance->{$type} as $assoc => $options) {
  397. if (isset($model['keep'][$assoc])) {
  398. $map[$name][$type] = isset($map[$name][$type]) ? array_merge($map[$name][$type], (array)$assoc) : (array)$assoc;
  399. }
  400. }
  401. }
  402. }
  403. return $map;
  404. }
  405. }