-
Notifications
You must be signed in to change notification settings - Fork 3
/
DispatcherConfigurator.php
69 lines (62 loc) · 2.42 KB
/
DispatcherConfigurator.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
<?php
/**
* @LICENSE_TEXT
*/
namespace EventBand\Bundle;
use EventBand\Adapter\Symfony\ListenerSubscription;
use EventBand\BandDispatcher;
use Symfony\Component\DependencyInjection\ContainerInterface;
use Symfony\Component\EventDispatcher\Event;
use Symfony\Component\EventDispatcher\EventDispatcherInterface;
/**
* Class DispatcherConfigurator
*
* @author Kirill chEbba Chebunin <iam@chebba.org>
*/
class DispatcherConfigurator
{
private $container;
private $eventDispatcher;
private $listeners = [];
public function __construct(ContainerInterface $container, EventDispatcherInterface $eventDispatcher)
{
$this->container = $container;
$this->eventDispatcher = $eventDispatcher;
}
public function addListenerService($id, $event, $method = null, $band = null, $priority = 0)
{
$this->listeners[(string) $band][$event][] = [$id, $method, $priority];
}
public function addSubscriberService($class, $serviceId, $band = null)
{
foreach ($class::getSubscribedEvents() as $eventName => $params) {
if (is_string($params)) {
$this->addListenerService($serviceId, $eventName, $params, $band, 0);
} elseif (is_string($params[0])) {
$this->addListenerService($serviceId, $eventName, $params[0], $band, isset($params[1]) ? $params[1] : 0);
} else {
foreach ($params as $listener) {
$this->addListenerService($serviceId, $eventName, $listener[0], $band, isset($listener[1]) ? $listener[1] : 0);
}
}
}
}
public function configure(BandDispatcher $dispatcher)
{
foreach ($this->listeners as $band => $events) {
foreach ($events as $event => $definitions) {
foreach ($definitions as $definition) {
$subscription = new ListenerSubscription(
$event,
function (Event $event, $eventName, EventDispatcherInterface $eventDispatcher) use ($definition) {
return call_user_func([$this->container->get($definition[0]), $definition[1]], $event, $eventName, $eventDispatcher);
},
$this->eventDispatcher,
$band
);
$dispatcher->subscribe($subscription, $definition[2]);
}
}
}
}
}