jerodev /
php-irc-client
| 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
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 |