<?php
namespace App\EventListener;
use Symfony\Component\HttpFoundation\JsonResponse;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpKernel\Event\ViewEvent;
use Symfony\Component\HttpKernel\Event\ExceptionEvent;
use Symfony\Component\Security\Core\Exception\AccessDeniedException;
use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;
/**
* @author Nur Hidayatullah <kematjaya0@gmail.com>
*/
class ApiViewEvent
{
public function getRoutePrefix()
{
return ["api_"];
}
public function onKernelView(ViewEvent $event):void
{
$value = $event->getControllerResult();
$format = [
'data' => $value
];
$event->setResponse(
new JsonResponse($format, Response::HTTP_OK)
);
}
public function onKernelException(ExceptionEvent $event):void
{
$process = false;
foreach ($this->getRoutePrefix() as $prefix) {
if (false !== strpos($event->getRequest()->attributes->get("_route"), $prefix)) {
$process = true;
break;
}
}
if (false === $process) {
return;
}
$responseCode = Response::HTTP_INTERNAL_SERVER_ERROR;
if ($event->getThrowable() instanceof AccessDeniedException) {
$responseCode = Response::HTTP_UNAUTHORIZED;
}
if ($event->getThrowable() instanceof NotFoundHttpException) {
$responseCode = Response::HTTP_NOT_FOUND;
}
// dump($event->getThrowable());exit;
$event->setResponse(
new JsonResponse([
'error' => $event->getThrowable()->getMessage()
], $responseCode)
);
}
}