src/Repository/UserTokenRepository.php line 31

Open in your IDE?
  1. <?php
  2. namespace App\Repository;
  3. use App\Entity\User;
  4. use App\Entity\UserToken;
  5. use Doctrine\Bundle\DoctrineBundle\Repository\ServiceEntityRepository;
  6. use Doctrine\Persistence\ManagerRegistry;
  7. /**
  8.  * @method UserToken|null find($id, $lockMode = null, $lockVersion = null)
  9.  * @method UserToken|null findOneBy(array $criteria, array $orderBy = null)
  10.  * @method UserToken[]    findAll()
  11.  * @method UserToken[]    findBy(array $criteria, array $orderBy = null, $limit = null, $offset = null)
  12.  */
  13. class UserTokenRepository extends ServiceEntityRepository
  14. {
  15.     /**
  16.      * @var int
  17.      */
  18.     private $tokenTtl;
  19.     /**
  20.      * UserTokenRepository constructor.
  21.      * @param ManagerRegistry $registry
  22.      * @param int $tokenTtl
  23.      */
  24.     public function __construct(ManagerRegistry $registryint $tokenTtl)
  25.     {
  26.         parent::__construct($registryUserToken::class);
  27.         $this->tokenTtl $tokenTtl;
  28.     }
  29.     /**
  30.      * @param User $user
  31.      * @param string $tokenString
  32.      *
  33.      * @throws \Exception
  34.      * @throws \Doctrine\ORM\ORMException
  35.      * @throws \Doctrine\ORM\OptimisticLockException
  36.      */
  37.     public function create(User $userstring $tokenString)
  38.     {
  39.         $token = new UserToken($user);
  40.         $token->setTokenString($tokenString);
  41.         $validDate = new \DateTime("now");
  42.         $validInterval = new \DateInterval("PT{$this->tokenTtl}S");
  43.         $token->setValidTo($validDate->add($validInterval));
  44.         $this->getEntityManager()->persist($token);
  45.         $this->getEntityManager()->flush();
  46.     }
  47.     /**
  48.      * @param User $user
  49.      */
  50.     public function disableOldTokens(User $user)
  51.     {
  52.         $qb $this->_em->createQueryBuilder();
  53.         $q $qb->update(UserToken::class, 'ut')
  54.             ->set('ut.isValid'$qb->expr()->literal(false))
  55.             ->where('ut.user = ?1')
  56.             ->andWhere('ut.isValid = ?2')
  57.             ->setParameter(1$user)
  58.             ->setParameter(2$qb->expr()->literal(true))
  59.             ->getQuery();
  60.         $q->execute();
  61.     }
  62. }