<?php
namespace App\Listener;
use App\Entity\User;
use App\Entity\UserToken;
use App\Services\UserTokenManager;
use Doctrine\ORM\EntityManager;
use Doctrine\ORM\EntityManagerInterface;
use Symfony\Component\HttpFoundation\RedirectResponse;
use Symfony\Component\HttpFoundation\Session\SessionInterface;
use Symfony\Component\HttpKernel\Event\FilterResponseEvent;
use Symfony\Component\HttpFoundation\Cookie;
use Symfony\Component\HttpKernel\HttpKernel;
use Symfony\Component\HttpKernel\Event\ResponseEvent;
use Symfony\Component\Security\Core\Authentication\Token\Storage\TokenStorageInterface;
class GenerateCookieListener
{
protected $session;
private $crypt;
/**
* @var EntityManager
*/
protected $em;
/**
* @var TokenStorageInterface
*/
protected $tokenStorage;
protected $userTokenManager;
public function __construct(SessionInterface $session, EntityManagerInterface $em, TokenStorageInterface $tokenStorage, UserTokenManager $userTokenManager)
{
$this->session = $session;
$this->em = $em;
$this->userTokenManager = $userTokenManager;
$this->tokenStorage = $tokenStorage;
}
public function onKernelResponse(ResponseEvent $event): void
{
// only on the “main” request
if (!$event->isMasterRequest()) {
return;
}
$request = $event->getRequest();
$response = $event->getResponse();
// If the controller has already set a cart_session cookie, do nothing
foreach ($response->headers->getCookies() as $cookie) {
if ($cookie->getName() === 'cart_session') {
return;
}
}
// Otherwise, if there's no valid cookie in the browser, seed one
$existing = $request->cookies->get('cart_session', '');
if (!is_string($existing) || strlen($existing) !== 36) {
$chars = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
$rand = '';
for ($i = 0; $i < 36; $i++) {
$rand .= $chars[random_int(0, strlen($chars) - 1)];
}
// also store in session if you want
$request->getSession()->set('cart_session', $rand);
// set it on the response
$response->headers->setCookie(new Cookie(
'cart_session',
$rand,
new \DateTime('+14 days'),
'/',
null,
false,
true
));
}
}
private function curPageURL() {
$pageURL = 'http';
if ($_SERVER["HTTPS"] == "on") {$pageURL .= "s";}
$pageURL .= "://";
if ($_SERVER["SERVER_PORT"] != "80") {
$pageURL .= $_SERVER["HTTP_HOST"]."".$_SERVER["REQUEST_URI"];
} else {
$pageURL .= $_SERVER["HTTP_HOST"].$_SERVER["REQUEST_URI"];
}
return $pageURL;
}
}