Completed
Push — master ( 1ec4da...059c5a )
by Nicolas
24s
created

EventBus::send()   A

Complexity

Conditions 3
Paths 3

Size

Total Lines 15

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 10
CRAP Score 3

Importance

Changes 0
Metric Value
dl 0
loc 15
c 0
b 0
f 0
ccs 10
cts 10
cp 1
rs 9.7666
cc 3
nc 3
nop 1
crap 3
1
<?php
2
declare(strict_types=1);
3
4
namespace BSP\EventBus;
5
6
use BSP\DrWatson\ExceptionType;
7
8
/**
9
 * EventBus execute listeners listening to a particular event.
10
 *
11
 * In order to do so, EventBus::listeners needs to be filled with listeners in its constructor:
12
 * Please pay attention that there can be multiple listeners to an Event.
13
 *
14
 * Exemple:
15
 * public function __constructor(DoSomethingOnDomainEvent $doSomethingOnDomainEvent) {
16
 *     $this->listeners[DomainEvent::class][] = $DoSomethingOnDomainEvent;
17
 * }
18
 */
19
abstract class EventBus
20
{
21
    /** @var EventListener[][] */
22
    protected $listeners = [];
23
24
    /**
25
     * @throws EventBusException
26
     */
27 2
    public function send(Event $event): void
28
    {
29 2
        if (!isset($this->listeners[get_class($event)])) {
30 1
            throw EventBusException::report(
31 1
                ExceptionType::DOMAIN(),
32 1
                'domain.eventbus.event.unkown',
33 1
                sprintf('"%s" listeners.', static::class),
34 1
                sprintf('You may have forgot to add the "%s" event to the "%s" eventBus.', get_class($event), static::class)
35
            );
36
        }
37
38 1
        foreach ($this->listeners[get_class($event)] as $listener) {
39 1
            $listener->listen($event);
40
        }
41 1
    }
42
}
43