Completed
Push — master ( 590dbb...658da2 )
by Alexander
02:01
created

FileRotator::setMaxFiles()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 8
Code Lines 4

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 6

Importance

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

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

131
            /** @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...
132 2
            @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

132
            /** @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...
133
        }
134 2
    }
135
136
    /***
137
     * Copy rotated file into new file
138
     * @param string $rotateFile
139
     * @param string $newFile
140
     * @param int|null $fileMode
141
     */
142 1
    private function rotateByCopy(string $rotateFile, string $newFile): void
143
    {
144 1
        @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 1
        if ($this->fileMode !== null) {
146
            @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 1
    }
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 1
    }
159
160
    private function isRunningOnWindows(): bool
161
    {
162
        return DIRECTORY_SEPARATOR === '\\';
163
    }
164
}
165