<?php

namespace RxConnexionBundle\EventListener;

use Symfony\Component\HttpKernel\Event\GetResponseEvent;
use Symfony\Component\DependencyInjection\ContainerInterface;

class HttpRequestEventListener {

    protected $container;

    public function __construct(ContainerInterface $container)
    {
        $this->container = $container;
    }

    public function onKernelRequest(GetResponseEvent $event)
    {
        $request = $event->getRequest();
        $requestUri = $request->getRequestUri();
        $pos = strpos($requestUri, '?');
        if(FALSE !== $pos) {
            $requestUri = substr($requestUri, 0, $pos);
        }
        $logData = sprintf("[%s] %s %s %s", date('Y-m-d H:i:s'), $request->getClientIp(), $request->getMethod(), $requestUri);
        $logName = 'http_requests.log';
        $logAbsPath = $this->container->getParameter('http_request_log_dir');
        $logFullPath = $logAbsPath . '/' . $logName;

        if(file_exists($logFullPath)) {
            $logFile = fopen($logFullPath, "a+");
            fwrite($logFile, PHP_EOL . $logData);
        } else {
            $logFile = fopen($logFullPath, "w");
            fwrite($logFile, $logData);
        }
        fclose($logFile);

        $logSize = filesize($logFullPath);
        if($logSize >= $this->container->getParameter('http_request_log_max_size')) {
            rename($logFullPath, $logAbsPath . '/' . $logName . '-' . date('Y-m-d-H-i-s') . '.log');
        }
    }
}