ObjectCollection.php 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324
  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. }
  97. if (empty($event->omitSubject)) {
  98. $subject = $event->subject();
  99. }
  100. //TODO: Temporary BC check, while we move all the triggers system into the CakeEventManager
  101. foreach (array('break', 'breakOn', 'collectReturn', 'modParams') as $opt) {
  102. if (isset($event->{$opt})) {
  103. $options[$opt] = $event->{$opt};
  104. }
  105. }
  106. $callback = array_pop(explode('.', $event->name()));
  107. }
  108. $options = array_merge(
  109. array(
  110. 'break' => false,
  111. 'breakOn' => false,
  112. 'collectReturn' => false,
  113. 'modParams' => false
  114. ),
  115. $options
  116. );
  117. $collected = array();
  118. $list = array_keys($this->_enabled);
  119. if ($options['modParams'] !== false && !isset($params[$options['modParams']])) {
  120. throw new CakeException(__d('cake_dev', 'Cannot use modParams with indexes that do not exist.'));
  121. }
  122. foreach ($list as $name) {
  123. $result = call_user_func_array(array($this->_loaded[$name], $callback), compact('subject') + $params);
  124. if ($options['collectReturn'] === true) {
  125. $collected[] = $result;
  126. }
  127. if (
  128. $options['break'] && ($result === $options['breakOn'] ||
  129. (is_array($options['breakOn']) && in_array($result, $options['breakOn'], true)))
  130. ) {
  131. return $result;
  132. } elseif ($options['modParams'] !== false && !in_array($result, array(true, false, null), true)) {
  133. $params[$options['modParams']] = $result;
  134. }
  135. }
  136. if ($options['modParams'] !== false) {
  137. return $params[$options['modParams']];
  138. }
  139. return $options['collectReturn'] ? $collected : $result;
  140. }
  141. /**
  142. * Provide public read access to the loaded objects
  143. *
  144. * @param string $name Name of property to read
  145. * @return mixed
  146. */
  147. public function __get($name) {
  148. if (isset($this->_loaded[$name])) {
  149. return $this->_loaded[$name];
  150. }
  151. return null;
  152. }
  153. /**
  154. * Provide isset access to _loaded
  155. *
  156. * @param string $name Name of object being checked.
  157. * @return boolean
  158. */
  159. public function __isset($name) {
  160. return isset($this->_loaded[$name]);
  161. }
  162. /**
  163. * Enables callbacks on an object or array of objects
  164. *
  165. * @param string|array $name CamelCased name of the object(s) to enable (string or array)
  166. * @param boolean Prioritize enabled list after enabling object(s)
  167. * @return void
  168. */
  169. public function enable($name, $prioritize = true) {
  170. $enabled = false;
  171. foreach ((array)$name as $object) {
  172. if (isset($this->_loaded[$object]) && !isset($this->_enabled[$object])) {
  173. $priority = isset($this->_loaded[$object]->settings['priority']) ? $this->_loaded[$object]->settings['priority'] : $this->defaultPriority;
  174. $this->_enabled[$object] = array($priority);
  175. $enabled = true;
  176. }
  177. }
  178. if ($prioritize && $enabled) {
  179. $this->prioritize();
  180. }
  181. }
  182. /**
  183. * Prioritize list of enabled object
  184. *
  185. * @return array Prioritized list of object
  186. */
  187. public function prioritize() {
  188. $i = 1;
  189. foreach ($this->_enabled as $name => $priority) {
  190. $priority[1] = $i++;
  191. $this->_enabled[$name] = $priority;
  192. }
  193. asort($this->_enabled);
  194. return $this->_enabled;
  195. }
  196. /**
  197. * Set priority for an object or array of objects
  198. *
  199. * @param string|array $name CamelCased name of the object(s) to enable (string or array)
  200. * If string the second param $priority is used else it should be an associative array
  201. * with keys as object names and values as priorities to set.
  202. * @param int|null Integer priority to set or null for default
  203. * @return void
  204. */
  205. public function setPriority($name, $priority = null) {
  206. if (is_string($name)) {
  207. $name = array($name => $priority);
  208. }
  209. foreach ($name as $obj => $prio) {
  210. if (isset($this->_loaded[$obj])) {
  211. if (is_null($prio)) {
  212. $prio = $this->defaultPriority;
  213. }
  214. $this->_loaded[$obj]->settings['priority'] = $prio;
  215. if (isset($this->_enabled[$obj])) {
  216. $this->_enabled[$obj] = array($prio);
  217. }
  218. }
  219. }
  220. $this->prioritize();
  221. }
  222. /**
  223. * Disables callbacks on a object or array of objects. Public object methods are still
  224. * callable as normal.
  225. *
  226. * @param string|array $name CamelCased name of the objects(s) to disable (string or array)
  227. * @return void
  228. */
  229. public function disable($name) {
  230. foreach ((array)$name as $object) {
  231. unset($this->_enabled[$object]);
  232. }
  233. }
  234. /**
  235. * Gets the list of currently-enabled objects, or, the current status of a single objects
  236. *
  237. * @param string $name Optional. The name of the object to check the status of. If omitted,
  238. * returns an array of currently-enabled object
  239. * @return mixed If $name is specified, returns the boolean status of the corresponding object.
  240. * Otherwise, returns an array of all enabled objects.
  241. */
  242. public function enabled($name = null) {
  243. if (!empty($name)) {
  244. return isset($this->_enabled[$name]);
  245. }
  246. return array_keys($this->_enabled);
  247. }
  248. /**
  249. * Gets the list of attached behaviors, or, whether the given behavior is attached
  250. *
  251. * @param string $name Optional. The name of the behavior to check the status of. If omitted,
  252. * returns an array of currently-attached behaviors
  253. * @return mixed If $name is specified, returns the boolean status of the corresponding behavior.
  254. * Otherwise, returns an array of all attached behaviors.
  255. */
  256. public function attached($name = null) {
  257. if (!empty($name)) {
  258. return isset($this->_loaded[$name]);
  259. }
  260. return array_keys($this->_loaded);
  261. }
  262. /**
  263. * Name of the object to remove from the collection
  264. *
  265. * @param string $name Name of the object to delete.
  266. * @return void
  267. */
  268. public function unload($name) {
  269. list($plugin, $name) = pluginSplit($name);
  270. unset($this->_loaded[$name]);
  271. unset($this->_enabled[$name]);
  272. }
  273. /**
  274. * Adds or overwrites an instantiated object to the collection
  275. *
  276. * @param string $name Name of the object
  277. * @param Object $object The object to use
  278. * @return array Loaded objects
  279. */
  280. public function set($name = null, $object = null) {
  281. if (!empty($name) && !empty($object)) {
  282. list($plugin, $name) = pluginSplit($name);
  283. $this->_loaded[$name] = $object;
  284. }
  285. return $this->_loaded;
  286. }
  287. /**
  288. * Normalizes an object array, creates an array that makes lazy loading
  289. * easier
  290. *
  291. * @param array $objects Array of child objects to normalize.
  292. * @return array Array of normalized objects.
  293. */
  294. public static function normalizeObjectArray($objects) {
  295. $normal = array();
  296. foreach ($objects as $i => $objectName) {
  297. $options = array();
  298. if (!is_int($i)) {
  299. $options = (array)$objectName;
  300. $objectName = $i;
  301. }
  302. list($plugin, $name) = pluginSplit($objectName);
  303. $normal[$name] = array('class' => $objectName, 'settings' => $options);
  304. }
  305. return $normal;
  306. }
  307. }