PageRenderTime 59ms CodeModel.GetById 28ms RepoModel.GetById 0ms app.codeStats 1ms

/Vendor/pear-pear.cakephp.org/CakePHP/Cake/Model/Behavior/ContainableBehavior.php

https://bitbucket.org/daveschwan/ronin-group
PHP | 431 lines | 289 code | 28 blank | 114 comment | 78 complexity | ff8e9512b56f43df2e0390a03d8011d5 MD5 | raw file
Possible License(s): LGPL-2.1, MPL-2.0-no-copyleft-exception, MIT, BSD-3-Clause, Apache-2.0
  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. * CakePHP(tm) : Rapid Development Framework (http://cakephp.org)
  8. * Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org)
  9. *
  10. * Licensed under The MIT License
  11. * For full copyright and license information, please see the LICENSE.txt
  12. * Redistributions of files must retain the above copyright notice.
  13. *
  14. * @copyright Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org)
  15. * @link http://cakephp.org CakePHP(tm) Project
  16. * @package Cake.Model.Behavior
  17. * @since CakePHP(tm) v 1.2.0.5669
  18. * @license http://www.opensource.org/licenses/mit-license.php MIT License
  19. */
  20. App::uses('ModelBehavior', 'Model');
  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 ($noContain || empty($contain)) {
  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 $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. } elseif ($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'])) ? max($query['recursive'], $containments['depth']) : $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. } elseif (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 $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 $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 Whether non-existent bindings show throw errors
  249. * @return array Containments
  250. */
  251. public function containments(Model $Model, $contain, $containments = array(), $throwErrors = null) {
  252. $options = array('className', 'joinTable', 'with', 'foreignKey', 'associationForeignKey', 'conditions', 'fields', 'order', 'limit', 'offset', 'unique', 'finderQuery');
  253. $keep = array();
  254. if ($throwErrors === null) {
  255. $throwErrors = (empty($this->settings[$Model->alias]) ? true : $this->settings[$Model->alias]['notices']);
  256. }
  257. foreach ((array)$contain as $name => $children) {
  258. if (is_numeric($name)) {
  259. $name = $children;
  260. $children = array();
  261. }
  262. if (preg_match('/(?<!\.)\(/', $name)) {
  263. $name = str_replace('(', '.(', $name);
  264. }
  265. if (strpos($name, '.') !== false) {
  266. $chain = explode('.', $name);
  267. $name = array_shift($chain);
  268. $children = array(implode('.', $chain) => $children);
  269. }
  270. $children = (array)$children;
  271. foreach ($children as $key => $val) {
  272. if (is_string($key) && is_string($val) && !in_array($key, $options, true)) {
  273. $children[$key] = (array)$val;
  274. }
  275. }
  276. $keys = array_keys($children);
  277. if ($keys && isset($children[0])) {
  278. $keys = array_merge(array_values($children), $keys);
  279. }
  280. foreach ($keys as $i => $key) {
  281. if (is_array($key)) {
  282. continue;
  283. }
  284. $optionKey = in_array($key, $options, true);
  285. if (!$optionKey && is_string($key) && preg_match('/^[a-z(]/', $key) && (!isset($Model->{$key}) || !is_object($Model->{$key}))) {
  286. $option = 'fields';
  287. $val = array($key);
  288. if ($key{0} === '(') {
  289. $val = preg_split('/\s*,\s*/', substr($key, 1, -1));
  290. } elseif (preg_match('/ASC|DESC$/', $key)) {
  291. $option = 'order';
  292. $val = $Model->{$name}->alias . '.' . $key;
  293. } elseif (preg_match('/[ =!]/', $key)) {
  294. $option = 'conditions';
  295. $val = $Model->{$name}->alias . '.' . $key;
  296. }
  297. $children[$option] = is_array($val) ? $val : array($val);
  298. $newChildren = null;
  299. if (!empty($name) && !empty($children[$key])) {
  300. $newChildren = $children[$key];
  301. }
  302. unset($children[$key], $children[$i]);
  303. $key = $option;
  304. $optionKey = true;
  305. if (!empty($newChildren)) {
  306. $children = Hash::merge($children, $newChildren);
  307. }
  308. }
  309. if ($optionKey && isset($children[$key])) {
  310. if (!empty($keep[$name][$key]) && is_array($keep[$name][$key])) {
  311. $keep[$name][$key] = array_merge((isset($keep[$name][$key]) ? $keep[$name][$key] : array()), (array)$children[$key]);
  312. } else {
  313. $keep[$name][$key] = $children[$key];
  314. }
  315. unset($children[$key]);
  316. }
  317. }
  318. if (!isset($Model->{$name}) || !is_object($Model->{$name})) {
  319. if ($throwErrors) {
  320. trigger_error(__d('cake_dev', 'Model "%s" is not associated with model "%s"', $Model->alias, $name), E_USER_WARNING);
  321. }
  322. continue;
  323. }
  324. $containments = $this->containments($Model->{$name}, $children, $containments);
  325. $depths[] = $containments['depth'] + 1;
  326. if (!isset($keep[$name])) {
  327. $keep[$name] = array();
  328. }
  329. }
  330. if (!isset($containments['models'][$Model->alias])) {
  331. $containments['models'][$Model->alias] = array('keep' => array(), 'instance' => &$Model);
  332. }
  333. $containments['models'][$Model->alias]['keep'] = array_merge($containments['models'][$Model->alias]['keep'], $keep);
  334. $containments['depth'] = empty($depths) ? 0 : max($depths);
  335. return $containments;
  336. }
  337. /**
  338. * Calculate needed fields to fetch the required bindings for the given model.
  339. *
  340. * @param Model $Model Model
  341. * @param array $map Map of relations for given model
  342. * @param array|boolean $fields If array, fields to initially load, if false use $Model as primary model
  343. * @return array Fields
  344. */
  345. public function fieldDependencies(Model $Model, $map, $fields = array()) {
  346. if ($fields === false) {
  347. foreach ($map as $parent => $children) {
  348. foreach ($children as $type => $bindings) {
  349. foreach ($bindings as $dependency) {
  350. if ($type === 'hasAndBelongsToMany') {
  351. $fields[$parent][] = '--primaryKey--';
  352. } elseif ($type === 'belongsTo') {
  353. $fields[$parent][] = $dependency . '.--primaryKey--';
  354. }
  355. }
  356. }
  357. }
  358. return $fields;
  359. }
  360. if (empty($map[$Model->alias])) {
  361. return $fields;
  362. }
  363. foreach ($map[$Model->alias] as $type => $bindings) {
  364. foreach ($bindings as $dependency) {
  365. $innerFields = array();
  366. switch ($type) {
  367. case 'belongsTo':
  368. $fields[] = $Model->{$type}[$dependency]['foreignKey'];
  369. break;
  370. case 'hasOne':
  371. case 'hasMany':
  372. $innerFields[] = $Model->$dependency->primaryKey;
  373. $fields[] = $Model->primaryKey;
  374. break;
  375. }
  376. if (!empty($innerFields) && !empty($Model->{$type}[$dependency]['fields'])) {
  377. $Model->{$type}[$dependency]['fields'] = array_unique(array_merge($Model->{$type}[$dependency]['fields'], $innerFields));
  378. }
  379. }
  380. }
  381. return array_unique($fields);
  382. }
  383. /**
  384. * Build the map of containments
  385. *
  386. * @param array $containments Containments
  387. * @return array Built containments
  388. */
  389. public function containmentsMap($containments) {
  390. $map = array();
  391. foreach ($containments['models'] as $name => $model) {
  392. $instance = $model['instance'];
  393. foreach ($this->types as $type) {
  394. foreach ($instance->{$type} as $assoc => $options) {
  395. if (isset($model['keep'][$assoc])) {
  396. $map[$name][$type] = isset($map[$name][$type]) ? array_merge($map[$name][$type], (array)$assoc) : (array)$assoc;
  397. }
  398. }
  399. }
  400. }
  401. return $map;
  402. }
  403. }