View source
<?php
namespace Drupal\filelog;
use Drupal\Component\Datetime\TimeInterface;
use Drupal\Component\Render\PlainTextOutput;
use Drupal\Core\Config\ConfigFactoryInterface;
use Drupal\Core\File\FileSystemInterface;
use Drupal\Core\State\StateInterface;
use Drupal\Core\Utility\Token;
use function date;
use function dirname;
use function fclose;
use function file_get_contents;
use function file_put_contents;
use function fopen;
use function gzencode;
use function rename;
class LogRotator {
protected $config;
protected $state;
protected $token;
protected $time;
protected $fileManager;
protected $fileSystem;
public function __construct(ConfigFactoryInterface $configFactory, StateInterface $state, Token $token, TimeInterface $time, LogFileManagerInterface $fileManager, FileSystemInterface $fileSystem) {
$this->config = $configFactory
->get('filelog.settings');
$this->state = $state;
$this->token = $token;
$this->time = $time;
$this->fileManager = $fileManager;
$this->fileSystem = $fileSystem;
}
public function run($force = FALSE) : bool {
if ($force || $this
->shouldRun($this->time
->getRequestTime())) {
return $this
->rotateFile();
}
return FALSE;
}
public function shouldRun($now) : bool {
$last = $this->state
->get('filelog.rotation');
switch ($this->config
->get('rotation.schedule')) {
case 'monthly':
return date('m', $last) !== date('m', $now);
case 'weekly':
return date('W', $last) !== date('W', $now);
case 'daily':
return date('d', $last) !== date('d', $now);
}
return FALSE;
}
protected function rotateFile() : bool {
$logFile = $this->fileManager
->getFileName();
$truncate = $this->config
->get('rotation.delete');
$timestamp = $this->state
->get('filelog.rotation');
if (!$truncate) {
$destination = $this->token
->replace($this->config
->get('rotation.destination'), [
'date' => $timestamp,
]);
$destination = PlainTextOutput::renderFromHtml($destination);
$destination = $this->config
->get('location') . '/' . $destination;
$directory = dirname($destination);
$this->fileSystem
->prepareDirectory($directory, $this->fileSystem::CREATE_DIRECTORY);
if ($this->config
->get('rotation.gzip')) {
$truncate = TRUE;
$data = file_get_contents($logFile);
if (!file_put_contents($destination . '.gz', gzencode($data))) {
throw new FileLogException("Log file could not be compressed from {$logFile} to {$destination}.gz.");
}
}
elseif (!rename($logFile, $destination)) {
throw new FileLogException("Log file could not be moved from {$logFile} to {$destination}.");
}
}
if ($truncate) {
$file = fopen($logFile, 'wb');
if (!$file || !fclose($file)) {
throw new FileLogException("Log file {$logFile} could not be truncated.");
}
}
$this->state
->set('filelog.rotation', $this->time
->getRequestTime());
return TRUE;
}
}