<?php

declare(strict_types=1);

namespace PpPhp\Core;

class EventDispatcher
{
    private array $listeners = [];

    /**
     * Register a listener for an event.
     *
     * @param string   $eventName
     * @param callable $listener  A callable, e.g., [$object, 'method']
     */
    public function addListener(string $eventName, callable $listener): void
    {
        $this->listeners[$eventName][] = $listener;
    }

    /**
     * Dispatch an event, calling all registered listeners.
     */
    public function dispatch(string $eventName, ...$args): void
    {
        if (!isset($this->listeners[$eventName])) {
            return;
        }

        foreach ($this->listeners[$eventName] as $listener) {
            $listener(...$args);
        }
    }
}