<?php

namespace App\Listeners;

use App\Events\AddScriptEvent;
use Twig\Environment;

class AddScriptListener
{
    protected array $menuItems;

    /**
     * Create the event listener.
     *
     * @return void
     */
    public function __construct()
    {
        //
    }

    /**
     * Handle the event.
     *
     * @param AddScriptEvent $event
     * @return void
     */
    public function handle(AddScriptEvent $event): void
    {
        /** @var Environment $twig */
        $twig = app('twig');

        $twigGlobals = $twig->getGlobals();

        if (!isset($twigGlobals[AddScriptEvent::GLOBAL_KEY])) {
            return;
        }
        $scripts = $twigGlobals[AddScriptEvent::GLOBAL_KEY];
        $scripts[] = $event->script;
        $twig->addGlobal(AddScriptEvent::GLOBAL_KEY, $scripts);
    }
}
