(REF) CiviEventDispatcher - Move service-listener stub to standalone class
[civicrm-core.git] / Civi / Core / CiviEventDispatcher.php
1 <?php
2
3 namespace Civi\Core;
4
5 use Symfony\Component\EventDispatcher\EventDispatcher;
6 use Symfony\Component\EventDispatcher\Event;
7
8 /**
9 * Class CiviEventDispatcher
10 * @package Civi\Core
11 *
12 * The CiviEventDispatcher is a Symfony dispatcher. Additionally, if an event
13 * follows the naming convention of "hook_*", then it will also be dispatched
14 * through CRM_Utils_Hook::invoke().
15 *
16 * @see \CRM_Utils_Hook
17 */
18 class CiviEventDispatcher extends EventDispatcher {
19
20 const DEFAULT_HOOK_PRIORITY = -100;
21
22 /**
23 * Track the list of hook-events for which we have autoregistered
24 * the hook adapter.
25 *
26 * @var array
27 * Array(string $eventName => trueish).
28 */
29 private $autoListeners = [];
30
31 /**
32 * A list of dispatch-policies (based on an exact-match to the event name).
33 *
34 * Note: $dispatchPolicyExact and $dispatchPolicyRegex should coexist; e.g.
35 * if one is NULL, then both are NULL. If one is an array, then both are arrays.
36 *
37 * @var array|null
38 * Array(string $eventName => string $action)
39 */
40 private $dispatchPolicyExact = NULL;
41
42 /**
43 * A list of dispatch-policies (based on an regex-match to the event name).
44 *
45 * Note: $dispatchPolicyExact and $dispatchPolicyRegex should coexist; e.g.
46 * if one is NULL, then both are NULL. If one is an array, then both are arrays.
47 *
48 * @var array|null
49 * Array(string $eventRegex => string $action)
50 */
51 private $dispatchPolicyRegex = NULL;
52
53 /**
54 * Determine whether $eventName should delegate to the CMS hook system.
55 *
56 * @param string $eventName
57 * Ex: 'civi.token.eval', 'hook_civicrm_post`.
58 * @return bool
59 */
60 protected function isHookEvent($eventName) {
61 return (substr($eventName, 0, 5) === 'hook_') && (strpos($eventName, '::') === FALSE);
62 }
63
64 /**
65 * Adds a service as event listener.
66 *
67 * This provides partial backwards compatibility with ContainerAwareEventDispatcher.
68 *
69 * @param string $eventName Event for which the listener is added
70 * @param array $callback The service ID of the listener service & the method
71 * name that has to be called
72 * @param int $priority The higher this value, the earlier an event listener
73 * will be triggered in the chain.
74 * Defaults to 0.
75 *
76 * @throws \InvalidArgumentException
77 */
78 public function addListenerService($eventName, $callback, $priority = 0) {
79 if (!\is_array($callback) || 2 !== \count($callback)) {
80 throw new \InvalidArgumentException('Expected an array("service", "method") argument');
81 }
82
83 $this->addListener($eventName, new \Civi\Core\Event\ServiceListener($callback), $priority);
84 }
85
86 /**
87 * @inheritDoc
88 */
89 public function dispatch($eventName, Event $event = NULL) {
90 // Dispatch policies add systemic overhead and (normally) should not be evaluated. JNZ.
91 if ($this->dispatchPolicyRegex !== NULL) {
92 switch ($mode = $this->checkDispatchPolicy($eventName)) {
93 case 'run':
94 // Continue on the normal execution.
95 break;
96
97 case 'drop':
98 // Quietly ignore the event.
99 return $event;
100
101 case 'warn':
102 // Run the event, but complain about it.
103 error_log("Unexpectedly dispatching event \"$eventName\".");
104 break;
105
106 case 'warn-drop':
107 // Ignore the event, but complaint about it.
108 error_log("Unexpectedly dispatching event \"$eventName\".");
109 return $event;
110
111 case 'fail':
112 throw new \RuntimeException("The dispatch policy prohibits event \"$eventName\".");
113
114 case 'not-ready':
115 throw new \RuntimeException("CiviCRM has not bootstrapped sufficiently to fire event \"$eventName\".");
116
117 default:
118 throw new \RuntimeException("The dispatch policy for \"$eventName\" is unrecognized ($mode).");
119
120 }
121 }
122 $this->bindPatterns($eventName);
123 return parent::dispatch($eventName, $event);
124 }
125
126 /**
127 * @inheritDoc
128 */
129 public function getListeners($eventName = NULL) {
130 $this->bindPatterns($eventName);
131 return parent::getListeners($eventName);
132 }
133
134 /**
135 * @inheritDoc
136 */
137 public function hasListeners($eventName = NULL) {
138 // All hook_* events have default listeners, so hasListeners(NULL) is a truism.
139 return ($eventName === NULL || $this->isHookEvent($eventName))
140 ? TRUE : parent::hasListeners($eventName);
141 }
142
143 /**
144 * Invoke hooks using an event object.
145 *
146 * @param \Civi\Core\Event\GenericHookEvent $event
147 * @param string $eventName
148 * Ex: 'hook_civicrm_dashboard'.
149 */
150 public static function delegateToUF($event, $eventName) {
151 $hookName = substr($eventName, 5);
152 $hooks = \CRM_Utils_Hook::singleton();
153 $params = $event->getHookValues();
154 $count = count($params);
155
156 switch ($count) {
157 case 0:
158 $fResult = $hooks->invokeViaUF($count, \CRM_Utils_Hook::$_nullObject, \CRM_Utils_Hook::$_nullObject, \CRM_Utils_Hook::$_nullObject, \CRM_Utils_Hook::$_nullObject, \CRM_Utils_Hook::$_nullObject, \CRM_Utils_Hook::$_nullObject, $hookName);
159 break;
160
161 case 1:
162 $fResult = $hooks->invokeViaUF($count, $params[0], \CRM_Utils_Hook::$_nullObject, \CRM_Utils_Hook::$_nullObject, \CRM_Utils_Hook::$_nullObject, \CRM_Utils_Hook::$_nullObject, \CRM_Utils_Hook::$_nullObject, $hookName);
163 break;
164
165 case 2:
166 $fResult = $hooks->invokeViaUF($count, $params[0], $params[1], \CRM_Utils_Hook::$_nullObject, \CRM_Utils_Hook::$_nullObject, \CRM_Utils_Hook::$_nullObject, \CRM_Utils_Hook::$_nullObject, $hookName);
167 break;
168
169 case 3:
170 $fResult = $hooks->invokeViaUF($count, $params[0], $params[1], $params[2], \CRM_Utils_Hook::$_nullObject, \CRM_Utils_Hook::$_nullObject, \CRM_Utils_Hook::$_nullObject, $hookName);
171 break;
172
173 case 4:
174 $fResult = $hooks->invokeViaUF($count, $params[0], $params[1], $params[2], $params[3], \CRM_Utils_Hook::$_nullObject, \CRM_Utils_Hook::$_nullObject, $hookName);
175 break;
176
177 case 5:
178 $fResult = $hooks->invokeViaUF($count, $params[0], $params[1], $params[2], $params[3], $params[4], \CRM_Utils_Hook::$_nullObject, $hookName);
179 break;
180
181 case 6:
182 $fResult = $hooks->invokeViaUF($count, $params[0], $params[1], $params[2], $params[3], $params[4], $params[5], $hookName);
183 break;
184
185 default:
186 throw new \RuntimeException("hook_{$hookName} cannot support more than 6 parameters");
187 }
188
189 $event->addReturnValues($fResult);
190 }
191
192 /**
193 * Attach any pattern-based listeners which may be interested in $eventName.
194 *
195 * @param string $eventName
196 * Ex: 'civi.api.resolve' or 'hook_civicrm_dashboard'.
197 */
198 protected function bindPatterns($eventName) {
199 if ($eventName !== NULL && !isset($this->autoListeners[$eventName])) {
200 $this->autoListeners[$eventName] = 1;
201 if ($this->isHookEvent($eventName)) {
202 // WISHLIST: For native extensions (and possibly D6/D7/D8/BD), enumerate
203 // the listeners and list them one-by-one. This would make it easier to
204 // inspect via "cv debug:event-dispatcher".
205 $this->addListener($eventName, [
206 '\Civi\Core\CiviEventDispatcher',
207 'delegateToUF',
208 ], self::DEFAULT_HOOK_PRIORITY);
209 }
210 }
211 }
212
213 /**
214 * Set the dispatch policy. This allows you to filter certain events.
215 * This can be useful during upgrades or debugging.
216 *
217 * Enforcement will add systemic overhead, so this should normally be NULL.
218 *
219 * @param array|null $dispatchPolicy
220 * Each key is either the string-literal name of an event, or a regex delimited by '/'.
221 * Each value is one of: 'run', 'drop', 'warn', 'fail'.
222 * Exact name matches take precedence over regexes. Regexes are evaluated in order.
223 *
224 * Ex: ['hook_civicrm_pre' => 'fail']
225 * Ex: ['/^hook_/' => 'warn']
226 *
227 * @return static
228 */
229 public function setDispatchPolicy($dispatchPolicy) {
230 if (is_array($dispatchPolicy)) {
231 // Split $dispatchPolicy in two (exact rules vs regex rules).
232 $this->dispatchPolicyExact = [];
233 $this->dispatchPolicyRegex = [];
234 foreach ($dispatchPolicy as $pattern => $action) {
235 if ($pattern[0] === '/') {
236 $this->dispatchPolicyRegex[$pattern] = $action;
237 }
238 else {
239 $this->dispatchPolicyExact[$pattern] = $action;
240 }
241 }
242 }
243 else {
244 $this->dispatchPolicyExact = NULL;
245 $this->dispatchPolicyRegex = NULL;
246 }
247
248 return $this;
249 }
250
251 // /**
252 // * @return array|NULL
253 // */
254 // public function getDispatchPolicy() {
255 // return $this->dispatchPolicyRegex === NULL ? NULL : array_merge($this->dispatchPolicyExact, $this->dispatchPolicyRegex);
256 // }
257
258 /**
259 * Determine whether the dispatch policy applies to a given event.
260 *
261 * @param string $eventName
262 * Ex: 'civi.api.resolve' or 'hook_civicrm_dashboard'.
263 * @return string
264 * Ex: 'run', 'drop', 'fail'
265 */
266 protected function checkDispatchPolicy($eventName) {
267 if (isset($this->dispatchPolicyExact[$eventName])) {
268 return $this->dispatchPolicyExact[$eventName];
269 }
270 foreach ($this->dispatchPolicyRegex as $eventPat => $action) {
271 if ($eventPat[0] === '/' && preg_match($eventPat, $eventName)) {
272 return $action;
273 }
274 }
275 return 'fail';
276 }
277
278 }