BehaviorCollection.php 8.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301
  1. <?php
  2. /**
  3. * BehaviorCollection
  4. *
  5. * Provides management and interface for interacting with collections of behaviors.
  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. * @package Cake.Model
  19. * @since CakePHP(tm) v 1.2.0.0
  20. * @license MIT License (http://www.opensource.org/licenses/mit-license.php)
  21. */
  22. App::uses('ObjectCollection', 'Utility');
  23. App::uses('CakeEventListener', 'Event');
  24. /**
  25. * Model behavior collection class.
  26. *
  27. * Defines the Behavior interface, and contains common model interaction functionality.
  28. *
  29. * @package Cake.Model
  30. */
  31. class BehaviorCollection extends ObjectCollection implements CakeEventListener {
  32. /**
  33. * Stores a reference to the attached name
  34. *
  35. * @var string
  36. */
  37. public $modelName = null;
  38. /**
  39. * Keeps a list of all methods of attached behaviors
  40. *
  41. * @var array
  42. */
  43. protected $_methods = array();
  44. /**
  45. * Keeps a list of all methods which have been mapped with regular expressions
  46. *
  47. * @var array
  48. */
  49. protected $_mappedMethods = array();
  50. /**
  51. * Attaches a model object and loads a list of behaviors
  52. *
  53. * @param string $modelName
  54. * @param array $behaviors
  55. * @return void
  56. */
  57. public function init($modelName, $behaviors = array()) {
  58. $this->modelName = $modelName;
  59. if (!empty($behaviors)) {
  60. foreach (BehaviorCollection::normalizeObjectArray($behaviors) as $config) {
  61. $this->load($config['class'], $config['settings']);
  62. }
  63. }
  64. }
  65. /**
  66. * Backwards compatible alias for load()
  67. *
  68. * @param string $behavior
  69. * @param array $config
  70. * @return void
  71. * @deprecated Replaced with load()
  72. */
  73. public function attach($behavior, $config = array()) {
  74. return $this->load($behavior, $config);
  75. }
  76. /**
  77. * Loads a behavior into the collection. You can use use `$config['enabled'] = false`
  78. * to load a behavior with callbacks disabled. By default callbacks are enabled. Disable behaviors
  79. * can still be used as normal.
  80. *
  81. * You can alias your behavior as an existing behavior by setting the 'className' key, i.e.,
  82. * {{{
  83. * public $actsAs = array(
  84. * 'Tree' => array(
  85. * 'className' => 'AliasedTree'
  86. * );
  87. * );
  88. * }}}
  89. * All calls to the `Tree` behavior would use `AliasedTree` instead.
  90. *
  91. * @param string $behavior CamelCased name of the behavior to load
  92. * @param array $config Behavior configuration parameters
  93. * @return boolean True on success, false on failure
  94. * @throws MissingBehaviorException when a behavior could not be found.
  95. */
  96. public function load($behavior, $config = array()) {
  97. if (is_array($config) && isset($config['className'])) {
  98. $alias = $behavior;
  99. $behavior = $config['className'];
  100. }
  101. $configDisabled = isset($config['enabled']) && $config['enabled'] === false;
  102. $priority = isset($config['priority']) ? $config['priority'] : $this->defaultPriority;
  103. unset($config['enabled'], $config['className'], $config['priority']);
  104. list($plugin, $name) = pluginSplit($behavior, true);
  105. if (!isset($alias)) {
  106. $alias = $name;
  107. }
  108. $class = $name . 'Behavior';
  109. App::uses($class, $plugin . 'Model/Behavior');
  110. if (!class_exists($class)) {
  111. throw new MissingBehaviorException(array(
  112. 'class' => $class,
  113. 'plugin' => substr($plugin, 0, -1)
  114. ));
  115. }
  116. if (!isset($this->{$alias})) {
  117. if (ClassRegistry::isKeySet($class)) {
  118. $this->_loaded[$alias] = ClassRegistry::getObject($class);
  119. } else {
  120. $this->_loaded[$alias] = new $class();
  121. ClassRegistry::addObject($class, $this->_loaded[$alias]);
  122. if (!empty($plugin)) {
  123. ClassRegistry::addObject($plugin . '.' . $class, $this->_loaded[$alias]);
  124. }
  125. }
  126. } elseif (isset($this->_loaded[$alias]->settings) && isset($this->_loaded[$alias]->settings[$this->modelName])) {
  127. if ($config !== null && $config !== false) {
  128. $config = array_merge($this->_loaded[$alias]->settings[$this->modelName], $config);
  129. } else {
  130. $config = array();
  131. }
  132. }
  133. if (empty($config)) {
  134. $config = array();
  135. }
  136. $this->_loaded[$alias]->settings['priority'] = $priority;
  137. $this->_loaded[$alias]->setup(ClassRegistry::getObject($this->modelName), $config);
  138. foreach ($this->_loaded[$alias]->mapMethods as $method => $methodAlias) {
  139. $this->_mappedMethods[$method] = array($alias, $methodAlias);
  140. }
  141. $methods = get_class_methods($this->_loaded[$alias]);
  142. $parentMethods = array_flip(get_class_methods('ModelBehavior'));
  143. $callbacks = array(
  144. 'setup', 'cleanup', 'beforeFind', 'afterFind', 'beforeSave', 'afterSave',
  145. 'beforeDelete', 'afterDelete', 'onError'
  146. );
  147. foreach ($methods as $m) {
  148. if (!isset($parentMethods[$m])) {
  149. $methodAllowed = (
  150. $m[0] !== '_' && !array_key_exists($m, $this->_methods) &&
  151. !in_array($m, $callbacks)
  152. );
  153. if ($methodAllowed) {
  154. $this->_methods[$m] = array($alias, $m);
  155. }
  156. }
  157. }
  158. if ($configDisabled) {
  159. $this->disable($alias);
  160. } elseif (!$this->enabled($alias)) {
  161. $this->enable($alias);
  162. } else {
  163. $this->setPriority($alias, $priority);
  164. }
  165. return true;
  166. }
  167. /**
  168. * Detaches a behavior from a model
  169. *
  170. * @param string $name CamelCased name of the behavior to unload
  171. * @return void
  172. */
  173. public function unload($name) {
  174. list(, $name) = pluginSplit($name);
  175. if (isset($this->_loaded[$name])) {
  176. $this->_loaded[$name]->cleanup(ClassRegistry::getObject($this->modelName));
  177. parent::unload($name);
  178. }
  179. foreach ($this->_methods as $m => $callback) {
  180. if (is_array($callback) && $callback[0] == $name) {
  181. unset($this->_methods[$m]);
  182. }
  183. }
  184. }
  185. /**
  186. * Backwards compatible alias for unload()
  187. *
  188. * @param string $name Name of behavior
  189. * @return void
  190. * @deprecated Use unload instead.
  191. */
  192. public function detach($name) {
  193. return $this->unload($name);
  194. }
  195. /**
  196. * Dispatches a behavior method. Will call either normal methods or mapped methods.
  197. *
  198. * If a method is not handled by the BehaviorCollection, and $strict is false, a
  199. * special return of `array('unhandled')` will be returned to signal the method was not found.
  200. *
  201. * @param Model $model The model the method was originally called on.
  202. * @param string $method The method called.
  203. * @param array $params Parameters for the called method.
  204. * @param boolean $strict If methods are not found, trigger an error.
  205. * @return array All methods for all behaviors attached to this object
  206. */
  207. public function dispatchMethod($model, $method, $params = array(), $strict = false) {
  208. $method = $this->hasMethod($method, true);
  209. if ($strict && empty($method)) {
  210. trigger_error(__d('cake_dev', "BehaviorCollection::dispatchMethod() - Method %s not found in any attached behavior", $method), E_USER_WARNING);
  211. return null;
  212. }
  213. if (empty($method)) {
  214. return array('unhandled');
  215. }
  216. if (count($method) === 3) {
  217. array_unshift($params, $method[2]);
  218. unset($method[2]);
  219. }
  220. return call_user_func_array(
  221. array($this->_loaded[$method[0]], $method[1]),
  222. array_merge(array(&$model), $params)
  223. );
  224. }
  225. /**
  226. * Gets the method list for attached behaviors, i.e. all public, non-callback methods.
  227. * This does not include mappedMethods.
  228. *
  229. * @return array All public methods for all behaviors attached to this collection
  230. */
  231. public function methods() {
  232. return $this->_methods;
  233. }
  234. /**
  235. * Check to see if a behavior in this collection implements the provided method. Will
  236. * also check mappedMethods.
  237. *
  238. * @param string $method The method to find.
  239. * @param boolean $callback Return the callback for the method.
  240. * @return mixed If $callback is false, a boolean will be returned, if its true, an array
  241. * containing callback information will be returned. For mapped methods the array will have 3 elements.
  242. */
  243. public function hasMethod($method, $callback = false) {
  244. if (isset($this->_methods[$method])) {
  245. return $callback ? $this->_methods[$method] : true;
  246. }
  247. foreach ($this->_mappedMethods as $pattern => $target) {
  248. if (preg_match($pattern . 'i', $method)) {
  249. if ($callback) {
  250. $target[] = $method;
  251. return $target;
  252. }
  253. return true;
  254. }
  255. }
  256. return false;
  257. }
  258. /**
  259. * Returns the implemented events that will get routed to the trigger function
  260. * in order to dispatch them separately on each behavior
  261. *
  262. * @return array
  263. */
  264. public function implementedEvents() {
  265. return array(
  266. 'Model.beforeFind' => 'trigger',
  267. 'Model.afterFind' => 'trigger',
  268. 'Model.beforeValidate' => 'trigger',
  269. 'Model.afterValidate' => 'trigger',
  270. 'Model.beforeSave' => 'trigger',
  271. 'Model.afterSave' => 'trigger',
  272. 'Model.beforeDelete' => 'trigger',
  273. 'Model.afterDelete' => 'trigger'
  274. );
  275. }
  276. }