<?php
namespace App\EventListener;
use App\Entity\Redirection;
use Doctrine\ORM\EntityManagerInterface;
use Symfony\Component\HttpFoundation\RedirectResponse;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpKernel\Event\RequestEvent;
use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;
use Symfony\Component\Routing\Router;
use Symfony\Component\Routing\RouterInterface;
use Symfony\Component\VarDumper\VarDumper;
class RequestListener
{
private $em;
private $router;
public function __construct(RouterInterface $router,EntityManagerInterface $em)
{
$this->router = $router;
$this->em = $em;
}
public function onKernelRequest(RequestEvent $event)
{
if ($event->getRequest()->getRequestUri()) {
if ($event->getThrowable() instanceof NotFoundHttpException) {
$code = "404";
} else {
$code = "500";
}
$redirections = $this->em->getRepository("App:Redirection")->findBy(['path' => $event->getRequest()->getRequestUri(), 'deletedAt' => null]);
if (count($redirections)<=0) {
$target = null;
foreach ($redirections as $redirection){
if ($redirection->getTarget()){
$target = $redirection->getTarget();
}
}
// if($target !== null){
// $response = new RedirectResponse($redirection->getTarget(), Response::HTTP_MOVED_PERMANENTLY);
// $event->setResponse($response);
// }else{
// $event->setResponse(new RedirectResponse($this->router->generate('error_controller_index_test', ['code'=>$code])));
// $event->stopPropagation();
// }
}
}
}
}