Passed
Pull Request — master (#47)
by Sergei
02:54 queued 31s
created

FileRotator::rotate()   A

Complexity

Conditions 4
Paths 4

Size

Total Lines 12
Code Lines 7

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 8
CRAP Score 4

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 4
eloc 7
c 1
b 0
f 0
nc 4
nop 2
dl 0
loc 12
ccs 8
cts 8
cp 1
crap 4
rs 10
1
<?php
2
3
declare(strict_types=1);
4
5
namespace Yiisoft\Log\Target\File;
6
7
use InvalidArgumentException;
8
use RuntimeException;
9
use Yiisoft\Files\FileHelper;
10
11
use function chmod;
12
use function extension_loaded;
13
use function fclose;
14
use function feof;
15
use function file_exists;
16
use function filesize;
17
use function flock;
18
use function fread;
19
use function ftruncate;
20
use function is_file;
21
use function rename;
22
use function sprintf;
23
use function substr;
24
use function unlink;
25
26
use const LOCK_EX;
27
use const LOCK_SH;
28
use const LOCK_UN;
29
30
/**
31
 * FileRotator takes care of rotating files.
32
 *
33
 * If the size of the file exceeds {@see FileRotator::$maxFileSize} (in kilo-bytes),
34
 * a rotation will be performed, which renames the current file by suffixing the file name with '.1'.
35
 *
36
 * All existing files are moved backwards by one place, i.e., '.2' to '.3', '.1' to '.2', and so on. If compression
37
 * is enabled {@see FileRotator::$compressRotatedFiles}, the rotated files will be compressed into the '.gz' format.
38
 * The property {@see FileRotator::$maxFiles} specifies how many history files to keep.
39
 */
40
final class FileRotator implements FileRotatorInterface
41
{
42
    /**
43
     * The extension of the compressed rotated files.
44
     */
45
    private const COMPRESS_EXTENSION = '.gz';
46
47
    /**
48
     * @var int The maximum file size, in kilo-bytes. Defaults to 10240, meaning 10MB.
49
     */
50
    private int $maxFileSize;
51
52
    /**
53
     * @var int The number of files used for rotation. Defaults to 5.
54
     */
55
    private int $maxFiles;
56
57
    /**
58
     * @var bool Whether to compress rotated files with gzip. Defaults to `false`.
59
     *
60
     * If compression is enabled, the rotated files will be compressed into the '.gz' format.
61
     */
62
    private bool $compressRotatedFiles;
63
64
    /**
65
     * @param int $maxFileSize The maximum file size, in kilo-bytes. Defaults to 10240, meaning 10MB.
66
     * @param int $maxFiles The number of files used for rotation. Defaults to 5.
67
     * @param int|null $fileMode The permission to be set for newly created files.
68
     * @param bool $compressRotatedFiles Whether to compress rotated files with gzip.
69
     */
70 10
    public function __construct(
71
        int $maxFileSize = 10240,
72
        int $maxFiles = 5,
73
        private ?int $fileMode = null,
74
        bool $compressRotatedFiles = false
75
    ) {
76 10
        $this->checkCannotBeLowerThanOne($maxFileSize, '$maxFileSize');
77 9
        $this->checkCannotBeLowerThanOne($maxFiles, '$maxFiles');
78
79 8
        $this->maxFileSize = $maxFileSize;
80 8
        $this->maxFiles = $maxFiles;
81
82 8
        if ($compressRotatedFiles && !extension_loaded('zlib')) {
83
            throw new RuntimeException(sprintf(
84
                'The %s requires the PHP extension "ext-zlib" to compress rotated files.',
85
                self::class,
86
            ));
87
        }
88
89 8
        $this->compressRotatedFiles = $compressRotatedFiles;
90
    }
91
92 4
    public function rotateFile(string $file): void
93
    {
94 4
        for ($i = $this->maxFiles; $i >= 0; --$i) {
95
            // `$i === 0` is the original file
96 4
            $rotateFile = $file . ($i === 0 ? '' : '.' . $i);
97 4
            $newFile = $file . '.' . ($i + 1);
98
99 4
            if ($i === $this->maxFiles) {
100 4
                $this->safeRemove($this->compressRotatedFiles ? $rotateFile . self::COMPRESS_EXTENSION : $rotateFile);
101 4
                continue;
102
            }
103
104 4
            if ($this->compressRotatedFiles && is_file($rotateFile . self::COMPRESS_EXTENSION)) {
105 1
                $this->rotate($rotateFile . self::COMPRESS_EXTENSION, $newFile . self::COMPRESS_EXTENSION);
106 1
                continue;
107
            }
108
109 4
            if (!is_file($rotateFile)) {
110 4
                continue;
111
            }
112
113 4
            $this->rotate($rotateFile, $newFile);
114
115 4
            if ($i === 0) {
116 4
                $this->clear($rotateFile);
117
            }
118
        }
119
    }
120
121 7
    public function shouldRotateFile(string $file): bool
122
    {
123 7
        return file_exists($file) && @filesize($file) > ($this->maxFileSize * 1024);
124
    }
125
126
    /***
127
     * Renames rotated file into new file.
128
     *
129
     * @param string $rotateFile
130
     * @param string $newFile
131
     */
132 4
    private function rotate(string $rotateFile, string $newFile): void
133
    {
134 4
        $this->safeRemove($newFile);
135 4
        rename($rotateFile, $newFile);
136
137 4
        if ($this->compressRotatedFiles && !$this->isCompressed($newFile)) {
138 2
            $this->compress($newFile);
139 2
            $newFile .= self::COMPRESS_EXTENSION;
140
        }
141
142 4
        if ($this->fileMode !== null) {
143 2
            chmod($newFile, $this->fileMode);
144
        }
145
    }
146
147
    /**
148
     * Compresses a file with gzip and renames it by appending `.gz` to the file.
149
     */
150 2
    private function compress(string $file): void
151
    {
152 2
        $filePointer = FileHelper::openFile($file, 'rb');
153 2
        flock($filePointer, LOCK_SH);
154 2
        $gzFile = $file . self::COMPRESS_EXTENSION;
155 2
        $gzFilePointer = gzopen($gzFile, 'wb9');
156
157 2
        while (!feof($filePointer)) {
158 2
            gzwrite($gzFilePointer, fread($filePointer, 8192));
159
        }
160
161 2
        flock($filePointer, LOCK_UN);
162 2
        fclose($filePointer);
163 2
        gzclose($gzFilePointer);
164 2
        @unlink($file);
0 ignored issues
show
Security Best Practice introduced by
It seems like you do not handle an error condition for unlink(). This can introduce security issues, and is generally not recommended. ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-unhandled  annotation

164
        /** @scrutinizer ignore-unhandled */ @unlink($file);

If you suppress an error, we recommend checking for the error condition explicitly:

// For example instead of
@mkdir($dir);

// Better use
if (@mkdir($dir) === false) {
    throw new \RuntimeException('The directory '.$dir.' could not be created.');
}
Loading history...
165
    }
166
167
    /***
168
     * Clears the file without closing any other process open handles.
169
     *
170
     * @param string $file
171
     */
172 4
    private function clear(string $file): void
173
    {
174 4
        $filePointer = FileHelper::openFile($file, 'ab');
175
176 4
        flock($filePointer, LOCK_EX);
177 4
        ftruncate($filePointer, 0);
178 4
        flock($filePointer, LOCK_UN);
179 4
        fclose($filePointer);
180
    }
181
182
    /**
183
     * Checks the existence of file and removes it.
184
     */
185 4
    private function safeRemove(string $file): void
186
    {
187 4
        if (is_file($file)) {
188 2
            @unlink($file);
0 ignored issues
show
Security Best Practice introduced by
It seems like you do not handle an error condition for unlink(). This can introduce security issues, and is generally not recommended. ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-unhandled  annotation

188
            /** @scrutinizer ignore-unhandled */ @unlink($file);

If you suppress an error, we recommend checking for the error condition explicitly:

// For example instead of
@mkdir($dir);

// Better use
if (@mkdir($dir) === false) {
    throw new \RuntimeException('The directory '.$dir.' could not be created.');
}
Loading history...
189
        }
190
    }
191
192
    /**
193
     * Whether the file is compressed.
194
     */
195 2
    private function isCompressed(string $file): bool
196
    {
197 2
        return substr($file, -3, 3) === self::COMPRESS_EXTENSION;
198
    }
199
200
    /**
201
     * Checks that the value cannot be lower than one.
202
     *
203
     * @param int $value The value to be checked.
204
     * @param string $argumentName The name of the argument to check.
205
     */
206 10
    private function checkCannotBeLowerThanOne(int $value, string $argumentName): void
207
    {
208 10
        if ($value < 1) {
209 2
            throw new InvalidArgumentException(sprintf(
210 2
                'The argument "%s" cannot be lower than 1.',
211 2
                $argumentName,
212 2
            ));
213
        }
214
    }
215
}
216