<?php
/**
 * @author Colinet Julien
 */

namespace CpCreation\VitiCore\Bridge\Symfony\Bundle\EventListener;

use Doctrine\ORM\EntityManagerInterface;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Symfony\Component\HttpKernel\Event\RequestEvent;
use Symfony\Component\HttpKernel\HttpKernelInterface;

class OrmFilterSubscriber implements EventSubscriberInterface
{
    private $em;

    public function __construct(EntityManagerInterface $em)
    {
        $this->em = $em;
    }

    public static function getSubscribedEvents(): array
    {
        return [
            RequestEvent::class => 'onKernelRequest',
        ];
    }

    /**
     * @param RequestEvent $event
     */
    public function onKernelRequest(RequestEvent $event)
    {
        if (($event->getRequestType() !== HttpKernelInterface::MASTER_REQUEST) || !$event->getRequest()->attributes->has('_controller')) {
            return;
        }
        if (preg_match('/Controller\\\\Admin/', $event->getRequest()->attributes->get('_controller'))) {
            $filter = $this->em->getFilters()->disable('disable');
        }

        return;
    }
}