src/EventListener/ApiViewEvent.php line 34

Open in your IDE?
  1. <?php
  2. namespace App\EventListener;
  3. use Symfony\Component\HttpFoundation\JsonResponse;
  4. use Symfony\Component\HttpFoundation\Response;
  5. use Symfony\Component\HttpKernel\Event\ViewEvent;
  6. use Symfony\Component\HttpKernel\Event\ExceptionEvent;
  7. use Symfony\Component\Security\Core\Exception\AccessDeniedException;
  8. use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;
  9. /**
  10.  * @author Nur Hidayatullah <kematjaya0@gmail.com>
  11.  */
  12. class ApiViewEvent 
  13. {
  14.     public function getRoutePrefix()
  15.     {
  16.         return ["api_"];
  17.     }
  18.     
  19.     public function onKernelView(ViewEvent $event):void
  20.     {
  21.         $value $event->getControllerResult();
  22.         $format = [
  23.             'data' => $value
  24.         ];
  25.         
  26.         $event->setResponse(
  27.             new JsonResponse($formatResponse::HTTP_OK)
  28.         );
  29.     }
  30.     
  31.     public function onKernelException(ExceptionEvent $event):void
  32.     {
  33.         $process false;
  34.         foreach ($this->getRoutePrefix() as $prefix) {
  35.             if (false !== strpos($event->getRequest()->attributes->get("_route"), $prefix)) {
  36.                 $process true;
  37.                 break;
  38.             }
  39.         }
  40.         
  41.         if (false === $process) {
  42.             return;
  43.         }
  44.         
  45.         $responseCode Response::HTTP_INTERNAL_SERVER_ERROR;
  46.         if ($event->getThrowable() instanceof AccessDeniedException) {
  47.             $responseCode Response::HTTP_UNAUTHORIZED;
  48.         }
  49.         if ($event->getThrowable() instanceof NotFoundHttpException) {
  50.             $responseCode Response::HTTP_NOT_FOUND;
  51.         }
  52. //        dump($event->getThrowable());exit;
  53.         $event->setResponse(
  54.             new JsonResponse([
  55.                 'error' => $event->getThrowable()->getMessage()
  56.             ], $responseCode)
  57.         );
  58.     }
  59. }