<?php
namespace App\EventListener;
use App\Client\Hubspot\Service\TokenService;
use App\Entity\System\Customer;
use App\Service\EnvironmentService;
use Symfony\Component\DependencyInjection\ParameterBag\ParameterBagInterface;
use Symfony\Component\HttpFoundation\Cookie;
use Symfony\Component\HttpKernel\Event\ResponseEvent;
use Symfony\Component\Security\Core\Authentication\Token\Storage\TokenStorageInterface;
class HubspotTokenChatListener
{
private TokenStorageInterface $tokenStorage;
private bool $isStaging;
private TokenService $tokenService;
private EnvironmentService $environmentService;
public function __construct(
ParameterBagInterface $parameterBag,
EnvironmentService $environmentService,
TokenStorageInterface $tokenStorage,
TokenService $tokenService
) {
$this->tokenStorage = $tokenStorage;
$this->isStaging = $parameterBag->get('is_staging');
$this->tokenService = $tokenService;
$this->environmentService = $environmentService;
}
public function onKernelResponse(ResponseEvent $event): void
{
if ($this->isStaging === false && $this->environmentService->isProd()) {
$customer = ($this->tokenStorage->getToken()) ? $this->tokenStorage->getToken()->getUser() : null;
$request = $event->getRequest();
$response = $event->getResponse();
if ($customer instanceof Customer) {
if (!$request->cookies->get('token_chat_hubspot')) {
try {
$tokenHubspot = $this->tokenService->getToken(
$customer->getEmail(),
$customer->getName(),
$customer->getSurnames()
);
} catch (\Throwable $e) {
$tokenHubspot = null;
}
$response->headers->setCookie(
new Cookie(
'token_chat_hubspot',
$tokenHubspot,
time() + 27000,
'/',
null,
null,
false
)
);
}
} else {
$response->headers->clearCookie('token_chat_hubspot');
}
}
}
}