1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
declare(strict_types=1); |
4
|
|
|
|
5
|
|
|
namespace Churn\Event; |
6
|
|
|
|
7
|
|
|
use Churn\Event\Channel\AfterAnalysisChannel; |
8
|
|
|
use Churn\Event\Channel\AfterFileAnalysisChannel; |
9
|
|
|
use Churn\Event\Channel\BeforeAnalysisChannel; |
10
|
|
|
|
11
|
|
|
/** |
12
|
|
|
* @internal |
13
|
|
|
*/ |
14
|
|
|
final class BrokerImpl implements Broker |
15
|
|
|
{ |
16
|
|
|
/** |
17
|
|
|
* @var array<string, array<callable>> |
18
|
|
|
* @psalm-var array<class-string, array<callable>> |
19
|
|
|
*/ |
20
|
|
|
private $subscribers = []; |
21
|
|
|
|
22
|
|
|
/** |
23
|
|
|
* @var array<\Churn\Event\Channel> |
24
|
|
|
*/ |
25
|
|
|
private $channels; |
26
|
|
|
|
27
|
|
|
/** |
28
|
|
|
* Class constructor. |
29
|
|
|
*/ |
30
|
|
|
public function __construct() |
31
|
|
|
{ |
32
|
|
|
$this->channels = [ |
33
|
|
|
new AfterAnalysisChannel(), |
34
|
|
|
new AfterFileAnalysisChannel(), |
35
|
|
|
new BeforeAnalysisChannel(), |
36
|
|
|
]; |
37
|
|
|
} |
38
|
|
|
|
39
|
|
|
/** |
40
|
|
|
* @param object $subscriber A subscriber object. |
41
|
|
|
*/ |
42
|
|
|
#[\Override] |
43
|
|
|
public function subscribe($subscriber): void |
44
|
|
|
{ |
45
|
|
|
foreach ($this->channels as $channel) { |
46
|
|
|
if (!$channel->accepts($subscriber)) { |
47
|
|
|
continue; |
48
|
|
|
} |
49
|
|
|
|
50
|
|
|
$this->subscribers[$channel->getEventClassname()][] = $channel->buildEventHandler($subscriber); |
51
|
|
|
} |
52
|
|
|
} |
53
|
|
|
|
54
|
|
|
/** |
55
|
|
|
* @param Event $event The triggered event. |
56
|
|
|
*/ |
57
|
|
|
#[\Override] |
58
|
|
|
public function notify(Event $event): void |
59
|
|
|
{ |
60
|
|
|
foreach ($this->subscribers as $eventClass => $subscribers) { |
61
|
|
|
if (!$event instanceof $eventClass) { |
62
|
|
|
continue; |
63
|
|
|
} |
64
|
|
|
|
65
|
|
|
$this->notifyAll($event, $subscribers); |
66
|
|
|
} |
67
|
|
|
} |
68
|
|
|
|
69
|
|
|
/** |
70
|
|
|
* @param Event $event The triggered event. |
71
|
|
|
* @param array<callable> $subscribers The subscribers to notify. |
72
|
|
|
*/ |
73
|
|
|
private function notifyAll(Event $event, array $subscribers): void |
74
|
|
|
{ |
75
|
|
|
foreach ($subscribers as $subscriber) { |
76
|
|
|
$subscriber($event); |
77
|
|
|
} |
78
|
|
|
} |
79
|
|
|
} |
80
|
|
|
|