ObjectCollection.php 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323
  1. <?php
  2. /**
  3. * CakePHP(tm) : Rapid Development Framework (http://cakephp.org)
  4. * Copyright 2005-2011, Cake Software Foundation, Inc. (http://cakefoundation.org)
  5. *
  6. * Licensed under The MIT License
  7. * Redistributions of files must retain the above copyright notice.
  8. *
  9. * @copyright Copyright 2005-2011, Cake Software Foundation, Inc. (http://cakefoundation.org)
  10. * @link http://cakephp.org CakePHP(tm) Project
  11. * @license MIT License (http://www.opensource.org/licenses/mit-license.php)
  12. */
  13. /**
  14. * Deals with Collections of objects. Keeping registries of those objects,
  15. * loading and constructing new objects and triggering callbacks. Each subclass needs
  16. * to implement its own load() functionality.
  17. *
  18. * All core subclasses of ObjectCollection by convention loaded objects are stored
  19. * in `$this->_loaded`. Enabled objects are stored in `$this->_enabled`. In addition
  20. * the all support an `enabled` option that controls the enabled/disabled state of the object
  21. * when loaded.
  22. *
  23. * @package Cake.Utility
  24. * @since CakePHP(tm) v 2.0
  25. */
  26. abstract class ObjectCollection {
  27. /**
  28. * List of the currently-enabled objects
  29. *
  30. * @var array
  31. */
  32. protected $_enabled = array();
  33. /**
  34. * A hash of loaded objects, indexed by name
  35. *
  36. * @var array
  37. */
  38. protected $_loaded = array();
  39. /**
  40. * Default object priority. A non zero integer.
  41. *
  42. * @var int
  43. */
  44. public $defaultPriority = 10;
  45. /**
  46. * Loads a new object onto the collection. Can throw a variety of exceptions
  47. *
  48. * Implementations of this class support a `$options['enabled']` flag which enables/disables
  49. * a loaded object.
  50. *
  51. * @param string $name Name of object to load.
  52. * @param array $options Array of configuration options for the object to be constructed.
  53. * @return object the constructed object
  54. */
  55. abstract public function load($name, $options = array());
  56. /**
  57. * Trigger a callback method on every object in the collection.
  58. * Used to trigger methods on objects in the collection. Will fire the methods in the
  59. * order they were attached.
  60. *
  61. * ### Options
  62. *
  63. * - `breakOn` Set to the value or values you want the callback propagation to stop on.
  64. * Can either be a scalar value, or an array of values to break on. Defaults to `false`.
  65. *
  66. * - `break` Set to true to enabled breaking. When a trigger is broken, the last returned value
  67. * will be returned. If used in combination with `collectReturn` the collected results will be returned.
  68. * Defaults to `false`.
  69. *
  70. * - `collectReturn` Set to true to collect the return of each object into an array.
  71. * This array of return values will be returned from the trigger() call. Defaults to `false`.
  72. *
  73. * - `modParams` Allows each object the callback gets called on to modify the parameters to the next object.
  74. * Setting modParams to an integer value will allow you to modify the parameter with that index.
  75. * Any non-null value will modify the parameter index indicated.
  76. * Defaults to false.
  77. *
  78. *
  79. * @param string $callback|CakeEvent Method to fire on all the objects. Its assumed all the objects implement
  80. * the method you are calling. If an instance of CakeEvent is provided, then then Event name will parsed to
  81. * get the callback name. This is done by getting the last word after any dot in the event name
  82. * (eg. `Model.afterSave` event will trigger the `afterSave` callback)
  83. * @param array $params Array of parameters for the triggered callback.
  84. * @param array $options Array of options.
  85. * @return mixed Either the last result or all results if collectReturn is on.
  86. * @throws CakeException when modParams is used with an index that does not exist.
  87. */
  88. public function trigger($callback, $params = array(), $options = array()) {
  89. if (empty($this->_enabled)) {
  90. return true;
  91. }
  92. if ($callback instanceof CakeEvent) {
  93. $event = $callback;
  94. if (is_array($event->data)) {
  95. $params =& $event->data;
  96. } else {
  97. $params = array($event->subject());
  98. }
  99. //TODO: Temporary BC check, while we move all the triggers system into the CakeEventManager
  100. foreach (array('breakOn', 'collectReturn', 'modParams') as $opt) {
  101. if (isset($event->{$opt})) {
  102. $options[$opt] = $event->{$opt};
  103. }
  104. }
  105. $callback = array_pop(explode('.', $event->name()));
  106. }
  107. $options = array_merge(
  108. array(
  109. 'break' => false,
  110. 'breakOn' => false,
  111. 'collectReturn' => false,
  112. 'modParams' => false
  113. ),
  114. $options
  115. );
  116. $collected = array();
  117. $list = array_keys($this->_enabled);
  118. if ($options['modParams'] !== false && !isset($params[$options['modParams']])) {
  119. throw new CakeException(__d('cake_dev', 'Cannot use modParams with indexes that do not exist.'));
  120. }
  121. foreach ($list as $name) {
  122. $result = call_user_func_array(array($this->_loaded[$name], $callback), $params);
  123. if ($options['collectReturn'] === true) {
  124. $collected[] = $result;
  125. }
  126. if (
  127. $options['break'] && ($result === $options['breakOn'] ||
  128. (is_array($options['breakOn']) && in_array($result, $options['breakOn'], true)))
  129. ) {
  130. return $result;
  131. } elseif ($options['modParams'] !== false && !in_array($result, array(true, false, null), true)) {
  132. $params[$options['modParams']] = $result;
  133. }
  134. }
  135. if ($options['modParams'] !== false) {
  136. return $params[$options['modParams']];
  137. }
  138. return $options['collectReturn'] ? $collected : $result;
  139. }
  140. /**
  141. * Provide public read access to the loaded objects
  142. *
  143. * @param string $name Name of property to read
  144. * @return mixed
  145. */
  146. public function __get($name) {
  147. if (isset($this->_loaded[$name])) {
  148. return $this->_loaded[$name];
  149. }
  150. return null;
  151. }
  152. /**
  153. * Provide isset access to _loaded
  154. *
  155. * @param string $name Name of object being checked.
  156. * @return boolean
  157. */
  158. public function __isset($name) {
  159. return isset($this->_loaded[$name]);
  160. }
  161. /**
  162. * Enables callbacks on an object or array of objects
  163. *
  164. * @param string|array $name CamelCased name of the object(s) to enable (string or array)
  165. * @param boolean Prioritize enabled list after enabling object(s)
  166. * @return void
  167. */
  168. public function enable($name, $prioritize = true) {
  169. $enabled = false;
  170. foreach ((array)$name as $object) {
  171. if (isset($this->_loaded[$object]) && !isset($this->_enabled[$object])) {
  172. $priority = isset($this->_loaded[$object]->settings['priority']) ? $this->_loaded[$object]->settings['priority'] : $this->defaultPriority;
  173. $this->_enabled[$object] = array($priority);
  174. $enabled = true;
  175. }
  176. }
  177. if ($prioritize && $enabled) {
  178. $this->prioritize();
  179. }
  180. }
  181. /**
  182. * Prioritize list of enabled object
  183. *
  184. * @return array Prioritized list of object
  185. */
  186. public function prioritize() {
  187. $i = 1;
  188. foreach ($this->_enabled as $name => $priority) {
  189. $priority[1] = $i++;
  190. $this->_enabled[$name] = $priority;
  191. }
  192. asort($this->_enabled);
  193. return $this->_enabled;
  194. }
  195. /**
  196. * Set priority for an object or array of objects
  197. *
  198. * @param string|array $name CamelCased name of the object(s) to enable (string or array)
  199. * If string the second param $priority is used else it should be an associative array
  200. * with keys as object names and values as priorities to set.
  201. * @param int|null Integer priority to set or null for default
  202. * @return void
  203. */
  204. public function setPriority($name, $priority = null) {
  205. if (is_string($name)) {
  206. $name = array($name => $priority);
  207. }
  208. foreach ($name as $obj => $prio) {
  209. if (isset($this->_loaded[$obj])) {
  210. if (is_null($prio)) {
  211. $prio = $this->defaultPriority;
  212. }
  213. $this->_loaded[$obj]->settings['priority'] = $prio;
  214. if (isset($this->_enabled[$obj])) {
  215. $this->_enabled[$obj] = array($prio);
  216. }
  217. }
  218. }
  219. $this->prioritize();
  220. }
  221. /**
  222. * Disables callbacks on a object or array of objects. Public object methods are still
  223. * callable as normal.
  224. *
  225. * @param string|array $name CamelCased name of the objects(s) to disable (string or array)
  226. * @return void
  227. */
  228. public function disable($name) {
  229. foreach ((array)$name as $object) {
  230. unset($this->_enabled[$object]);
  231. }
  232. }
  233. /**
  234. * Gets the list of currently-enabled objects, or, the current status of a single objects
  235. *
  236. * @param string $name Optional. The name of the object to check the status of. If omitted,
  237. * returns an array of currently-enabled object
  238. * @return mixed If $name is specified, returns the boolean status of the corresponding object.
  239. * Otherwise, returns an array of all enabled objects.
  240. */
  241. public function enabled($name = null) {
  242. if (!empty($name)) {
  243. return isset($this->_enabled[$name]);
  244. }
  245. return array_keys($this->_enabled);
  246. }
  247. /**
  248. * Gets the list of attached behaviors, or, whether the given behavior is attached
  249. *
  250. * @param string $name Optional. The name of the behavior to check the status of. If omitted,
  251. * returns an array of currently-attached behaviors
  252. * @return mixed If $name is specified, returns the boolean status of the corresponding behavior.
  253. * Otherwise, returns an array of all attached behaviors.
  254. */
  255. public function attached($name = null) {
  256. if (!empty($name)) {
  257. return isset($this->_loaded[$name]);
  258. }
  259. return array_keys($this->_loaded);
  260. }
  261. /**
  262. * Name of the object to remove from the collection
  263. *
  264. * @param string $name Name of the object to delete.
  265. * @return void
  266. */
  267. public function unload($name) {
  268. list($plugin, $name) = pluginSplit($name);
  269. unset($this->_loaded[$name]);
  270. unset($this->_enabled[$name]);
  271. }
  272. /**
  273. * Adds or overwrites an instantiated object to the collection
  274. *
  275. * @param string $name Name of the object
  276. * @param Object $object The object to use
  277. * @return array Loaded objects
  278. */
  279. public function set($name = null, $object = null) {
  280. if (!empty($name) && !empty($object)) {
  281. list($plugin, $name) = pluginSplit($name);
  282. $this->_loaded[$name] = $object;
  283. }
  284. return $this->_loaded;
  285. }
  286. /**
  287. * Normalizes an object array, creates an array that makes lazy loading
  288. * easier
  289. *
  290. * @param array $objects Array of child objects to normalize.
  291. * @return array Array of normalized objects.
  292. */
  293. public static function normalizeObjectArray($objects) {
  294. $normal = array();
  295. foreach ($objects as $i => $objectName) {
  296. $options = array();
  297. if (!is_int($i)) {
  298. $options = (array)$objectName;
  299. $objectName = $i;
  300. }
  301. list($plugin, $name) = pluginSplit($objectName);
  302. $normal[$name] = array('class' => $objectName, 'settings' => $options);
  303. }
  304. return $normal;
  305. }
  306. }