src/EventSubscriber/ExceptionSubscriber.php line 37

  1. <?php
  2. namespace App\EventSubscriber;
  3. use App\Factory\JsonResponseInterface;
  4. use App\Normalizer\ExceptionNormalizerFormatterInterface;
  5. use App\Normalizer\NormalizerInterface;
  6. use Symfony\Component\EventDispatcher\EventSubscriberInterface;
  7. use Symfony\Component\HttpKernel\Event\ExceptionEvent;
  8. use Symfony\Component\HttpKernel\KernelEvents;
  9. use Symfony\Component\Serializer\SerializerInterface;
  10. /**
  11.  * @author Roméo Razafindrakoto <romeorazaf@myagency.mg>
  12.  */
  13. class ExceptionSubscriber implements EventSubscriberInterface
  14. {
  15.     /**
  16.      * @var array<NormalizerInterface>
  17.      */
  18.     private static array $normalizers;
  19.     public function __construct(
  20.         private readonly SerializerInterface $serializer,
  21.         private readonly ExceptionNormalizerFormatterInterface $exceptionNormalizerFormatter,
  22.         private readonly JsonResponseInterface $jsonResponse
  23.     ) {
  24.     }
  25.     public static function getSubscribedEvents(): array
  26.     {
  27.         return [
  28.             KernelEvents::EXCEPTION => [['processException'0]],
  29.         ];
  30.     }
  31.     public function processException(ExceptionEvent $event): void
  32.     {
  33.         $result null;
  34.         $request $event->getRequest();
  35.         $exception $event->getThrowable();
  36.         if (str_contains($request->getRequestUri(), '/api')) {
  37.             foreach (self::$normalizers as $key => $normalizer) {
  38.                 if ($normalizer->supports($exception)) {
  39.                     $result $normalizer->normalize($exception);
  40.                     break;
  41.                 }
  42.             }
  43.             if (null === $result) {
  44.                 $result $this->exceptionNormalizerFormatter->format(
  45.                     $exception->getMessage()
  46.                 );
  47.             }
  48.             $event->setResponse($this->jsonResponse->getJsonResponse(
  49.                 intval($result['code']),
  50.                 $this->serializer->serialize($result'json')
  51.             ));
  52.         }
  53.     }
  54.     public function addNormalizer(NormalizerInterface $normalizer): void
  55.     {
  56.         self::$normalizers[] = $normalizer;
  57.     }
  58. }