1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
declare(strict_types=1); |
4
|
|
|
|
5
|
|
|
namespace Moon\Logger\Handler; |
6
|
|
|
|
7
|
|
|
use DateTimeImmutable; |
8
|
|
|
use Moon\Logger\Formatter\FormatterInterface; |
9
|
|
|
|
10
|
|
|
class RotatingFileHandler implements HandlerInterface |
11
|
|
|
{ |
12
|
|
|
/** |
13
|
|
|
* @var string |
14
|
|
|
*/ |
15
|
|
|
private $filename; |
16
|
|
|
/** |
17
|
|
|
* @var \DateInterval |
18
|
|
|
*/ |
19
|
|
|
private $rotateEvery; |
20
|
|
|
/** |
21
|
|
|
* @var DateTimeImmutable |
22
|
|
|
*/ |
23
|
|
|
private $rotationStartedAt; |
24
|
|
|
/** |
25
|
|
|
* @var FormatterInterface |
26
|
|
|
*/ |
27
|
|
|
private $formatter; |
28
|
|
|
|
29
|
|
|
/** |
30
|
|
|
* @var string |
31
|
|
|
*/ |
32
|
|
|
private $defaultCurrentTime = 'now'; |
33
|
|
|
|
34
|
|
|
public function __construct(FormatterInterface $formatter, string $filename, \DateInterval $rotateEvery = null) |
35
|
|
|
{ |
36
|
|
|
$this->filename = $filename; |
37
|
|
|
$this->formatter = $formatter; |
38
|
|
|
$this->rotateEvery = $rotateEvery ?: new \DateInterval('P1D'); |
39
|
|
|
$this->rotationStartedAt = new DateTimeImmutable('now'); |
40
|
|
|
} |
41
|
3 |
|
|
42
|
|
View Code Duplication |
public function add(string $name, string $level, $message, array $context = []): void |
|
|
|
|
43
|
3 |
|
{ |
44
|
3 |
|
// Format the message |
45
|
3 |
|
$data = $this->formatter->interpolate($name, $level, $message, $context); |
46
|
3 |
|
|
47
|
3 |
|
// Push it to file |
48
|
|
|
\file_put_contents($this->getRotatedFilename(), $data.PHP_EOL, FILE_APPEND); |
49
|
|
|
} |
50
|
|
|
|
51
|
|
|
/** |
52
|
2 |
|
* Return the file name appending the $this->rotationStartedAt. |
53
|
|
|
*/ |
54
|
|
|
private function getRotatedFilename(): string |
55
|
2 |
|
{ |
56
|
|
|
// Check if a new file must be used |
57
|
|
|
$now = $this->getCurrentDateTime(); |
58
|
2 |
|
if ($now > $this->rotationStartedAt->add($this->rotateEvery)) { |
59
|
2 |
|
$this->rotationStartedAt = $now; |
60
|
|
|
} |
61
|
|
|
|
62
|
|
|
// Get file name appending data by on $this->rotationEvery |
63
|
|
|
return \preg_replace('/(^.*\/[^.\/]+)(\.[^.\/]+)?$/', "$1_{$this->rotationStartedAt->format('Y-M-d H:m:s')}$2", |
64
|
|
|
$this->filename); |
65
|
|
|
} |
66
|
3 |
|
|
67
|
|
|
/** |
68
|
|
|
* Return a current DateTime. Extracted for be easily tested. |
69
|
3 |
|
*/ |
70
|
3 |
|
private function getCurrentDateTime(): DateTimeImmutable |
71
|
1 |
|
{ |
72
|
|
|
return new DateTimeImmutable($this->defaultCurrentTime); |
73
|
|
|
} |
74
|
|
|
} |
75
|
|
|
|
Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.
You can also find more detailed suggestions in the “Code” section of your repository.