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