<?php
namespace App\Repository;
use App\Entity\User;
use App\Entity\UserToken;
use Doctrine\Bundle\DoctrineBundle\Repository\ServiceEntityRepository;
use Doctrine\Persistence\ManagerRegistry;
/**
* @method UserToken|null find($id, $lockMode = null, $lockVersion = null)
* @method UserToken|null findOneBy(array $criteria, array $orderBy = null)
* @method UserToken[] findAll()
* @method UserToken[] findBy(array $criteria, array $orderBy = null, $limit = null, $offset = null)
*/
class UserTokenRepository extends ServiceEntityRepository
{
/**
* @var int
*/
private $tokenTtl;
/**
* UserTokenRepository constructor.
* @param ManagerRegistry $registry
* @param int $tokenTtl
*/
public function __construct(ManagerRegistry $registry, int $tokenTtl)
{
parent::__construct($registry, UserToken::class);
$this->tokenTtl = $tokenTtl;
}
/**
* @param User $user
* @param string $tokenString
*
* @throws \Exception
* @throws \Doctrine\ORM\ORMException
* @throws \Doctrine\ORM\OptimisticLockException
*/
public function create(User $user, string $tokenString)
{
$token = new UserToken($user);
$token->setTokenString($tokenString);
$validDate = new \DateTime("now");
$validInterval = new \DateInterval("PT{$this->tokenTtl}S");
$token->setValidTo($validDate->add($validInterval));
$this->getEntityManager()->persist($token);
$this->getEntityManager()->flush();
}
/**
* @param User $user
*/
public function disableOldTokens(User $user)
{
$qb = $this->_em->createQueryBuilder();
$q = $qb->update(UserToken::class, 'ut')
->set('ut.isValid', $qb->expr()->literal(false))
->where('ut.user = ?1')
->andWhere('ut.isValid = ?2')
->setParameter(1, $user)
->setParameter(2, $qb->expr()->literal(true))
->getQuery();
$q->execute();
}
}