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