<?php
namespace Noahtech\Sistemas\InterjamaBundle\EventListener;
use Noahtech\Sistemas\InterjamaBundle\Utils\Response as ResponseMC;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Symfony\Component\HttpFoundation\File\Exception\AccessDeniedException;
use Symfony\Component\HttpFoundation\JsonResponse;
use Symfony\Component\HttpKernel\Event\GetResponseForExceptionEvent;
use Symfony\Component\HttpKernel\Exception\AccessDeniedHttpException;
use Symfony\Component\HttpKernel\Exception\HttpException;
use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;
use Symfony\Component\HttpKernel\KernelEvents;
use Symfony\Bundle\FrameworkBundle\Templating\EngineInterface;
use Symfony\Component\HttpFoundation\Response;
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
/**
* Description of ApiExceptionSubscriber
*
* @author rafa
*/
class ApiExceptionSubscriber implements EventSubscriberInterface {
private $templating;
public function __construct(EngineInterface $templating) {
$this->templating = $templating;
}
//put your code here
public static function getSubscribedEvents(): array {
return array(
KernelEvents::EXCEPTION => 'onKernelException'
);
}
public function onKernelException(GetResponseForExceptionEvent $event) {
$exception = $event->getException();
// $request = $event->getRequest();
$ajax = $event->getRequest()->isXmlHttpRequest();
$url = $event->getRequest()->getPathInfo();
$api=strpos($url, '/api/') !== false; // verificamos si viene de api para devolver un rest y no una pagina
if (!$exception instanceof HttpException) {
return;
}
$code = 500;
if ($exception instanceof HttpException) {
$code = 500;
}
if ($exception instanceof NotFoundHttpException) {
$code = 404;
}
if ($exception instanceof AccessDeniedHttpException) {
$code = 403;
}
if ($exception instanceof AccessDeniedException) {
$code = 403;
}
if ($exception instanceof \Symfony\Component\Security\Core\Exception\AccessDeniedException) {
$code = 403;
}
if ($ajax || $api) {
$response = new ResponseMC();
$response->setCode($code);
$response->setMessage($exception->getMessage());
$res = new JsonResponse(['code' => $response->getCode(),'error'=>1,
'message' => $response->getMessage()
]);
$res->headers->set('Content-Type', 'application/problem+json');
} else {
$title = "No se encuentra autorizado para acceder a la pagina.";
$res = new Response($this->templating->render('@NoahtechSistemasInterjama/Default/error.html.twig',
array('title' => $title, 'error' => 1), 200));
}
$event->setResponse($res);
}
}