<?php
namespace App\EventListener;
use App\Entity\Routing;
use Doctrine\ORM\EntityManager;
use Doctrine\ORM\EntityManagerInterface;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Symfony\Component\HttpFoundation\RedirectResponse;
use Symfony\Component\HttpKernel\Event\GetResponseEvent;
use Symfony\Component\HttpKernel\Event\GetResponseForExceptionEvent;
use Symfony\Component\HttpKernel\Exception\HttpExceptionInterface;
use Symfony\Component\HttpKernel\KernelEvents;
class RoutingSubscriber implements EventSubscriberInterface
{
/** @var EntityManager */
private $entityManager;
public function __construct(EntityManagerInterface $entityManager)
{
$this->entityManager = $entityManager;
}
public static function getSubscribedEvents()
{
return array(
KernelEvents::REQUEST => array(array('onKernelRequest', 17)),
KernelEvents::EXCEPTION => array(array('onKernelException', 10)),
);
}
/**
* @param GetResponseEvent $event
*/
public function onKernelRequest(GetResponseEvent $event)
{
$request = $event->getRequest();
$routing = $this->entityManager->getRepository(Routing::class)->findOneBy(
['routing' => $request->getPathInfo()]
);
if ($routing) {
$event->setResponse(
new RedirectResponse(
$routing->getRedirect(),
$routing->getCodeRedirect() ? $routing->getCodeRedirect() : ""
)
);
}
}
/**
* @param GetResponseForExceptionEvent $event
*/
public function onKernelException(GetResponseForExceptionEvent $event){
$exception = $event->getException();
if ($exception instanceof HttpExceptionInterface) {
if (404 == $exception->getStatusCode()) {
$request = $event->getRequest();
$pathinfo = $request->getPathInfo();
$baseurl = $request->getSchemeAndHttpHost() . $request->getBaseUrl();
if (FALSE !== strpos($pathinfo, '/article')) {
$event->setResponse(new RedirectResponse($baseurl . '/magazine'));
}elseif (FALSE !== strpos($pathinfo, '/activites')) {
$event->setResponse(new RedirectResponse($baseurl . '/activites'));
}
}
}
}
}