Passed
Push — master ( 93e91b...83695f )
by Fabien
02:05
created

Broker::__construct()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 6
Code Lines 4

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 1
eloc 4
c 1
b 0
f 0
nc 1
nop 0
dl 0
loc 6
rs 10
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