<?php
namespace App\Service;
use App\Entity\ProUser;
use App\Security\ADTokenAuthenticator;
use FOS\UserBundle\Model\UserManagerInterface;
use Psr\Log\LoggerInterface;
use Symfony\Component\HttpFoundation\Session\SessionInterface;
use Symfony\Component\Serializer\Encoder\JsonEncoder;
use Symfony\Component\Serializer\Normalizer\GetSetMethodNormalizer;
use Symfony\Component\Serializer\Serializer;
class ProUserRegistrationSession
{
public const SESSION_REGISTRATION_USER_KEY = 'pro_registration_user';
/** @var Serializer */
private $serializer;
public function __construct(private readonly SessionInterface $session, private readonly UserManagerInterface $userManager, private readonly LoggerInterface $logger)
{
$this->serializer = new Serializer(
[new GetSetMethodNormalizer()],
[new JsonEncoder()]
);
}
public function create()
{
/* @var ProUser $user */
$user = $this->userManager->createUser(ProUser::class);
$user->setEnabled(true);
$user->setEmail($this->session->get(ADTokenAuthenticator::SESSION_REGISTRATION_USER_EMAIL));
$user->setAdId($this->session->get(ADTokenAuthenticator::SESSION_REGISTRATION_USER_AD_ID));
$this->logger->info('ProUserRegistrationSession:40 User '.$user->getId().' enabled');
$user->setNeedsTransaction(false);
return $user;
}
public function exists(): bool
{
return $this->session->has(self::SESSION_REGISTRATION_USER_KEY);
}
public function load()
{
$user = $this->session->get(self::SESSION_REGISTRATION_USER_KEY);
return null === $user ? $this->create() : $this->serializer->deserialize($user, ProUser::class, 'json');
}
public function save(ProUser $user): void
{
$this->session->set(self::SESSION_REGISTRATION_USER_KEY, $this->serializer->serialize($user, 'json'));
}
public function remove(): void
{
$this->session->remove(self::SESSION_REGISTRATION_USER_KEY);
$this->session->remove(ADTokenAuthenticator::SESSION_REGISTRATION_USER_EMAIL);
$this->session->remove(ADTokenAuthenticator::SESSION_REGISTRATION_USER_AD_ID);
}
}