Completed
Push — master ( 7c39f2...831177 )
by Jeroen
04:12
created

EventHandlerCollection::invoke()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 5
Code Lines 3

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
eloc 3
dl 0
loc 5
rs 10
c 0
b 0
f 0
cc 2
nc 2
nop 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 string $event The event to invoke handlers for.
39
     *  @param array $arguments An array of arguments to be sent to the event handler.
40
     */
41
    public function invoke(string $event, array $arguments = []): void
42
    {
43
        $handlers = array_merge($this->eventHandlers['*'] ?? [], $this->eventHandlers[$event] ?? []);
44
        foreach ($handlers as $handler) {
45
            $handler(...$arguments);
46
        }
47
    }
48
}
49