-
Notifications
You must be signed in to change notification settings - Fork 0
/
AbstractContainerMediator.php
382 lines (381 loc) · 13.9 KB
/
AbstractContainerMediator.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
<?php
declare(strict_types = 1);
/**
* Contains AbstractContainerMediator class.
*
* PHP version 7.0
*
* LICENSE:
* This file is part of Event Mediator - A general event mediator (dispatcher)
* which has minimal dependencies so it is easy to drop in and use.
* Copyright (C) 2015-2016 Michael Cummings
*
* This program is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License as published by the Free
* Software Foundation; version 2 of the License.
*
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
* FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
* details.
*
* You should have received a copy of the GNU General Public License along with
* this program; if not, you may write to
*
* Free Software Foundation, Inc.
* 59 Temple Place, Suite 330
* Boston, MA 02111-1307 USA
*
* or find a electronic copy at
* <http://spdx.org/licenses/GPL-2.0.html>.
*
* You should also be able to find a copy of this license in the included
* LICENSE file.
*
* @author Michael Cummings <mgcummings@yahoo.com>
* @copyright 2015-2016 Michael Cummings
* @license GPL-2.0
*/
namespace EventMediator;
/**
* Class AbstractContainerMediator
*/
abstract class AbstractContainerMediator extends Mediator implements ContainerMediatorInterface
{
/**
* Add a service as an event listener.
*
* @param string $eventName Name of the event the listener is being added for.
* @param array $listener Listener to be added. ['containerID', 'method']
* @param int|string $priority Priority level for the added listener.
*
* @return ContainerMediatorInterface Fluent interface.
* @throws \DomainException
* @throws \InvalidArgumentException
*/
public function addServiceListener(string $eventName, array $listener, $priority = 0): ContainerMediatorInterface
{
$this->checkEventName($eventName);
$this->checkAllowedServiceListener($listener);
$priority = $this->getActualPriority($eventName, $priority);
if (array_key_exists($eventName, $this->serviceListeners)
&& array_key_exists($priority, $this->serviceListeners[$eventName])
&& in_array($listener, $this->serviceListeners[$eventName][$priority], true)
) {
return $this;
}
$this->serviceListeners[$eventName][$priority][] = $listener;
return $this;
}
/**
* @param array $events
*
* @return ContainerMediatorInterface
* @throws \DomainException
* @throws \InvalidArgumentException
* @throws \LengthException
*/
public function addServiceListenersByEventList(array $events): ContainerMediatorInterface
{
$this->walkEventList($events, [$this, 'addServiceListener']);
return $this;
}
/**
* Add a service as a subscriber to event(s).
*
* @param ServiceSubscriberInterface $sub Service subscriber to be added.
*
* @return ContainerMediatorInterface Fluent interface.
* @throws \DomainException
* @throws \InvalidArgumentException
* @throws \LengthException
*/
public function addServiceSubscriber(ServiceSubscriberInterface $sub): ContainerMediatorInterface
{
return $this->addServiceListenersByEventList($sub->getServiceSubscribedEvents());
}
/**
* @param string $eventName
*
* @return array
* @throws \DomainException
* @throws \InvalidArgumentException
*/
public function getListeners(string $eventName = ''): array
{
$this->lazyLoadServices($eventName);
return parent::getListeners($eventName);
}
/** @noinspection GenericObjectTypeUsageInspection */
/**
* This method is used any time the mediator need to get the actual instance
* of the class for an event.
*
* Normal will only be called during actual trigger of an event since lazy
* loading is used.
*
* @param string $serviceName
*
* @return object
*/
abstract public function getServiceByName(string $serviceName);
/**
* Get a list of service listeners for an event.
*
* Note that if event name is empty all listeners will be returned. Any event subscribers are also included in the
* list.
*
* @param string $eventName Name of the event the list of service listeners is needed for.
*
* @return array List of event service listeners or empty array if event is unknown or has no listeners or
* subscribers.
* @throws \InvalidArgumentException
*/
public function getServiceListeners(string $eventName = ''): array
{
$this->sortServiceListeners($eventName);
if ('' !== $eventName) {
return array_key_exists($eventName, $this->serviceListeners) ? $this->serviceListeners[$eventName] : [];
}
return $this->serviceListeners;
}
/**
* Remove a service as an event listener.
*
* @param string $eventName Event name that listener is being removed from.
* @param array $listener Service listener to be removed.
* @param int|string $priority Priority level for the to be removed listener.
*
* @return ContainerMediatorInterface Fluent interface.
* @throws \DomainException
* @throws \InvalidArgumentException
*/
public function removeServiceListener(string $eventName, array $listener, $priority = 0): ContainerMediatorInterface
{
$this->checkEventName($eventName);
if (!array_key_exists($eventName, $this->serviceListeners)) {
return $this;
}
$this->checkAllowedServiceListener($listener);
if (in_array($eventName, $this->loadedServices, true)) {
$this->removeListener($eventName, [$this->getServiceByName($listener[0]), $listener[1]], $priority);
}
/**
* @var array $priorities
* @var int|string $atPriority
* @var array $listeners
*/
if ('last' !== $priority) {
$priorities = $this->serviceListeners[$eventName];
} else {
$priorities = array_reverse($this->serviceListeners[$eventName], true);
$priority = 'first';
}
$isIntPriority = is_int($priority);
foreach ($priorities as $atPriority => $listeners) {
if ($isIntPriority && $priority !== $atPriority) {
continue;
}
$key = array_search($listener, $listeners, true);
if (false !== $key) {
$this->bubbleUpUnsetServiceListener($eventName, $atPriority, $key);
if ('first' === $priority) {
break;
}
}
}
return $this;
}
/**
* @param array $events
*
* @return ContainerMediatorInterface
* @throws \DomainException
* @throws \InvalidArgumentException
* @throws \LengthException
*/
public function removeServiceListenersByEventList(array $events): ContainerMediatorInterface
{
$this->walkEventList($events, [$this, 'removeServiceListener']);
return $this;
}
/**
* Remove a service subscriber from event(s).
*
* @param ServiceSubscriberInterface $sub Subscriber to be removed.
*
* @return ContainerMediatorInterface Fluent interface.
* @throws \DomainException
* @throws \InvalidArgumentException
* @throws \LengthException
*/
public function removeServiceSubscriber(ServiceSubscriberInterface $sub): ContainerMediatorInterface
{
return $this->removeServiceListenersByEventList($sub->getServiceSubscribedEvents());
}
/**
* This is used to bring in the service container that will be used.
*
* Though not required it would be considered best practice for this method
* to create a new instance of the container when given null. Another good
* practice is to call this method from the class constructor to allow
* easier testing. For examples of both have a look at
* PimpleContainerMediator.
*
* @see PimpleContainerMediator Container mediator implemented using Pimple.
*
* @param mixed $value The service container to be used.
*
* @return ContainerMediatorInterface Fluent interface.
*/
abstract public function setServiceContainer($value = null): ContainerMediatorInterface;
/**
* @param string $eventName
* @param string|int $priority
*
* @return int
*/
protected function getActualPriority(string $eventName, $priority): int
{
if (is_int($priority)) {
return $priority;
}
$listenerM = parent::getActualPriority($eventName, $priority);
if ($priority === 'first') {
$serviceM = array_key_exists($eventName, $this->serviceListeners)
? max(array_keys($this->serviceListeners[$eventName])) + 1 : 1;
$priority = ($listenerM > $serviceM) ? $listenerM : $serviceM;
} elseif ($priority === 'last') {
$serviceM = array_key_exists($eventName, $this->serviceListeners)
? min(array_keys($this->serviceListeners[$eventName])) - 1 : -1;
$priority = ($listenerM < $serviceM) ? $listenerM : $serviceM;
}
return (int)$priority;
}
/**
* @param string $eventName
* @param int $priority
* @param int $key
*/
private function bubbleUpUnsetServiceListener(string $eventName, int $priority, int $key)
{
unset($this->serviceListeners[$eventName][$priority][$key]);
// Remove empty priorities.
if (0 === count($this->serviceListeners[$eventName][$priority])) {
unset($this->serviceListeners[$eventName][$priority]);
}
// Remove empty events.
if (0 === count($this->serviceListeners[$eventName])) {
unset($this->serviceListeners[$eventName]);
$key = array_search($eventName, $this->loadedServices, true);
unset($this->loadedServices[$key]);
}
}
/**
* @param $listener
*
* @throws \InvalidArgumentException
*/
private function checkAllowedServiceListener($listener)
{
if (is_array($listener) && 2 === count($listener)) {
list($containerID, $method) = $listener;
if (!is_string($method)) {
$mess = sprintf('Service listener method name MUST be a string, but was given %s', gettype($method));
throw new \InvalidArgumentException($mess);
}
if (!is_string($containerID)) {
$mess = sprintf('Service listener container ID MUST be a string, but was given %s',
gettype($containerID));
throw new \InvalidArgumentException($mess);
}
if (!ctype_print($method) || false === preg_match('%\w{1,}%', $method)) {
$mess = 'Service listener method name format is invalid, was given ' . $method;
throw new \InvalidArgumentException($mess);
}
// Also catches empty string.
if (!ctype_print($containerID)) {
$mess = 'Using any non-printable characters in the container ID is NOT allowed';
throw new \InvalidArgumentException($mess);
}
return;
}
$mess = 'Service listener form MUST be ["containerID", "methodName"]';
throw new \InvalidArgumentException($mess);
}
/**
* @param string $eventName
*
* @return ContainerMediatorInterface Fluent interface
* @throws \DomainException
* @throws \InvalidArgumentException
*/
private function lazyLoadServices(string $eventName = ''): ContainerMediatorInterface
{
if (0 === count($this->serviceListeners)) {
return $this;
}
if ('' !== $eventName) {
if (!array_key_exists($eventName, $this->serviceListeners)) {
return $this;
}
$eventNames = [$eventName];
} else {
$eventNames = array_keys($this->serviceListeners);
}
foreach ($eventNames as $event) {
if (!in_array($event, $this->loadedServices, true)) {
$this->loadedServices[] = $event;
}
/**
* @var array $priorities
* @var int $priority
* @var array $listeners
* @var array $listener
*/
$priorities = $this->serviceListeners[$event];
foreach ($priorities as $priority => $listeners) {
foreach ($listeners as $listener) {
$this->addListener($event, [$this->getServiceByName($listener[0]), $listener[1]], $priority);
}
}
}
return $this;
}
/**
* @param string $eventName
*
* @return ContainerMediatorInterface Fluent Interface
* @throws \InvalidArgumentException
*/
private function sortServiceListeners(string $eventName): ContainerMediatorInterface
{
if (0 === count($this->serviceListeners)) {
return $this;
}
if ('' !== $eventName) {
if (!array_key_exists($eventName, $this->serviceListeners)) {
return $this;
}
$eventNames = [$eventName];
} else {
ksort($this->serviceListeners);
$eventNames = array_keys(parent::getListeners(''));
}
foreach ($eventNames as $anEvent) {
krsort($this->serviceListeners[$anEvent], SORT_NUMERIC);
}
return $this;
}
/**
* List of already loaded services.
*
* @var string[] $loadedServices
*/
private $loadedServices = [];
/**
* @var array $serviceListeners Holds the list of service listeners that will be lazy loaded when events are
* triggered.
*/
private $serviceListeners = [];
}