<?php

namespace KupShop\AdminBundle\EventListener;

use KupShop\AdminBundle\AdminRequiredControllerInterface;
use KupShop\KupShopBundle\Config;
use KupShop\KupShopBundle\Exception\RedirectException;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Symfony\Component\HttpKernel\Event\ControllerEvent;
use Symfony\Component\HttpKernel\KernelEvents;

class AdminAuthenticationListener implements EventSubscriberInterface
{
    public static function getSubscribedEvents()
    {
        return [
            KernelEvents::CONTROLLER => 'onKernelController',
        ];
    }

    public function onKernelController(ControllerEvent $event)
    {
        $controller = $event->getController();
        $request = $event->getRequest();

        if (!is_array($controller)) {
            return;
        }

        if ($controller[0] instanceof AdminRequiredControllerInterface) {
            if (!getAdminUser()) {
                $cfg = Config::get();
                throw new RedirectException('/'.trim($cfg['Path']['admin'], '/').'/index.php?error=4&url='.urlencode($request->getRequestUri()));
            }
        }
    }
}
