<?php
namespace App\EventSubscriber;
use App\Constant\Features;
use App\Exception\FeatureNotAvailableException;
use App\Repository\Plan\PlanRepository;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Symfony\Component\HttpFoundation\JsonResponse;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpKernel\Event\ExceptionEvent;
class FeatureNotAvailableExceptionSubscriber implements EventSubscriberInterface
{
private $planRepository;
public function __construct(PlanRepository $planRepository)
{
$this->planRepository = $planRepository;
}
public static function getSubscribedEvents(): array
{
return [
'kernel.exception' => 'onKernelException',
];
}
public function onKernelException(ExceptionEvent $event)
{
$exception = $event->getThrowable();
if ($exception instanceof FeatureNotAvailableException) {
$feature = Features::findByRole($exception->getFeatureName());
$plans = $this->planRepository->findAllWithFeatures();
$requiredPlan = null;
foreach ($plans as $plan) {
if ($plan->getFeatureByName($feature['name'])) {
$requiredPlan = $plan;
break;
}
}
$responseData = [
'message' => $exception->getMessage(),
'requiredPlan' => $requiredPlan ? [
'id' => $requiredPlan->getId(),
'name' => $requiredPlan->getName()
] : null
];
$response = new JsonResponse($responseData, Response::HTTP_FORBIDDEN);
$event->setResponse($response);
}
}
}