Dispatcher::dispatch()   A
last analyzed

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
cc 2
eloc 2
c 1
b 0
f 0
nc 2
nop 1
dl 0
loc 4
rs 10
1
<?php declare(strict_types=1);
2
3
namespace Stratadox\CardGame\Infrastructure\DomainEvents;
4
5
use function get_class;
6
use Stratadox\CardGame\DomainEvent;
7
use Stratadox\CardGame\EventHandler\EventHandler;
8
9
class Dispatcher
10
{
11
    /** @var EventHandler[][] */
12
    private $handlers;
13
14
    public function __construct(EventHandler ...$handlers)
15
    {
16
        foreach ($handlers as $eventHandler) {
17
            foreach ($eventHandler->events() as $event) {
18
                $this->registerHandler($event, $eventHandler);
19
            }
20
        }
21
    }
22
23
    public function dispatch(DomainEvent $event): void
24
    {
25
        foreach ($this->handlers[get_class($event)] ?? [] as $handler) {
26
            $handler->handle($event);
27
        }
28
    }
29
30
    public function registerHandler(string $event, EventHandler $handler): void
31
    {
32
        $this->handlers[$event][] = $handler;
33
    }
34
}
35