<?php

namespace App\Modules\Shared\Infraestructure\Event;

use App\Modules\Shared\Domain\Bus\Event\Event;
use App\Modules\Shared\Domain\Bus\Event\EventBus;
use App\Modules\Shared\Infraestructure\CallableFirstParameterExtractor;
use Symfony\Component\HttpFoundation\Exception\BadRequestException;

final class InMemoryEventBus implements EventBus
{

    private $handlerLocator;
    public function __construct(iterable $eventHandlers)
    {
        $this->handlerLocator = CallableFirstParameterExtractor::forCallables($eventHandlers);
    }

    public function addHandlers(iterable $eventHandlers)
    {
        $locates = CallableFirstParameterExtractor::forCallables($eventHandlers);
        foreach ($locates as $key => $locate) {
            $this->handlerLocator[$key] = $locate;
        }
    }

    public function publish(Event $event)
    {
        if (isset($this->handlerLocator[$event::class])) {
            foreach ($this->handlerLocator[$event::class] as $classHandler) {
                $classHandler->__invoke($event);
            }
        }
    }

    public function publishAll(Event ...$event)
    {
        foreach ($event as $e) {
            if (isset($this->handlerLocator[$e::class])) {
                foreach ($this->handlerLocator[$e::class] as $classHandler) {
                    $classHandler->__invoke($e);
                }
            }
        }
    }
}
