EventDispatcher   A
last analyzed

Complexity

Total Complexity 8

Size/Duplication

Total Lines 51
Duplicated Lines 0 %

Importance

Changes 0
Metric Value
eloc 16
dl 0
loc 51
rs 10
c 0
b 0
f 0
wmc 8

3 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 2 1
A addHandler() 0 7 2
A triggerEvent() 0 17 5
1
<?php
2
3
declare(strict_types=1);
4
5
namespace Tebe\Pvc\Event;
6
7
class EventDispatcher
8
{
9
    /**
10
     * @var EventHandler[]
11
     */
12
    private $handlers = [];
13
14
    /**
15
     * EventDispatcher constructor.
16
     */
17
    public function __construct()
18
    {
19
    }
20
21
    /**
22
     * @param string $eventName
23
     * @param EventHandler $handler
24
     * @return EventDispatcher
25
     */
26
    public function addHandler(string $eventName, EventHandler $handler): self
27
    {
28
        if (!isset($this->handlers[$eventName])) {
29
            $this->handlers[$eventName] = [];
30
        }
31
        $this->handlers[$eventName][] = $handler;
32
        return $this;
33
    }
34
35
    /**
36
     * @param string $event
37
     * @param object|null $context
38
     * @param array|null $info
39
     * @return Event
40
     */
41
    public function triggerEvent(string $event, object $context = null, array $info = null): Event
42
    {
43
        if (!$event instanceof Event) {
0 ignored issues
show
introduced by
$event is never a sub-type of Tebe\Pvc\Event\Event.
Loading history...
44
            $event = new Event($event, $context, $info);
45
        }
46
        $eventName = $event->getName();
47
        if (!isset($this->handlers[$eventName])) {
48
            return $event;
49
        }
50
        foreach ($this->handlers[$eventName] as $handler) {
51
            /* @var EventHandler $handler */
52
            $handler->handle($event);
53
            if ($event->isCancelled()) {
54
                break;
55
            }
56
        }
57
        return $event;
58
    }
59
}
60