src/EventSubscriber/ApiAccessDeniedSubscriber.php line 27

Open in your IDE?
  1. <?php
  2. namespace Seidemann\Hanagud\EventSubscriber;
  3. use Seidemann\Hanagud\Http\ApiResponse;
  4. use Symfony\Component\EventDispatcher\EventSubscriberInterface;
  5. use Symfony\Component\HttpKernel\DataCollector\ExceptionDataCollector;
  6. use Symfony\Component\HttpKernel\Event\ExceptionEvent;
  7. use Symfony\Component\HttpKernel\KernelEvents;
  8. use Symfony\Component\HttpKernel\Profiler\Profiler;
  9. use Symfony\Component\Security\Core\Exception\AccessDeniedException;
  10. class ApiAccessDeniedSubscriber implements EventSubscriberInterface
  11. {
  12.     public function __construct(private ?Profiler $profiler null)
  13.     {
  14.     }
  15.     /**
  16.      * Creates the ApiResponse from a given AccessDeniedException.
  17.      */
  18.     private function createApiResponse(AccessDeniedException $exception): ApiResponse
  19.     {
  20.         return new ApiResponse(null$exception403);
  21.     }
  22.     public function onKernelException(ExceptionEvent $event): void
  23.     {
  24.         $exception $event->getThrowable();
  25.         if (!$exception instanceof AccessDeniedException) {
  26.             return;
  27.         }
  28.         $request $event->getRequest();
  29.         if (in_array('application/json'$request->getAcceptableContentTypes())) {
  30.             $response $this->createApiResponse($exception);
  31.             $event->setResponse($response);
  32.             // If profiler is enabled, log exception into it
  33.             if (null !== $this->profiler) {
  34.                 /** @var ExceptionDataCollector $exceptionCollector */
  35.                 $exceptionCollector $this->profiler->get('exception');
  36.                 $exceptionCollector->collect($request$response$exception);
  37.             }
  38.         }
  39.     }
  40.     public static function getSubscribedEvents()
  41.     {
  42.         return [
  43.             KernelEvents::EXCEPTION => [
  44.                 // we need a higher priority than Security HTTP ExceptionListener,
  45.                 // however we use a different priority for the rest of the responses,
  46.                 // hence this is in its own class
  47.                 ['onKernelException'2],
  48.             ],
  49.         ];
  50.     }
  51. }