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