<?php

/**
 * Logrotate handling
 *
 * LICENSE: This Software is the property of Lifestyle Webconsulting GmbH (Aschaffenburg, Germany)
 * and is protected 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  2014 Lifestyle Webconsulting GmbH
 * @version    $Id:$
 * @link       http://www.life-style.de
 */

namespace Sso\WebserviceBundle\Logger\TokenUsage;

use Doctrine\ORM\EntityManager;

/**
 * Class LogrotateHandler
 * @package Sso\WebserviceBundle\Logger\TokenUsage
 */
class LogrotateHandler
{

    /**
     * @var EntityManager
     */
    private $entityManager;

    /**
     * @var boolean
     */
    private $readonly;

    /**
     * LogrotateHandler constructor.
     * @param EntityManager $entityManager
     * @param bool $readonly
     */
    public function __construct(EntityManager $entityManager, $readonly)
    {
        $this->entityManager = $entityManager;
        $this->readonly = (boolean)$readonly;
    }

    /**
     * Do log rotate - Delete entries older than $createTime
     * 
     * @param int $createDate Unix timestamp
     */
    public function rotateTime($createDate)
    {
        if ($this->readonly) {
            return;
        }

        // Prepare date
        $date = new \DateTime();
        $date->setTimestamp($createDate);

        // Delete entries
        $queryBuilder = $this->entityManager->createQueryBuilder();
        $queryBuilder->delete('Sso\WebserviceBundle\Entity\ServiceProvider\Type\TokenUsage', 'l')->andWhere($queryBuilder->expr()->lt('l.Date', ':createdDate'));
        $this->entityManager->createQuery($queryBuilder)
            ->setParameter('createdDate', $date->format('Y-m-d H:i:s'))
            ->execute();
    }
}
