src/EventSubscriber/FeatureNotAvailableExceptionSubscriber.php line 29

Open in your IDE?
  1. <?php
  2. namespace App\EventSubscriber;
  3. use App\Constant\Features;
  4. use App\Exception\FeatureNotAvailableException;
  5. use App\Repository\Plan\PlanRepository;
  6. use Symfony\Component\EventDispatcher\EventSubscriberInterface;
  7. use Symfony\Component\HttpFoundation\JsonResponse;
  8. use Symfony\Component\HttpFoundation\Response;
  9. use Symfony\Component\HttpKernel\Event\ExceptionEvent;
  10. class FeatureNotAvailableExceptionSubscriber implements EventSubscriberInterface
  11. {
  12.     private $planRepository;
  13.     public function __construct(PlanRepository $planRepository)
  14.     {
  15.         $this->planRepository $planRepository;
  16.     }
  17.     public static function getSubscribedEvents(): array
  18.     {
  19.         return [
  20.             'kernel.exception' => 'onKernelException',
  21.         ];
  22.     }
  23.     public function onKernelException(ExceptionEvent $event)
  24.     {
  25.         $exception $event->getThrowable();
  26.         if ($exception instanceof FeatureNotAvailableException) {
  27.             $feature Features::findByRole($exception->getFeatureName());
  28.             $plans $this->planRepository->findAllWithFeatures();
  29.             $requiredPlan null;
  30.             foreach ($plans as $plan) {
  31.                 if ($plan->getFeatureByName($feature['name'])) {
  32.                     $requiredPlan $plan;
  33.                     break;
  34.                 }
  35.             }
  36.             $responseData = [
  37.                 'message' => $exception->getMessage(),
  38.                 'requiredPlan' => $requiredPlan ? [
  39.                     'id' => $requiredPlan->getId(),
  40.                     'name' => $requiredPlan->getName()
  41.                 ] : null
  42.             ];
  43.             $response = new JsonResponse($responseDataResponse::HTTP_FORBIDDEN);
  44.             $event->setResponse($response);
  45.         }
  46.     }
  47. }