Passed
Pull Request — master (#7)
by Alexander
01:20
created

FileRotator::getMaxFileSize()   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
nc 1
nop 0
dl 0
loc 3
ccs 2
cts 2
cp 1
crap 1
rs 10
c 0
b 0
f 0
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 [[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 [[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 18
    public function __construct(int $maxFileSize = 10240, int $maxFiles = 5, int $fileMode = null, bool $rotateByCopy = null)
47
    {
48 18
        $this->setMaxFileSize($maxFileSize);
49 18
        $this->setMaxFiles($maxFiles);
50 18
        $this->fileMode = $fileMode;
51
52 18
        $this->rotateByCopy = $rotateByCopy ?? $this->isRunningOnWindows();
53
    }
54
55
    /**
56
     * Sets the value of maxFileSize.
57
     * @param int $maxFileSize
58
     * @return FileRotator
59
     */
60 18
    public function setMaxFileSize(int $maxFileSize): self
61
    {
62 18
        $this->maxFileSize = $maxFileSize;
63 18
        if ($this->maxFileSize < 1) {
64 3
            $this->maxFileSize = 1;
65
        }
66
67 18
        return $this;
68
    }
69
70
    /**
71
     * @inheritDoc
72
     */
73 15
    public function getMaxFileSize(): int
74
    {
75 15
        return $this->maxFileSize;
76
    }
77
78
    /**
79
     * Sets the value of maxFiles.
80
     *
81
     * @param int $maxFiles
82
     * @return FileRotator
83
     */
84 18
    public function setMaxFiles(int $maxFiles): self
85
    {
86 18
        $this->maxFiles = $maxFiles;
87 18
        if ($this->maxFiles < 1) {
88 2
            $this->maxFiles = 1;
89
        }
90
91 18
        return $this;
92
    }
93
94
    /**
95
     * Gets the value of maxFiles.
96
     * @return int
97
     */
98 3
    public function getMaxFiles(): int
99
    {
100 3
        return $this->maxFiles;
101
    }
102
103
    /**
104
     * @inheritDoc
105
     */
106 7
    public function rotateFile(string $file): void
107
    {
108 7
        for ($i = $this->maxFiles; $i >= 0; --$i) {
109
            // $i == 0 is the original file
110 7
            $rotateFile = $file . ($i === 0 ? '' : '.' . $i);
111 7
            if (is_file($rotateFile)) {
112
                // suppress errors because it's possible multiple processes enter into this section
113 7
                if ($i === $this->maxFiles) {
114 5
                    @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

114
                    /** @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...
115 5
                    continue;
116
                }
117 7
                $newFile = $file . '.' . ($i + 1);
118 7
                if ($this->rotateByCopy) {
119 6
                    $this->rotateByCopy($rotateFile, $newFile);
120
                } else {
121 1
                    $this->rotateByRename($rotateFile, $newFile);
122
                }
123
124 7
                if ($i === 0) {
125 7
                    $this->clearFile($rotateFile);
126
                }
127
            }
128
        }
129
    }
130
131
    /***
132
     * Clears the file without closing any other process open handles
133
     * @param string $rotateFile
134
     */
135 7
    private function clearFile(string $rotateFile): void
136
    {
137 7
        if ($filePointer = @fopen($rotateFile, 'ab')) {
138 7
            @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

138
            /** @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...
139 7
            @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

139
            /** @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...
140
        }
141
    }
142
143
    /***
144
     * Copy rotated file into new file
145
     * @param string $rotateFile
146
     * @param string $newFile
147
     */
148 6
    private function rotateByCopy(string $rotateFile, string $newFile): void
149
    {
150 6
        @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

150
        /** @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...
151 6
        if ($this->fileMode !== null) {
152 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

152
            /** @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...
153
        }
154
    }
155
156
    /**
157
     * Renames rotated file into new file
158
     * @param string $rotateFile
159
     * @param string $newFile
160
     */
161 1
    private function rotateByRename(string $rotateFile, string $newFile): void
162
    {
163 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

163
        /** @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...
164
    }
165
166 6
    private function isRunningOnWindows(): bool
167
    {
168 6
        return DIRECTORY_SEPARATOR === '\\';
169
    }
170
}
171