EventHandlerCollection   A
last analyzed

Complexity

Total Complexity 6

Size/Duplication

Total Lines 40
Duplicated Lines 0 %

Importance

Changes 0
Metric Value
eloc 12
dl 0
loc 40
rs 10
c 0
b 0
f 0
wmc 6

3 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 3 1
A addHandler() 0 12 3
A invoke() 0 5 2
1
<?php
2
3
namespace Jerodev\PhpIrcClient\Helpers;
4
5
class EventHandlerCollection
6
{
7
    /** @var callable[][] */
8
    private $eventHandlers;
9
10
    public function __construct()
11
    {
12
        $this->eventHandlers = [];
13
    }
14
15
    /**
16
     *  Register an event handler.
17
     *
18
     *  @param callable|string $event The name of the event to listen for. Pass a callable to this parameter to catch all events.
19
     *  @param callable|null $function The callable that will be invoked on event
20
     */
21
    public function addHandler($event, ?callable $function): void
22
    {
23
        if (is_callable($event)) {
24
            $function = $event;
25
            $event = '*';
26
        }
27
28
        if (!array_key_exists($event, $this->eventHandlers)) {
29
            $this->eventHandlers[$event] = [];
30
        }
31
32
        $this->eventHandlers[$event][] = $function;
33
    }
34
35
    /**
36
     *  Invoke all handlers for a specific event.
37
     *
38
     *  @param Event $event
39
     */
40
    public function invoke(Event $event): void
41
    {
42
        $handlers = array_merge($this->eventHandlers['*'] ?? [], $this->eventHandlers[$event->getEvent()] ?? []);
43
        foreach ($handlers as $handler) {
44
            $handler(...$event->getArguments());
45
        }
46
    }
47
}
48