<?php

/**
 * Lifestyle Webconsulting GmbH
 *
 * LICENSE: This Software is the property of Lifestyle Webconsulting GmbH (Aschaffenburg, Germany)
 * and is private by copyright law - it is NOT Freeware.
 *
 * Any unauthorized use of this software without a valid license
 * is a violation of the license agreement and will be prosecuted by
 * civil and criminal law.
 *
 * @copyright  2019 Lifestyle Webconsulting GmbH
 * @link       https://www.life-style.de
 */

namespace Sso\AccessBundle\Repository;

use DateTime;
use Doctrine\ORM\EntityRepository;

/**
 * Class TemporaryTokenRepository
 *
 * @copyright  2019 Lifestyle Webconsulting GmbH
 * @link       https://www.life-style.de
 * @package Sso\AccessBundle\Repository
 */
class TemporaryTokenRepository extends EntityRepository
{
    /**
     * @inheritDoc
     */
    public function find($id, $lockMode = null, $lockVersion = null)
    {
        $this->deleteExpired();
        return parent::find((string)$id, $lockMode, $lockVersion);
    }

    /**
     * Deletes expired entries from temporary token storage
     */
    private function deleteExpired()
    {
        $qb = $this->createQueryBuilder('t');
        $qb->delete();
        $qb->where('t.expire < :now');
        $qb->setParameter('now', new DateTime());
        $qb->getQuery()->execute();
    }
}
