ObjectCollection.php 10 KB

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