<?php

namespace events;

class EventService
{
    private static $events = [];

    public static function dispatchEvent($event, $args = null)
    {
        if (isset(self::$events[$event]) && !empty(self::$events[$event])) {
            foreach (self::$events[$event] as $function) {
                try {
                    call_user_func($function, $args);
                    syslog(LOG_DEBUG, "Calling function on $event event");
                } catch (\SocketConnectionException $exception) {
                    syslog(LOG_DEBUG, "Error occurred while calling function on $event event. " . $exception->getMessage());
                } catch (\Exception $exception) {
                    syslog(LOG_ERR, "Error occurred while calling function on $event event. " . $exception->getMessage());
                }
            }
        }
    }

    public static function addEventListener($event, \Closure $function): void
    {
        self::$events[$event][] = $function;
    }
}
