src/EventListener/HubspotTokenChatListener.php line 32

Open in your IDE?
  1. <?php
  2. namespace App\EventListener;
  3. use App\Client\Hubspot\Service\TokenService;
  4. use App\Entity\System\Customer;
  5. use App\Service\EnvironmentService;
  6. use Symfony\Component\DependencyInjection\ParameterBag\ParameterBagInterface;
  7. use Symfony\Component\HttpFoundation\Cookie;
  8. use Symfony\Component\HttpKernel\Event\ResponseEvent;
  9. use Symfony\Component\Security\Core\Authentication\Token\Storage\TokenStorageInterface;
  10. class HubspotTokenChatListener
  11. {
  12.     private TokenStorageInterface $tokenStorage;
  13.     private bool $isStaging;
  14.     private TokenService $tokenService;
  15.     private EnvironmentService $environmentService;
  16.     public function __construct(
  17.         ParameterBagInterface $parameterBag,
  18.         EnvironmentService $environmentService,
  19.         TokenStorageInterface $tokenStorage,
  20.         TokenService $tokenService
  21.     ) {
  22.         $this->tokenStorage $tokenStorage;
  23.         $this->isStaging $parameterBag->get('is_staging');
  24.         $this->tokenService $tokenService;
  25.         $this->environmentService $environmentService;
  26.     }
  27.     public function onKernelResponse(ResponseEvent $event): void
  28.     {
  29.         if ($this->isStaging === false && $this->environmentService->isProd()) {
  30.             $customer = ($this->tokenStorage->getToken()) ? $this->tokenStorage->getToken()->getUser() : null;
  31.             $request $event->getRequest();
  32.             $response $event->getResponse();
  33.             if ($customer instanceof Customer) {
  34.                 if (!$request->cookies->get('token_chat_hubspot')) {
  35.                     try {
  36.                         $tokenHubspot $this->tokenService->getToken(
  37.                             $customer->getEmail(),
  38.                             $customer->getName(),
  39.                             $customer->getSurnames()
  40.                         );
  41.                     } catch (\Throwable $e) {
  42.                         $tokenHubspot null;
  43.                     }
  44.                     $response->headers->setCookie(
  45.                         new Cookie(
  46.                             'token_chat_hubspot',
  47.                             $tokenHubspot,
  48.                             time() + 27000,
  49.                             '/',
  50.                             null,
  51.                             null,
  52.                             false
  53.                         )
  54.                     );
  55.                 }
  56.             } else {
  57.                 $response->headers->clearCookie('token_chat_hubspot');
  58.             }
  59.         }
  60.     }
  61. }