src/EventListener/RequestListener.php line 38

Open in your IDE?
  1. <?php
  2. namespace App\EventListener;
  3. use Doctrine\ORM\EntityManagerInterface;
  4. use Symfony\Component\EventDispatcher\EventSubscriberInterface;
  5. use Symfony\Component\HttpFoundation\RedirectResponse;
  6. use Symfony\Component\HttpFoundation\Response;
  7. use Symfony\Component\HttpKernel\Event\ExceptionEvent;
  8. use Symfony\Component\HttpKernel\Event\GetResponseForExceptionEvent;
  9. use Symfony\Component\HttpKernel\Event\RequestEvent;
  10. use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;
  11. use Symfony\Component\Routing\Router;
  12. use Symfony\Component\Routing\RouterInterface;
  13. use Symfony\Component\VarDumper\VarDumper;
  14. use Symfony\Contracts\HttpClient\HttpClientInterface;
  15. use Symfony\Component\DependencyInjection\ParameterBag\ParameterBagInterface;
  16. use App\Entity\Redirection;
  17. use App\Entity\User;
  18. use App\Service\FacebookConversion;
  19. class RequestListener implements EventSubscriberInterface
  20. {
  21.     private $em;
  22.     private $router;
  23.     private $client;
  24.     private $params;
  25.     private $fbConversion;
  26.     public function __construct(RouterInterface $routerEntityManagerInterface $emHttpClientInterface $clientParameterBagInterface $paramsFacebookConversion $fbConversion)
  27.     {
  28.         $this->router $router;
  29.         $this->em $em;
  30.         $this->client $client;
  31.         $this->params $params;
  32.         $this->fbConversion $fbConversion;
  33.     }
  34.     public static function getSubscribedEvents(): array
  35.     {
  36.         return [
  37.             ExceptionEvent::class => 'onException',
  38.             RequestEvent::class => 'onRequest',
  39.         ];
  40.     }
  41.     public function onException(RequestEvent $event)
  42.     {
  43.         if ($event->getRequest()->getRequestUri()) {
  44.             if ($event->getThrowable() instanceof NotFoundHttpException) {
  45.                 $code "404";
  46.             } else {
  47.                 $code "500";
  48.             }
  49.             $redirections $this->em->getRepository("App:Redirection")->findBy(['path' => $event->getRequest()->getRequestUri(), 'deletedAt' => null]);
  50.             if (count($redirections) <= 0) {
  51.                 $redirection = new Redirection();
  52.                 $redirection->setPath($event->getRequest()->getRequestUri());
  53.                 $redirection->setCode($code);
  54.                 $this->em->persist($redirection);
  55.                 $this->em->flush();
  56.             } else {
  57.                 $target null;
  58.                 foreach ($redirections as $redirection) {
  59.                     if ($redirection->getTarget()) {
  60.                         $target $redirection->getTarget();
  61.                     }
  62.                 }
  63.                 if ($target !== null) {
  64.                     $response = new RedirectResponse($redirection->getTarget(), Response::HTTP_MOVED_PERMANENTLY);
  65.                     $event->setResponse($response);
  66.                 }
  67.             }
  68.         }
  69.     }
  70.     private function fetchUsersLocationFromIp(string $ip): ?array
  71.     {
  72.         try {
  73.             $response $this->client->request('GET''https://ipinfo.io/' $ip '/json?token=' $this->params->get('ipinfo_token'));
  74.             if ($response->getStatusCode() === 200) {
  75.                 $res $response->toArray();
  76.                 if (!isset($res['country']) || !isset($res['timezone'])) {
  77.                     return null;
  78.                 }
  79.                 return $response->toArray();
  80.             }
  81.         } catch (\Exception $e) {
  82.             return null;
  83.         }
  84.         return null;
  85.     }
  86.     private function getCurrencyFromIp(string $ip): string
  87.     {
  88.         $location $this->fetchUsersLocationFromIp($ip);
  89.         if (!$location) {
  90.             return 'euros';
  91.         }
  92.         if ($location['country'] === 'FR') {
  93.             return 'euros';
  94.         } else if ($location['country'] === 'GB') {
  95.             return 'pounds';
  96.         }
  97.         if (strpos($location['timezone'], 'Europe') === false) {
  98.             return 'dollars';
  99.         }
  100.         return 'euros';
  101.     }
  102.     public function onRequest(RequestEvent $event)
  103.     {
  104.         $userAgent $event->getRequest()->headers->get('User-Agent');
  105.         if (preg_match('/googlebot|bingbot|slurp|duckduckbot|baiduspider|yandex|uptimerobot/i'$userAgent)) {
  106.             return;
  107.         }
  108.         // do not redirect if the request is for an API endpoint or the admin panel
  109.         if (str_starts_with($event->getRequest()->getRequestUri(), '/api') || str_starts_with($event->getRequest()->getRequestUri(), '/admin')) {
  110.             return;
  111.         }
  112.         if ($event->isMainRequest()) {
  113.             $session $event->getRequest()->getSession();
  114.             if($event->getRequest()->get('selected_locale')){
  115.                 $session->set('selected_locale'$event->getRequest()->get('selected_locale'));
  116.             }
  117.             // if (!$session->has('uniqSessionId')) {
  118.             //     $session->set('uniqSessionId', $session->getId().'_'.uniqid());
  119.             // }
  120.             if ($event->getRequest()->get('fbclid')){
  121.                 $session->set('fbclid'$this->fbConversion->makeFBCID($event->getRequest()->get('fbclid')));
  122.             }
  123.             if ($event->getRequest()->get('rdt_cid')){
  124.                 $session->set('rdt_cid'$event->getRequest()->get('rdt_cid'));
  125.             }
  126.             if ($event->getRequest()->get('selected_currency')){
  127.                 $allowedCurrencies = ['euros''dollars''pounds'];
  128.                 $selectedCurrency $event->getRequest()->get('selected_currency');
  129.                 if (in_array($selectedCurrency$allowedCurrencies) && $selectedCurrency !== $session->get('currency')) {
  130.                     $session->set('currency'$selectedCurrency);
  131.                     $session $event->getRequest()->getSession();
  132.                     $repoCart $this->em->getRepository('App:Cart');
  133.                     $cart $repoCart->findOneBy(array(
  134.                         "session" => User::getSessionId($event->getRequest()),
  135.                         "ordered" => false
  136.                     ));
  137.                     if ($cart) {
  138.                         foreach ($cart->getCartProducts() as $cartProduct) {
  139.                             $this->em->remove($cartProduct);
  140.                         }
  141.                         $this->em->remove($cart);
  142.                         $this->em->flush();
  143.                     }
  144.                 }
  145.             }
  146.             if (!$session->get('currency')) {
  147.                 $userIp = isset($_SERVER['HTTP_X_FORWARDED_FOR']) ? $_SERVER['HTTP_X_FORWARDED_FOR'] : $_SERVER['REMOTE_ADDR'];
  148.                 $session->set('currency'$this->getCurrencyFromIp($userIp));
  149.             }
  150.             $browserLocale $event->getRequest()->getPreferredLanguage(array('en''fr'));
  151.             $targetLocale $session->has('selected_locale') ? $session->get('selected_locale') : $browserLocale;
  152.             if ($event->getRequest()->getLocale() != $targetLocale) {
  153.                 $route $this->router->match($event->getRequest()->getPathInfo());
  154.                 if(array_key_exists('_route'$route)){
  155.                     $attributes $route;
  156.                     unset($attributes['_route']);
  157.                     unset($attributes['_controller']);
  158.                     $attributes['_locale'] = $targetLocale;
  159.                     $response = new RedirectResponse($this->router->generate($route["_route"], $attributes));
  160.                     $event->getRequest()->setLocale($targetLocale);
  161.                     $event->setResponse($response);
  162.                 }
  163.             }
  164.         }
  165.     }
  166. }