<?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\DbLogBundle\Logger;

use Doctrine\ORM\EntityManager;
use LifeStyle\Tools\DbLogBundle\Exception\NotImplementedException;

/**
 * Class LogrotateHandler
 * @package LifeStyle\Tools\DbLogBundle\Logger
 */
class LogrotateHandler
{
    /**
     * @var \Doctrine\ORM\EntityManager
     */
    private $entityManager;

    /**
     * @param EntityManager $entityManager
     */
    public function __construct(EntityManager $entityManager)
    {
        $this->entityManager = $entityManager;
    }

    /**
     * @param int $createTime
     */
    public function rotateTime($createTime)
    {
        $queryBuilder = $this->entityManager->createQueryBuilder();
        $queryBuilder->delete('LifeStyle\Tools\DbLogBundle\Entity\SystemLog', 'l')
            ->andWhere($queryBuilder->expr()->lt('l.createdTime', ':createdTime'));
        // createdTime is microtime(true) * 10
        $this->entityManager->createQuery($queryBuilder)->setParameter('createdTime', $createTime * 10)->execute();
    }

    /**
     * Do log rotate - Shrink down log to $size number of entries
     * @param int $size
     */
    public function rotateSize($size)
    {
        throw new NotImplementedException('DB-logrotate with size limit not implemented yet. As "DELETE FROM table LIMIT lim" is not supported by some databases, it may need some more effort, to develop.');
    }
}
