src/EventSubscriber/FrontEventSubscriber.php line 30

Open in your IDE?
  1. <?php
  2. namespace App\EventSubscriber;
  3. use App\Repository\ExcludedIpRepository;
  4. use App\Service\Visits\VisitsManager;
  5. use JetBrains\PhpStorm\ArrayShape;
  6. use Symfony\Component\EventDispatcher\EventSubscriberInterface;
  7. use Symfony\Component\HttpKernel\Event\RequestEvent;
  8. use Symfony\Component\Security\Core\Security;
  9. class FrontEventSubscriber implements EventSubscriberInterface
  10. {
  11.     private string $method;
  12.     private bool $isCandidacy;
  13.     public function __construct(private VisitsManager $visitsManager, private Security $security, private ExcludedIpRepository $ipRepository)
  14.     {
  15.     }
  16.     public function onKernelView(RequestEvent $event)
  17.     {
  18.         if($this->security->getUser()) {
  19.             return;
  20.         }
  21.         if($this->ipRepository->findOneByIp($this->visitsManager->getUserIP())) {
  22.             return;
  23.         }
  24.         $this->method $event->getRequest()->getMethod();
  25.         $route $event->getRequest()->attributes->get('_route');
  26.         $this->isCandidacy = isset($event->getRequest()->request->getIterator()->getArrayCopy()['candidacy']);
  27.         switch ($route) {
  28.             case 'app_front':
  29.                 $this->openingFrontView();
  30.                 break;
  31.             case 'app_front_candidate':
  32.                 $this->candidate();
  33.                 break;
  34.             case 'app_front_spontaneous_candidate':
  35.                 $this->spontaneous();
  36.                 break;
  37.             default:
  38.                 break;
  39.         }
  40.     }
  41.     #[ArrayShape([RequestEvent::class => "string"])]
  42.     public static function getSubscribedEvents(): array
  43.     {
  44.         return [
  45.             RequestEvent::class => 'onKernelView'
  46.         ];
  47.     }
  48.     private function openingFrontView()
  49.     {
  50.         $this->visitsManager->addVisit();
  51.     }
  52.     private function candidate()
  53.     {
  54.         $name $this->isCandidacy 'candidate' 'open_candidacy_form';
  55.         $this->visitsManager->addClick($name);
  56.     }
  57.     private function spontaneous()
  58.     {
  59.         $this->addClickFromMethod($this->method'spontaneous');
  60.     }
  61.     private function addClickFromMethod($method$name)
  62.     {
  63.         switch ($method) {
  64.             case 'GET':
  65.                 $this->visitsManager->addClick('open_' $name '_form');
  66.                 break;
  67.             case 'POST':
  68.                 $this->visitsManager->addClick($name);
  69.                 break;
  70.         }
  71.     }
  72. }