1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
declare(strict_types=1); |
4
|
|
|
|
5
|
|
|
namespace Arp\LaminasEvent\Factory\Listener; |
6
|
|
|
|
7
|
|
|
use Arp\EventDispatcher\Listener\AddListenerAwareInterface; |
8
|
|
|
use Arp\EventDispatcher\Listener\AggregateListenerInterface; |
9
|
|
|
use Arp\EventDispatcher\Listener\Exception\EventListenerException; |
10
|
|
|
use Laminas\ServiceManager\Exception\ServiceNotCreatedException; |
11
|
|
|
use Psr\Container\ContainerExceptionInterface; |
12
|
|
|
use Psr\Container\ContainerInterface; |
13
|
|
|
use Psr\Container\NotFoundExceptionInterface; |
14
|
|
|
|
15
|
|
|
trait ListenerRegistrationTrait |
16
|
|
|
{ |
17
|
|
|
/** |
18
|
|
|
* @param array<mixed> $configs |
19
|
|
|
* |
20
|
|
|
* @throws ServiceNotCreatedException |
21
|
|
|
* @throws ContainerExceptionInterface |
22
|
|
|
* @throws NotFoundExceptionInterface |
23
|
|
|
*/ |
24
|
|
|
public function registerEventListeners( |
25
|
|
|
ContainerInterface $container, |
26
|
|
|
AddListenerAwareInterface $collection, |
27
|
|
|
array $configs, |
28
|
|
|
string $serviceName |
29
|
|
|
): void { |
30
|
|
|
foreach ($configs as $eventName => $listeners) { |
31
|
|
|
if (is_string($listeners) && $container->has($listeners)) { |
32
|
|
|
$listeners = $container->get($listeners); |
33
|
|
|
} |
34
|
|
|
|
35
|
|
|
if ($listeners instanceof AggregateListenerInterface) { |
36
|
|
|
$listeners->addListeners($collection); |
37
|
|
|
continue; |
38
|
|
|
} |
39
|
|
|
|
40
|
|
|
if (!is_iterable($listeners)) { |
41
|
|
|
continue; |
42
|
|
|
} |
43
|
|
|
|
44
|
|
|
foreach ($listeners as $listener) { |
45
|
|
|
$priority = 1; |
46
|
|
|
|
47
|
|
|
if (is_array($listener)) { |
48
|
|
|
$priority = isset($listener['priority']) ? (int)$listener['priority'] : $priority; |
49
|
|
|
$listener = $listener['listener'] ?? null; |
50
|
|
|
} |
51
|
|
|
|
52
|
|
|
if (is_string($listener) && $container->has($listener)) { |
53
|
|
|
$listener = $container->get($listener); |
54
|
|
|
} |
55
|
|
|
|
56
|
|
|
if (null === $listener || !is_callable($listener)) { |
57
|
|
|
throw new ServiceNotCreatedException( |
58
|
|
|
sprintf( |
59
|
|
|
'Event listeners must be of type \'callable\'; ' |
60
|
|
|
. '\'%s\' provided when registering event \'%s::%s\'', |
61
|
|
|
is_object($listener) ? get_class($listener) : gettype($listener), |
62
|
|
|
$serviceName, |
63
|
|
|
$eventName |
64
|
|
|
) |
65
|
|
|
); |
66
|
|
|
} |
67
|
|
|
|
68
|
|
|
try { |
69
|
|
|
$collection->addListenerForEvent($eventName, $listener, $priority); |
70
|
|
|
} catch (EventListenerException $e) { |
71
|
|
|
throw new ServiceNotCreatedException( |
72
|
|
|
sprintf( |
73
|
|
|
'Failed to add new event listener for event \'%s::%s\': %s', |
74
|
|
|
$serviceName, |
75
|
|
|
$eventName, |
76
|
|
|
$e->getMessage() |
77
|
|
|
), |
78
|
|
|
$e->getCode(), |
79
|
|
|
$e |
80
|
|
|
); |
81
|
|
|
} |
82
|
|
|
} |
83
|
|
|
} |
84
|
|
|
} |
85
|
|
|
} |
86
|
|
|
|