vendor/nijens/openapi-bundle/src/EventListener/JsonResponseExceptionSubscriber.php line 58

Open in your IDE?
  1. <?php
  2. declare(strict_types=1);
  3. /*
  4.  * This file is part of the OpenapiBundle package.
  5.  *
  6.  * (c) Niels Nijens <nijens.niels@gmail.com>
  7.  *
  8.  * For the full copyright and license information, please view the LICENSE
  9.  * file that was distributed with this source code.
  10.  */
  11. namespace Nijens\OpenapiBundle\EventListener;
  12. use Exception;
  13. use Nijens\OpenapiBundle\Routing\RouteContext;
  14. use Nijens\OpenapiBundle\Service\ExceptionJsonResponseBuilderInterface;
  15. use Symfony\Component\EventDispatcher\EventSubscriberInterface;
  16. use Symfony\Component\HttpKernel\Event\ExceptionEvent;
  17. use Symfony\Component\HttpKernel\KernelEvents;
  18. /**
  19.  * Transforms an exception to a JSON response for OpenAPI routes.
  20.  *
  21.  * @deprecated since 1.3, to be removed in 2.0. Use the new exception handling system instead.
  22.  */
  23. class JsonResponseExceptionSubscriber implements EventSubscriberInterface
  24. {
  25.     /**
  26.      * @var ExceptionJsonResponseBuilderInterface
  27.      */
  28.     private $responseBuilder;
  29.     /**
  30.      * {@inheritdoc}
  31.      */
  32.     public static function getSubscribedEvents(): array
  33.     {
  34.         return [
  35.             KernelEvents::EXCEPTION => [
  36.                 ['onKernelExceptionTransformToJsonResponse'0],
  37.             ],
  38.         ];
  39.     }
  40.     /**
  41.      * Constructs a new JsonResponseExceptionSubscriber instance.
  42.      */
  43.     public function __construct(ExceptionJsonResponseBuilderInterface $responseBuilder)
  44.     {
  45.         $this->responseBuilder $responseBuilder;
  46.     }
  47.     /**
  48.      * Converts the exception to a JSON response.
  49.      */
  50.     public function onKernelExceptionTransformToJsonResponse(ExceptionEvent $event): void
  51.     {
  52.         $routeOptions $event->getRequest()->attributes->get(RouteContext::REQUEST_ATTRIBUTE);
  53.         if (isset($routeOptions[RouteContext::RESOURCE]) === false) {
  54.             return;
  55.         }
  56.         $exception $event->getThrowable();
  57.         if ($exception === null) {
  58.             return;
  59.         }
  60.         if ($exception instanceof Exception === false) {
  61.             $exception = new Exception($exception->getMessage(), $exception->getCode(), $exception);
  62.         }
  63.         $event->setResponse($this->responseBuilder->build($exception));
  64.     }
  65. }