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