Passed
Push — master ( bb9381...992d6d )
by Alexander
08:39
created

FileRotator::setMaxFileSize()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 8
Code Lines 4

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 5
CRAP Score 2

Importance

Changes 0
Metric Value
cc 2
eloc 4
c 0
b 0
f 0
nc 2
nop 1
dl 0
loc 8
rs 10
ccs 5
cts 5
cp 1
crap 2
1
<?php
2
3
declare(strict_types=1);
4
5
namespace Yiisoft\Log\Target\File;
6
7
/**
8
 * FileRotator takes care of rotating files.
9
 *
10
 * If the size of the file exceeds {@see maxFileSize} (in kilo-bytes), a rotation will be performed, which renames
11
 * the current file by suffixing the file name with '.1'.
12
 *
13
 * All existing files are moved backwards by one place, i.e., '.2' to '.3', '.1' to '.2', and so on.
14
 * The property {@see maxFiles} specifies how many history files to keep.
15
 */
16
class FileRotator implements FileRotatorInterface
17
{
18
    /**
19
     * @var int maximum file size, in kilo-bytes. Defaults to 10240, meaning 10MB.
20
     */
21
    private int $maxFileSize;
22
    /**
23
     * @var int number of files used for rotation. Defaults to 5.
24
     */
25
    private int $maxFiles;
26
    /**
27
     * @var int|null the permission to be set for newly created files.
28
     * This value will be used by PHP chmod() function. No umask will be applied.
29
     * If not set, the permission will be determined by the current environment.
30
     */
31
    private ?int $fileMode;
32
    /**
33
     * @var bool|null Whether to rotate files by copy and truncate in contrast to rotation by
34
     * renaming files. Defaults to `true` to be more compatible with log tailers and is windows
35
     * systems which do not play well with rename on open files. Rotation by renaming however is
36
     * a bit faster.
37
     *
38
     * The problem with windows systems where the [rename()](http://www.php.net/manual/en/function.rename.php)
39
     * function does not work with files that are opened by some process is described in a
40
     * [comment by Martin Pelletier](http://www.php.net/manual/en/function.rename.php#102274) in
41
     * the PHP documentation. By setting rotateByCopy to `true` you can work
42
     * around this problem.
43
     */
44
    private ?bool $rotateByCopy;
45
46 10
    public function __construct(int $maxFileSize = 10240, int $maxFiles = 5, int $fileMode = null, bool $rotateByCopy = null)
47
    {
48 10
        $this->setMaxFileSize($maxFileSize);
49 8
        $this->setMaxFiles($maxFiles);
50 8
        $this->fileMode = $fileMode;
51
52 8
        $this->rotateByCopy = $rotateByCopy ?? $this->isRunningOnWindows();
53
    }
54
55
    /**
56
     * Sets the value of maxFileSize.
57
     * @param int $maxFileSize
58
     * @return FileRotator
59
     */
60 10
    public function setMaxFileSize(int $maxFileSize): self
61
    {
62 10
        $this->maxFileSize = $maxFileSize;
63 10
        if ($this->maxFileSize < 1) {
64 3
            throw new \InvalidArgumentException('The argument $maxFileSize cannot be lower than 1');
65
        }
66
67 8
        return $this;
68
    }
69
70 5
    public function getMaxFileSize(): int
71
    {
72 5
        return $this->maxFileSize;
73
    }
74
75
    /**
76
     * Sets the value of maxFiles.
77
     *
78
     * @param int $maxFiles
79
     * @return $this
80
     */
81 8
    public function setMaxFiles(int $maxFiles): self
82
    {
83 8
        $this->maxFiles = $maxFiles;
84 8
        if ($this->maxFiles < 1) {
85 1
            throw new \InvalidArgumentException('The argument $maxFiles cannot be lower than 1');
86
        }
87
88 8
        return $this;
89
    }
90
91
    /**
92
     * Gets the value of maxFiles.
93
     * @return int
94
     */
95 1
    public function getMaxFiles(): int
96
    {
97 1
        return $this->maxFiles;
98
    }
99
100 3
    public function rotateFile(string $file): void
101
    {
102 3
        for ($i = $this->maxFiles; $i >= 0; --$i) {
103
            // $i == 0 is the original file
104 3
            $rotateFile = $file . ($i === 0 ? '' : '.' . $i);
105 3
            if (is_file($rotateFile)) {
106
                // suppress errors because it's possible multiple processes enter into this section
107 3
                if ($i === $this->maxFiles) {
108 1
                    @unlink($rotateFile);
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

108
                    /** @scrutinizer ignore-unhandled */ @unlink($rotateFile);

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...
109 1
                    continue;
110
                }
111 3
                $newFile = $file . '.' . ($i + 1);
112 3
                if ($this->rotateByCopy) {
113 2
                    $this->rotateByCopy($rotateFile, $newFile);
114
                } else {
115 1
                    $this->rotateByRename($rotateFile, $newFile);
116
                }
117
118 3
                if ($i === 0) {
119 3
                    $this->clearFile($rotateFile);
120
                }
121
            }
122
        }
123
    }
124
125
    /***
126
     * Clears the file without closing any other process open handles
127
     * @param string $rotateFile
128
     */
129 3
    private function clearFile(string $rotateFile): void
130
    {
131 3
        if ($filePointer = @fopen($rotateFile, 'ab')) {
132 3
            @ftruncate($filePointer, 0);
0 ignored issues
show
Security Best Practice introduced by
It seems like you do not handle an error condition for ftruncate(). 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

132
            /** @scrutinizer ignore-unhandled */ @ftruncate($filePointer, 0);

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...
133 3
            @fclose($filePointer);
0 ignored issues
show
Security Best Practice introduced by
It seems like you do not handle an error condition for fclose(). 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

133
            /** @scrutinizer ignore-unhandled */ @fclose($filePointer);

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...
134
        }
135
    }
136
137
    /***
138
     * Copy rotated file into new file
139
     * @param string $rotateFile
140
     * @param string $newFile
141
     */
142 2
    private function rotateByCopy(string $rotateFile, string $newFile): void
143
    {
144 2
        @copy($rotateFile, $newFile);
0 ignored issues
show
Security Best Practice introduced by
It seems like you do not handle an error condition for copy(). 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

144
        /** @scrutinizer ignore-unhandled */ @copy($rotateFile, $newFile);

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...
145 2
        if ($this->fileMode !== null) {
146 1
            @chmod($newFile, $this->fileMode);
0 ignored issues
show
Security Best Practice introduced by
It seems like you do not handle an error condition for chmod(). 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

146
            /** @scrutinizer ignore-unhandled */ @chmod($newFile, $this->fileMode);

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...
147
        }
148
    }
149
150
    /**
151
     * Renames rotated file into new file
152
     * @param string $rotateFile
153
     * @param string $newFile
154
     */
155 1
    private function rotateByRename(string $rotateFile, string $newFile): void
156
    {
157 1
        @rename($rotateFile, $newFile);
0 ignored issues
show
Security Best Practice introduced by
It seems like you do not handle an error condition for rename(). 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

157
        /** @scrutinizer ignore-unhandled */ @rename($rotateFile, $newFile);

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...
158
    }
159
160 4
    private function isRunningOnWindows(): bool
161
    {
162 4
        return DIRECTORY_SEPARATOR === '\\';
163
    }
164
}
165