<?php
namespace App\Event;
use App\Controller\AdminApi\AbstractAdminApiController;
use App\Event\ApiException;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Symfony\Component\HttpFoundation\JsonResponse;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpKernel\Event\ControllerEvent;
use Symfony\Component\HttpKernel\Event\ExceptionEvent;
use Symfony\Component\HttpKernel\Exception\AccessDeniedHttpException;
use Symfony\Component\HttpKernel\Exception\MethodNotAllowedHttpException;
use Symfony\Component\HttpKernel\Exception\NotAcceptableHttpException;
use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;
use Symfony\Component\HttpKernel\KernelEvents;
class AdminApiEventSubscriber implements EventSubscriberInterface {
private $api_host;
private $env;
public function __construct($api_host, $env) {
$this->api_host = $api_host;
$this->env = $env;
}
public static function getSubscribedEvents() {
return [
KernelEvents::EXCEPTION => 'onKernelException',
KernelEvents::CONTROLLER => 'onKernelController',
];
}
public function onKernelController(ControllerEvent $event) {
$c = $event->getController();
$controller = is_array($c) ? $c[0] : $c;
if(!$controller || !($controller instanceof AbstractAdminApiController)) return;
}
public function onKernelException(ExceptionEvent $event) {
$r = $event->getRequest();
if($r->getHost() != $this->api_host) return;
$ex = $event->getThrowable();
$data = [
'status' => Response::HTTP_INTERNAL_SERVER_ERROR,
'error' => "Unknown error"
];
if($this->env == "dev") {
$data['error'] = "[DEBUG ENV] ".$ex->getMessage();
$data['stack'] = $ex->getTrace();
}
switch(true) {
case $ex instanceof NotFoundHttpException:
case $ex instanceof AccessDeniedHttpException:
case $ex instanceof MethodNotAllowedHttpException:
case $ex instanceof NotAcceptableHttpException:
$data['status'] = $ex->getStatusCode();
$data['error'] = $ex->getMessage();
break;
case $ex instanceof ApiException:
$data['status'] = Response::HTTP_BAD_REQUEST;
$data['error'] = $ex->getMessage();
break;
}
$event->setResponse(new JsonResponse($data, $data['status']));
}
}