<?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  2018 Lifestyle Webconsulting GmbH
 * @link       http://www.life-style.de
 */

namespace LifeStyle\Tools\RestAuthBundle\EventListener;

use Doctrine\ORM\EntityManagerInterface;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Symfony\Component\HttpKernel\KernelEvents;

/**
 * Class TokenRotateListener
 *
 * @copyright  2016 Lifestyle Webconsulting GmbH
 * @link       http://www.life-style.de
 * @package LifeStyle\Tools\RestAuthBundle\EventListener
 */
class TokenRotateListener implements EventSubscriberInterface
{
    /**
     * @var EntityManagerInterface
     */
    private $entityManager;

    /**
     * TokenRotateListener constructor.
     * @param EntityManagerInterface $entityManager
     */
    public function __construct(EntityManagerInterface $entityManager)
    {
        $this->entityManager = $entityManager;
    }

    /**
     * @return array
     */
    public static function getSubscribedEvents()
    {
        return array(
            KernelEvents::CONTROLLER => 'rotate'
        );
    }

    /**
     * Delete entries from token-usage-table older than 5 minutes
     */
    public function rotate()
    {
        // We do not need this clean up on each request
        if (mt_rand(0, 100) > 20) {
            return;
        }

        $date = new \DateTime();
        $date->sub(new \DateInterval('PT5M'));

        $queryBuilder = $this->entityManager->createQueryBuilder();
        $queryBuilder->delete('LifeStyle\Tools\RestAuthBundle\Entity\Usage\WsseTokens', 't')
            ->andWhere($queryBuilder->expr()->lt('t.created', ':createdTime'));
        $this->entityManager->createQuery($queryBuilder)->setParameter('createdTime', $date)->execute();
    }
}
