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
![]() |
|||
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 |