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: * @package Cake.Event
13: * @since CakePHP(tm) v 2.1
14: * @license http://www.opensource.org/licenses/mit-license.php MIT License
15: */
16:
17: App::uses('CakeEventListener', 'Event');
18:
19: /**
20: * The event manager is responsible for keeping track of event listeners, passing the correct
21: * data to them, and firing them in the correct order, when associated events are triggered. You
22: * can create multiple instances of this object to manage local events or keep a single instance
23: * and pass it around to manage all events in your app.
24: *
25: * @package Cake.Event
26: */
27: class CakeEventManager {
28:
29: /**
30: * The default priority queue value for new, attached listeners
31: *
32: * @var int
33: */
34: public static $defaultPriority = 10;
35:
36: /**
37: * The globally available instance, used for dispatching events attached from any scope
38: *
39: * @var CakeEventManager
40: */
41: protected static $_generalManager = null;
42:
43: /**
44: * List of listener callbacks associated to
45: *
46: * @var object
47: */
48: protected $_listeners = array();
49:
50: /**
51: * Internal flag to distinguish a common manager from the singleton
52: *
53: * @var bool
54: */
55: protected $_isGlobal = false;
56:
57: /**
58: * Returns the globally available instance of a CakeEventManager
59: * this is used for dispatching events attached from outside the scope
60: * other managers were created. Usually for creating hook systems or inter-class
61: * communication
62: *
63: * If called with the first parameter, it will be set as the globally available instance
64: *
65: * @param CakeEventManager $manager Optional event manager instance.
66: * @return CakeEventManager the global event manager
67: */
68: public static function instance($manager = null) {
69: if ($manager instanceof CakeEventManager) {
70: self::$_generalManager = $manager;
71: }
72: if (empty(self::$_generalManager)) {
73: self::$_generalManager = new CakeEventManager();
74: }
75:
76: self::$_generalManager->_isGlobal = true;
77: return self::$_generalManager;
78: }
79:
80: /**
81: * Adds a new listener to an event. Listeners
82: *
83: * @param callback|CakeEventListener $callable PHP valid callback type or instance of CakeEventListener to be called
84: * when the event named with $eventKey is triggered. If a CakeEventListener instance is passed, then the `implementedEvents`
85: * method will be called on the object to register the declared events individually as methods to be managed by this class.
86: * It is possible to define multiple event handlers per event name.
87: *
88: * @param string $eventKey The event unique identifier name with which the callback will be associated. If $callable
89: * is an instance of CakeEventListener this argument will be ignored
90: *
91: * @param array $options used to set the `priority` and `passParams` flags to the listener.
92: * Priorities are handled like queues, and multiple attachments added to the same priority queue will be treated in
93: * the order of insertion. `passParams` means that the event data property will be converted to function arguments
94: * when the listener is called. If $called is an instance of CakeEventListener, this parameter will be ignored
95: *
96: * @return void
97: * @throws InvalidArgumentException When event key is missing or callable is not an
98: * instance of CakeEventListener.
99: */
100: public function attach($callable, $eventKey = null, $options = array()) {
101: if (!$eventKey && !($callable instanceof CakeEventListener)) {
102: throw new InvalidArgumentException(__d('cake_dev', 'The eventKey variable is required'));
103: }
104: if ($callable instanceof CakeEventListener) {
105: $this->_attachSubscriber($callable);
106: return;
107: }
108: $options = $options + array('priority' => self::$defaultPriority, 'passParams' => false);
109: $this->_listeners[$eventKey][$options['priority']][] = array(
110: 'callable' => $callable,
111: 'passParams' => $options['passParams'],
112: );
113: }
114:
115: /**
116: * Auxiliary function to attach all implemented callbacks of a CakeEventListener class instance
117: * as individual methods on this manager
118: *
119: * @param CakeEventListener $subscriber Event listener.
120: * @return void
121: */
122: protected function _attachSubscriber(CakeEventListener $subscriber) {
123: foreach ((array)$subscriber->implementedEvents() as $eventKey => $function) {
124: $options = array();
125: $method = $function;
126: if (is_array($function) && isset($function['callable'])) {
127: list($method, $options) = $this->_extractCallable($function, $subscriber);
128: } elseif (is_array($function) && is_numeric(key($function))) {
129: foreach ($function as $f) {
130: list($method, $options) = $this->_extractCallable($f, $subscriber);
131: $this->attach($method, $eventKey, $options);
132: }
133: continue;
134: }
135: if (is_string($method)) {
136: $method = array($subscriber, $function);
137: }
138: $this->attach($method, $eventKey, $options);
139: }
140: }
141:
142: /**
143: * Auxiliary function to extract and return a PHP callback type out of the callable definition
144: * from the return value of the `implementedEvents` method on a CakeEventListener
145: *
146: * @param array $function the array taken from a handler definition for an event
147: * @param CakeEventListener $object The handler object
148: * @return callback
149: */
150: protected function _extractCallable($function, $object) {
151: $method = $function['callable'];
152: $options = $function;
153: unset($options['callable']);
154: if (is_string($method)) {
155: $method = array($object, $method);
156: }
157: return array($method, $options);
158: }
159:
160: /**
161: * Removes a listener from the active listeners.
162: *
163: * @param callback|CakeEventListener $callable any valid PHP callback type or an instance of CakeEventListener
164: * @param string $eventKey The event unique identifier name with which the callback has been associated
165: * @return void
166: */
167: public function detach($callable, $eventKey = null) {
168: if ($callable instanceof CakeEventListener) {
169: return $this->_detachSubscriber($callable, $eventKey);
170: }
171: if (empty($eventKey)) {
172: foreach (array_keys($this->_listeners) as $eventKey) {
173: $this->detach($callable, $eventKey);
174: }
175: return;
176: }
177: if (empty($this->_listeners[$eventKey])) {
178: return;
179: }
180: foreach ($this->_listeners[$eventKey] as $priority => $callables) {
181: foreach ($callables as $k => $callback) {
182: if ($callback['callable'] === $callable) {
183: unset($this->_listeners[$eventKey][$priority][$k]);
184: break;
185: }
186: }
187: }
188: }
189:
190: /**
191: * Auxiliary function to help detach all listeners provided by an object implementing CakeEventListener
192: *
193: * @param CakeEventListener $subscriber the subscriber to be detached
194: * @param string $eventKey optional event key name to unsubscribe the listener from
195: * @return void
196: */
197: protected function _detachSubscriber(CakeEventListener $subscriber, $eventKey = null) {
198: $events = (array)$subscriber->implementedEvents();
199: if (!empty($eventKey) && empty($events[$eventKey])) {
200: return;
201: } elseif (!empty($eventKey)) {
202: $events = array($eventKey => $events[$eventKey]);
203: }
204: foreach ($events as $key => $function) {
205: if (is_array($function)) {
206: if (is_numeric(key($function))) {
207: foreach ($function as $handler) {
208: $handler = isset($handler['callable']) ? $handler['callable'] : $handler;
209: $this->detach(array($subscriber, $handler), $key);
210: }
211: continue;
212: }
213: $function = $function['callable'];
214: }
215: $this->detach(array($subscriber, $function), $key);
216: }
217: }
218:
219: /**
220: * Dispatches a new event to all configured listeners
221: *
222: * @param string|CakeEvent $event the event key name or instance of CakeEvent
223: * @return CakeEvent
224: * @triggers $event
225: */
226: public function dispatch($event) {
227: if (is_string($event)) {
228: $event = new CakeEvent($event);
229: }
230:
231: $listeners = $this->listeners($event->name());
232: if (empty($listeners)) {
233: return $event;
234: }
235:
236: foreach ($listeners as $listener) {
237: if ($event->isStopped()) {
238: break;
239: }
240: if ($listener['passParams'] === true) {
241: $result = call_user_func_array($listener['callable'], $event->data);
242: } else {
243: $result = call_user_func($listener['callable'], $event);
244: }
245: if ($result === false) {
246: $event->stopPropagation();
247: }
248: if ($result !== null) {
249: $event->result = $result;
250: }
251: }
252: return $event;
253: }
254:
255: /**
256: * Returns a list of all listeners for an eventKey in the order they should be called
257: *
258: * @param string $eventKey Event key.
259: * @return array
260: */
261: public function listeners($eventKey) {
262: $localListeners = array();
263: $priorities = array();
264: if (!$this->_isGlobal) {
265: $localListeners = $this->prioritisedListeners($eventKey);
266: $localListeners = empty($localListeners) ? array() : $localListeners;
267: }
268: $globalListeners = self::instance()->prioritisedListeners($eventKey);
269: $globalListeners = empty($globalListeners) ? array() : $globalListeners;
270:
271: $priorities = array_merge(array_keys($globalListeners), array_keys($localListeners));
272: $priorities = array_unique($priorities);
273: asort($priorities);
274:
275: $result = array();
276: foreach ($priorities as $priority) {
277: if (isset($globalListeners[$priority])) {
278: $result = array_merge($result, $globalListeners[$priority]);
279: }
280: if (isset($localListeners[$priority])) {
281: $result = array_merge($result, $localListeners[$priority]);
282: }
283: }
284: return $result;
285: }
286:
287: /**
288: * Returns the listeners for the specified event key indexed by priority
289: *
290: * @param string $eventKey Event key.
291: * @return array
292: */
293: public function prioritisedListeners($eventKey) {
294: if (empty($this->_listeners[$eventKey])) {
295: return array();
296: }
297: return $this->_listeners[$eventKey];
298: }
299: }
300: