Passed
Pull Request — master (#37)
by Wilmer
20:16 queued 08:06
created

FileRotator::isRunningOnWindows()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 3
Code Lines 1

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 2
CRAP Score 1

Importance

Changes 0
Metric Value
cc 1
eloc 1
c 0
b 0
f 0
nc 1
nop 0
dl 0
loc 3
rs 10
ccs 2
cts 2
cp 1
crap 1
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 copy;
13
use function extension_loaded;
14
use function fclose;
15
use function feof;
16
use function file_exists;
17
use function filesize;
18
use function flock;
19
use function fread;
20
use function ftruncate;
21
use function is_file;
22
use function rename;
23
use function sprintf;
24
use function substr;
25
use function unlink;
26
27
use const DIRECTORY_SEPARATOR;
28
use const LOCK_EX;
29
use const LOCK_SH;
30
use const LOCK_UN;
31
32
/**
33
 * FileRotator takes care of rotating files.
34
 *
35
 * If the size of the file exceeds {@see FileRotator::$maxFileSize} (in kilo-bytes),
36
 * a rotation will be performed, which renames the current file by suffixing the file name with '.1'.
37
 *
38
 * All existing files are moved backwards by one place, i.e., '.2' to '.3', '.1' to '.2', and so on. If compression
39
 * is enabled {@see FileRotator::$compressRotatedFiles}, the rotated files will be compressed into the '.gz' format.
40
 * The property {@see FileRotator::$maxFiles} specifies how many history files to keep.
41
 */
42
final class FileRotator implements FileRotatorInterface
43
{
44
    /**
45
     * The extension of the compressed rotated files.
46
     */
47
    private const COMPRESS_EXTENSION = '.gz';
48
49
    /**
50
     * @var int The maximum file size, in kilo-bytes. Defaults to 10240, meaning 10MB.
51
     */
52
    private int $maxFileSize;
53
54
    /**
55
     * @var int The number of files used for rotation. Defaults to 5.
56
     */
57
    private int $maxFiles;
58
59
    /**
60
     * @var int|null The permission to be set for newly created files.
61
     * This value will be used by PHP chmod() function. No umask will be applied.
62
     * If not set, the permission will be determined by the current environment.
63
     */
64
    private ?int $fileMode;
65
66
    /**
67
     * @var bool|null Whether to rotate files by copy and truncate in contrast to rotation by renaming files.
68
     * Defaults to `true` for Windows systems that do not play well with rename on open files.
69
     * The default for other systems is `false`, as rotation by renaming is slightly faster.
70
     *
71
     * The problem with windows systems where the [rename()](http://www.php.net/manual/en/function.rename.php)
72
     * function does not work with files that are opened by some process is described in a
73
     * [comment by Martin Pelletier](http://www.php.net/manual/en/function.rename.php#102274) in
74
     * the PHP documentation. By setting `rotateByCopy` to `true` you can work around this problem.
75
     */
76
    private ?bool $rotateByCopy;
77
78
    /**
79
     * @var bool Whether to compress rotated files with gzip. Defaults to `false`.
80
     *
81
     * If compression is enabled, the rotated files will be compressed into the '.gz' format.
82
     */
83
    private bool $compressRotatedFiles;
84
85
    /**
86
     * @param int $maxFileSize The maximum file size, in kilo-bytes. Defaults to 10240, meaning 10MB.
87
     * @param int $maxFiles The number of files used for rotation. Defaults to 5.
88
     * @param int|null $fileMode The permission to be set for newly created files.
89
     * @param bool|null $rotateByCopy Whether to rotate files by copying and truncating or renaming them.
90
     * @param bool $compressRotatedFiles Whether to compress rotated files with gzip.
91
     */
92 15
    public function __construct(
93
        int $maxFileSize = 10240,
94
        int $maxFiles = 5,
95
        int $fileMode = null,
96
        bool $rotateByCopy = null,
97
        bool $compressRotatedFiles = false
98
    ) {
99 15
        $this->checkCannotBeLowerThanOne($maxFileSize, '$maxFileSize');
100 14
        $this->checkCannotBeLowerThanOne($maxFiles, '$maxFiles');
101
102 13
        $this->maxFileSize = $maxFileSize;
103 13
        $this->maxFiles = $maxFiles;
104 13
        $this->fileMode = $fileMode;
105 13
        $this->rotateByCopy = $rotateByCopy ?? $this->isRunningOnWindows();
106
107 13
        if ($compressRotatedFiles && !extension_loaded('zlib')) {
108
            throw new RuntimeException(sprintf(
109
                'The %s requires the PHP extension "ext-zlib" to compress rotated files.',
110
                self::class,
111
            ));
112
        }
113
114 13
        $this->compressRotatedFiles = $compressRotatedFiles;
115
    }
116
117 8
    public function rotateFile(string $file): void
118
    {
119 8
        for ($i = $this->maxFiles; $i >= 0; --$i) {
120
            // `$i === 0` is the original file
121 8
            $rotateFile = $file . ($i === 0 ? '' : '.' . $i);
122 8
            $newFile = $file . '.' . ($i + 1);
123
124 8
            if ($i === $this->maxFiles) {
125 8
                $this->safeRemove($this->compressRotatedFiles ? $rotateFile . self::COMPRESS_EXTENSION : $rotateFile);
126 8
                continue;
127
            }
128
129 8
            if ($this->compressRotatedFiles && is_file($rotateFile . self::COMPRESS_EXTENSION)) {
130 2
                $this->rotate($rotateFile . self::COMPRESS_EXTENSION, $newFile . self::COMPRESS_EXTENSION);
131 2
                continue;
132
            }
133
134 8
            if (!is_file($rotateFile)) {
135 8
                continue;
136
            }
137
138 8
            $this->rotate($rotateFile, $newFile);
139
140 8
            if ($i === 0) {
141 8
                $this->clear($rotateFile);
142
            }
143
        }
144
    }
145
146 13
    public function shouldRotateFile(string $file): bool
147
    {
148 13
        return file_exists($file) && @filesize($file) > ($this->maxFileSize * 1024);
149
    }
150
151
    /***
152
     * Copies or renames rotated file into new file.
153
     *
154
     * @param string $rotateFile
155
     * @param string $newFile
156
     */
157 8
    private function rotate(string $rotateFile, string $newFile): void
158
    {
159 8
        if ($this->rotateByCopy === true) {
160 4
            copy($rotateFile, $newFile);
161
        } else {
162 4
            $this->safeRemove($newFile);
163 4
            rename($rotateFile, $newFile);
164
        }
165
166 8
        if ($this->compressRotatedFiles && !$this->isCompressed($newFile)) {
167 4
            $this->compress($newFile);
168 4
            $newFile .= self::COMPRESS_EXTENSION;
169
        }
170
171 8
        if ($this->fileMode !== null) {
172 4
            chmod($newFile, $this->fileMode);
173
        }
174
    }
175
176
    /**
177
     * Compresses a file with gzip and renames it by appending `.gz` to the file.
178
     *
179
     * @param string $file
180
     */
181 4
    private function compress(string $file): void
182
    {
183 4
        $filePointer = FileHelper::openFile($file, 'rb');
184 4
        flock($filePointer, LOCK_SH);
185 4
        $gzFile = $file . self::COMPRESS_EXTENSION;
186 4
        $gzFilePointer = gzopen($gzFile, 'wb9');
187
188 4
        while (!feof($filePointer)) {
189 4
            gzwrite($gzFilePointer, fread($filePointer, 8192));
190
        }
191
192 4
        flock($filePointer, LOCK_UN);
193 4
        fclose($filePointer);
194 4
        gzclose($gzFilePointer);
195 4
        @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

195
        /** @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...
196
    }
197
198
    /***
199
     * Clears the file without closing any other process open handles.
200
     *
201
     * @param string $file
202
     */
203 8
    private function clear(string $file): void
204
    {
205 8
        $filePointer = FileHelper::openFile($file, 'ab');
206
207 8
        flock($filePointer, LOCK_EX);
208 8
        ftruncate($filePointer, 0);
209 8
        flock($filePointer, LOCK_UN);
210 8
        fclose($filePointer);
211
    }
212
213
    /**
214
     * Checks the existence of file and removes it.
215
     *
216
     * @param string $file
217
     */
218 8
    private function safeRemove(string $file): void
219
    {
220 8
        if (is_file($file)) {
221 4
            @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

221
            /** @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...
222
        }
223
    }
224
225
    /**
226
     * Whether the file is compressed.
227
     *
228
     * @param string $file
229
     *
230
     * @return bool
231
     */
232 4
    private function isCompressed(string $file): bool
233
    {
234 4
        return substr($file, -3, 3) === self::COMPRESS_EXTENSION;
235
    }
236
237
    /**
238
     * Whether it works on Windows OS.
239
     *
240
     * @return bool
241
     */
242 1
    private function isRunningOnWindows(): bool
243
    {
244 1
        return DIRECTORY_SEPARATOR === '\\';
245
    }
246
247
    /**
248
     * Checks that the value cannot be lower than one.
249
     *
250
     * @param int $value The value to be checked.
251
     * @param string $argumentName The name of the argument to check.
252
     */
253 15
    private function checkCannotBeLowerThanOne(int $value, string $argumentName): void
254
    {
255 15
        if ($value < 1) {
256 2
            throw new InvalidArgumentException(sprintf(
257
                'The argument "%s" cannot be lower than 1.',
258
                $argumentName,
259
            ));
260
        }
261
    }
262
}
263