<?php
declare(strict_types=1);
namespace App\Bundles\ApiBundle\EventListener;
use DateTime;
use Exception;
use Lexik\Bundle\JWTAuthenticationBundle\Event\JWTCreatedEvent;
use Symfony\Component\HttpFoundation\RequestStack;
class JWTCreatedListener
{
/**
* @var array
*/
private array $requestData = [];
/**
* @param RequestStack $requestStack
*/
public function __construct(RequestStack $requestStack)
{
$currentRequest = $requestStack->getCurrentRequest();
if (!empty($currentRequest)) {
$json = $currentRequest->getContent();
}
if (!empty($json) && is_string($json)) {
$this->requestData = json_decode($json, true);
}
}
/**
* @param JWTCreatedEvent $event
* @return void
*
* @throws Exception
*/
public function onJWTCreated(JWTCreatedEvent $event): void
{
$days = (isset($this->requestData['remember']) && $this->requestData['remember'] === true)
? '+30 day'
: '+1 day';
$expiration = new DateTime($days);
$payload = $event->getData();
$payload['exp'] = $expiration->getTimestamp();
$event->setData($payload);
}
}