bundles/Suzuki/CoreBundle/APIExceptions/APIExceptionListener.php line 12

Open in your IDE?
  1. <?php
  2. namespace Suzuki\CoreBundle\APIExceptions;
  3. use Suzuki\CoreComponent\APIExceptions\APIExceptionInterface;
  4. use Symfony\Component\HttpFoundation\JsonResponse;
  5. use Symfony\Component\HttpKernel\Event\GetResponseForExceptionEvent;
  6. class APIExceptionListener
  7. {
  8.     public function onKernelException(GetResponseForExceptionEvent $event)
  9.     {
  10.         if ($event->getException() instanceof APIExceptionInterface) {
  11.             $response = new JsonResponse($this->buildResponseData($event->getException()));
  12.             $response->setStatusCode($event->getException()->getCode());
  13.             $event->setResponse($response);
  14.         }
  15.     }
  16.     /**
  17.      * @param APIExceptionInterface $exception
  18.      *
  19.      * @return array
  20.      */
  21.     private function buildResponseData(ApiExceptionInterface $exception)
  22.     {
  23.         $messages json_decode($exception->getMessage());
  24.         if ( !is_array($messages)) {
  25.             $messages $exception->getMessage() ? [$exception->getMessage()] : [];
  26.         }
  27.         return [
  28.             'error' => [
  29.                 'code'     => $exception->getCode(),
  30.                 'messages' => $messages,
  31.             ],
  32.         ];
  33.     }
  34. }