1
|
|
|
<?php |
2
|
|
|
declare(strict_types = 1); |
3
|
|
|
|
4
|
|
|
namespace Innmind\EventBusBundle; |
5
|
|
|
|
6
|
|
|
use Innmind\EventBusBundle\Exception\InvalidArgumentException; |
7
|
|
|
use Innmind\EventBus\{ |
8
|
|
|
EventBusInterface, |
9
|
|
|
EventBus, |
10
|
|
|
Exception\InvalidArgumentException as InvalidEventException |
11
|
|
|
}; |
12
|
|
|
use Innmind\Immutable\{ |
13
|
|
|
Map, |
14
|
|
|
MapInterface, |
15
|
|
|
SetInterface, |
16
|
|
|
Set |
17
|
|
|
}; |
18
|
|
|
use Symfony\Component\DependencyInjection\ContainerInterface; |
19
|
|
|
|
20
|
|
|
final class ContainerAwareEventBus implements EventBusInterface |
21
|
|
|
{ |
22
|
|
|
private $container; |
23
|
|
|
private $listeners; |
24
|
|
|
private $bus; |
25
|
|
|
|
26
|
6 |
|
public function __construct( |
27
|
|
|
ContainerInterface $container, |
28
|
|
|
MapInterface $listeners |
29
|
|
|
) { |
30
|
|
|
if ( |
31
|
6 |
|
(string) $listeners->keyType() !== 'string' || |
32
|
6 |
|
(string) $listeners->valueType() !== SetInterface::class |
33
|
|
|
) { |
34
|
1 |
|
throw new InvalidArgumentException; |
35
|
|
|
} |
36
|
|
|
|
37
|
|
|
$listeners->foreach(function(string $class, SetInterface $listeners) { |
38
|
3 |
|
if ((string) $listeners->type() !== 'string') { |
39
|
|
|
throw new InvalidArgumentException; |
40
|
|
|
} |
41
|
5 |
|
}); |
42
|
|
|
|
43
|
5 |
|
$this->container = $container; |
44
|
5 |
|
$this->listeners = $listeners; |
45
|
5 |
|
} |
46
|
|
|
|
47
|
|
|
/** |
48
|
|
|
* {@inheritdoc} |
49
|
|
|
*/ |
50
|
3 |
|
public function dispatch($event): EventBusInterface |
51
|
|
|
{ |
52
|
3 |
|
if (!is_object($event)) { |
53
|
1 |
|
throw new InvalidEventException; |
54
|
|
|
} |
55
|
|
|
|
56
|
2 |
|
if (!$this->bus instanceof EventBusInterface) { |
57
|
2 |
|
$this->initialize(); |
58
|
|
|
} |
59
|
|
|
|
60
|
2 |
|
$this->bus->dispatch($event); |
61
|
|
|
|
62
|
2 |
|
return $this; |
63
|
|
|
} |
64
|
|
|
|
65
|
2 |
|
private function initialize() |
66
|
|
|
{ |
67
|
|
|
$listeners = $this |
68
|
2 |
|
->listeners |
69
|
2 |
|
->reduce( |
70
|
2 |
|
new Map('string', SetInterface::class), |
71
|
|
|
function(Map $carry, string $class, SetInterface $services): Map { |
72
|
2 |
|
return $carry->put( |
73
|
|
|
$class, |
74
|
2 |
|
$services->reduce( |
75
|
2 |
|
new Set('callable'), |
76
|
2 |
|
function(Set $carry, string $service): Set { |
77
|
2 |
|
return $carry->add( |
78
|
2 |
|
$this->container->get($service) |
79
|
|
|
); |
80
|
2 |
|
} |
81
|
|
|
) |
82
|
|
|
); |
83
|
2 |
|
} |
84
|
|
|
); |
85
|
2 |
|
$this->bus = new EventBus($listeners); |
86
|
2 |
|
} |
87
|
|
|
} |
88
|
|
|
|