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