Passed
Push — master ( bcb124...6c908c )
by Fabien
02:02
created

BrokerImpl::notifyAll()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 4
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
eloc 2
c 1
b 0
f 0
dl 0
loc 4
rs 10
cc 2
nc 2
nop 2
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
    public function subscribe($subscriber): void
43
    {
44
        foreach ($this->channels as $channel) {
45
            if (!$channel->accepts($subscriber)) {
46
                continue;
47
            }
48
49
            $this->subscribers[$channel->getEventClassname()][] = $channel->buildEventHandler($subscriber);
50
        }
51
    }
52
53
    /**
54
     * @param Event $event The triggered event.
55
     */
56
    public function notify(Event $event): void
57
    {
58
        foreach ($this->subscribers as $eventClass => $subscribers) {
59
            if (!$event instanceof $eventClass) {
60
                continue;
61
            }
62
63
            $this->notifyAll($event, $subscribers);
64
        }
65
    }
66
67
    /**
68
     * @param Event $event The triggered event.
69
     * @param array<callable> $subscribers The subscribers to notify.
70
     */
71
    private function notifyAll(Event $event, array $subscribers): void
72
    {
73
        foreach ($subscribers as $subscriber) {
74
            $subscriber($event);
75
        }
76
    }
77
}
78