Passed
Pull Request — master (#12)
by
unknown
08:46
created

EventHandlerCollection::__construct()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 3
Code Lines 1

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 1
eloc 1
nc 1
nop 0
dl 0
loc 3
rs 10
c 0
b 0
f 0
1
<?php
2
3
declare(strict_types=1);
4
5
namespace Jerodev\PhpIrcClient\Helpers;
6
7
class EventHandlerCollection
8
{
9
    /** @var array<string, array<int, callable>> */
10
    private array $eventHandlers = [];
11
12
    /**
13
     * Register an event handler.
14
     *
15
     * @param callable|string $event The name of the event to listen for. Pass a callable to this parameter to catch all events.
16
     * @param callable|null $function The callable that will be invoked on event
17
     */
18
    public function addHandler(
19
        callable | string $event,
20
        ?callable $function
21
    ): void {
22
        if (is_callable($event)) {
23
            $function = $event;
24
            $event = '*';
25
        }
26
27
        if (!array_key_exists($event, $this->eventHandlers)) {
0 ignored issues
show
Bug introduced by
It seems like $event can also be of type callable; however, parameter $key of array_key_exists() does only seem to accept integer|string, maybe add an additional type check? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

27
        if (!array_key_exists(/** @scrutinizer ignore-type */ $event, $this->eventHandlers)) {
Loading history...
28
            $this->eventHandlers[$event] = [];
29
        }
30
31
        /** @psalm-suppress InvalidPropertyAssignmentValue */
32
        $this->eventHandlers[$event][] = $function;
33
    }
34
35
    /**
36
     *  Invoke all handlers for a specific event.
37
     */
38
    public function invoke(Event $event): void
39
    {
40
        $handlers = array_merge(
41
            $this->eventHandlers['*'] ?? [],
42
            $this->eventHandlers[$event->getEvent()] ?? []
43
        );
44
        foreach ($handlers as $handler) {
45
            $handler(...$event->getArguments());
46
        }
47
    }
48
}
49