<?php
namespace EADPlataforma\EventListener;
use Symfony\Component\HttpKernel\Event\RequestEvent;
use Symfony\Component\HttpKernel\Event\ExceptionEvent;
use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;
use Symfony\Component\HttpKernel\Exception\MethodNotAllowedHttpException;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpFoundation\RedirectResponse;
use Symfony\Component\Routing\Generator\UrlGeneratorInterface;
use Doctrine\DBAL\Exception\TableNotFoundException;
use Doctrine\DBAL\Exception\InvalidFieldNameException;
use Doctrine\DBAL\Exception\ConnectionException;
use EADPlataforma\Services\GeneralService;
use EADPlataforma\Http\EADResponse;
use EADPlataforma\Error\ActionInvalidException;
use EADPlataforma\Error\FieldException;
use EADPlataforma\Error\EADException;
class KernelListener
{
/**
*@var UrlGeneratorInterface
*/
protected $router;
/**
*@var GeneralService
*/
protected $generalService;
/**
* @param UrlGeneratorInterface Router
* @param GeneralService generalService
*/
public function __construct(UrlGeneratorInterface $router,
GeneralService $generalService)
{
$this->router = $router;
$this->generalService = $generalService;
}
public function onKernelRequest(RequestEvent $event)
{
//$databaseManagerService = $this->generalService->getService('DatabaseManagerService');
//$databaseManagerService->executeMigrations();
}
public function onKernelException(ExceptionEvent $event)
{
$exception = $event->getThrowable();
if($exception instanceof EADException){
$eadResponse = new EADResponse(
$exception->getData(),
$exception->getCode(),
$exception->getHeaders()
);
$event->setResponse($eadResponse->getResponse());
}else if(
$exception instanceof NotFoundHttpException ||
$exception instanceof MethodNotAllowedHttpException
) {
$route = 'notFound';
if ($route === $event->getRequest()->get('_route')) {
return;
}
$url = $this->router->generate($route);
$response = new RedirectResponse($url);
$event->setResponse($response);
}else if (
$exception instanceof TableNotFoundException ||
$exception instanceof InvalidFieldNameException
){
$databaseManagerService = $this->generalService->getService(
'DatabaseManagerService'
);
$databaseManagerService->executeMigrations();
sleep(2);
$route = 'notFound';
if ($route === $event->getRequest()->get('_route')) {
return;
}
$url = $this->router->generate($route);
$response = new RedirectResponse($url);
$event->setResponse($response);
}else if($exception instanceof ConnectionException){
print_r('Estamos em manutenção, retornaremos dentro de instantes.');
exit;
}
}
}