Passed
Pull Request — master (#19492)
by Paweł
11:10 queued 03:04
created

FileTarget::rotateByRename()   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 2
dl 0
loc 3
ccs 2
cts 2
cp 1
crap 1
rs 10
c 0
b 0
f 0
1
<?php
2
/**
3
 * @link http://www.yiiframework.com/
4
 * @copyright Copyright (c) 2008 Yii Software LLC
5
 * @license http://www.yiiframework.com/license/
6
 */
7
8
namespace yii\log;
9
10
use Yii;
11
use yii\base\InvalidConfigException;
12
use yii\helpers\FileHelper;
13
14
/**
15
 * FileTarget records log messages in a file.
16
 *
17
 * The log file is specified via [[logFile]]. If the size of the log file exceeds
18
 * [[maxFileSize]] (in kilo-bytes), a rotation will be performed, which renames
19
 * the current log file by suffixing the file name with '.1'. All existing log
20
 * files are moved backwards by one place, i.e., '.2' to '.3', '.1' to '.2', and so on.
21
 * The property [[maxLogFiles]] specifies how many history files to keep.
22
 *
23
 * Since 2.0.46 rotation of the files is done only by copy and property `rotateByCopy` is deprecated.
24
 *
25
 * @author Qiang Xue <[email protected]>
26
 * @since 2.0
27
 */
28
class FileTarget extends Target
29
{
30
    /**
31
     * @var string|null log file path or [path alias](guide:concept-aliases). If not set, it will use the "@runtime/logs/app.log" file.
32
     * The directory containing the log files will be automatically created if not existing.
33
     */
34
    public $logFile;
35
    /**
36
     * @var bool whether log files should be rotated when they reach a certain [[maxFileSize|maximum size]].
37
     * Log rotation is enabled by default. This property allows you to disable it, when you have configured
38
     * an external tools for log rotation on your server.
39
     * @since 2.0.3
40
     */
41
    public $enableRotation = true;
42
    /**
43
     * @var int maximum log file size, in kilo-bytes. Defaults to 10240, meaning 10MB.
44
     */
45
    public $maxFileSize = 10240; // in KB
46
    /**
47
     * @var int number of log files used for rotation. Defaults to 5.
48
     */
49
    public $maxLogFiles = 5;
50
    /**
51
     * @var int|null the permission to be set for newly created log files.
52
     * This value will be used by PHP chmod() function. No umask will be applied.
53
     * If not set, the permission will be determined by the current environment.
54
     */
55
    public $fileMode;
56
    /**
57
     * @var int the permission to be set for newly created directories.
58
     * This value will be used by PHP chmod() function. No umask will be applied.
59
     * Defaults to 0775, meaning the directory is read-writable by owner and group,
60
     * but read-only for other users.
61
     */
62
    public $dirMode = 0775;
63
    /**
64
     * @var bool Whether to rotate log files by copy and truncate in contrast to rotation by
65
     * renaming files. Defaults to `true` to be more compatible with log tailers and windows
66
     * systems which do not play well with rename on open files. Rotation by renaming however is
67
     * a bit faster.
68
     *
69
     * The problem with windows systems where the [rename()](https://www.php.net/manual/en/function.rename.php)
70
     * function does not work with files that are opened by some process is described in a
71
     * [comment by Martin Pelletier](https://www.php.net/manual/en/function.rename.php#102274) in
72
     * the PHP documentation. By setting rotateByCopy to `true` you can work around this.
73
     * @deprecated since 2.0.46 and setting it to false has no effect anymore since rotating is done only by copy
74
     */
75
    public $rotateByCopy = true;
76
77
78
    /**
79
     * Initializes the route.
80
     * This method is invoked after the route is created by the route manager.
81
     */
82 2
    public function init()
83
    {
84 2
        parent::init();
85 2
        if ($this->logFile === null) {
86
            $this->logFile = Yii::$app->getRuntimePath() . '/logs/app.log';
87
        } else {
88 2
            $this->logFile = Yii::getAlias($this->logFile);
0 ignored issues
show
Documentation Bug introduced by
It seems like Yii::getAlias($this->logFile) can also be of type false. However, the property $logFile is declared as type null|string. Maybe add an additional type check?

Our type inference engine has found a suspicous assignment of a value to a property. This check raises an issue when a value that can be of a mixed type is assigned to a property that is type hinted more strictly.

For example, imagine you have a variable $accountId that can either hold an Id object or false (if there is no account id yet). Your code now assigns that value to the id property of an instance of the Account class. This class holds a proper account, so the id value must no longer be false.

Either this assignment is in error or a type check should be added for that assignment.

class Id
{
    public $id;

    public function __construct($id)
    {
        $this->id = $id;
    }

}

class Account
{
    /** @var  Id $id */
    public $id;
}

$account_id = false;

if (starsAreRight()) {
    $account_id = new Id(42);
}

$account = new Account();
if ($account instanceof Id)
{
    $account->id = $account_id;
}
Loading history...
89
        }
90 2
        if ($this->maxLogFiles < 1) {
91
            $this->maxLogFiles = 1;
92
        }
93 2
        if ($this->maxFileSize < 1) {
94
            $this->maxFileSize = 1;
95
        }
96 2
    }
97
98
    /**
99
     * Writes log messages to a file.
100
     * Starting from version 2.0.14, this method throws LogRuntimeException in case the log can not be exported.
101
     * @throws InvalidConfigException if unable to open the log file for writing
102
     * @throws LogRuntimeException if unable to write complete log to file
103
     */
104 1
    public function export()
105
    {
106 1
        if (strpos($this->logFile, '://') === false || strncmp($this->logFile, 'file://', 7) === 0) {
0 ignored issues
show
Bug introduced by
It seems like $this->logFile can also be of type null; however, parameter $haystack of strpos() does only seem to accept string, maybe add an additional type check? ( Ignorable by Annotation )

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

106
        if (strpos(/** @scrutinizer ignore-type */ $this->logFile, '://') === false || strncmp($this->logFile, 'file://', 7) === 0) {
Loading history...
Bug introduced by
It seems like $this->logFile can also be of type null; however, parameter $string1 of strncmp() does only seem to accept string, maybe add an additional type check? ( Ignorable by Annotation )

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

106
        if (strpos($this->logFile, '://') === false || strncmp(/** @scrutinizer ignore-type */ $this->logFile, 'file://', 7) === 0) {
Loading history...
107 1
            $logPath = dirname($this->logFile);
0 ignored issues
show
Bug introduced by
It seems like $this->logFile can also be of type null; however, parameter $path of dirname() does only seem to accept string, maybe add an additional type check? ( Ignorable by Annotation )

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

107
            $logPath = dirname(/** @scrutinizer ignore-type */ $this->logFile);
Loading history...
108 1
            FileHelper::createDirectory($logPath, $this->dirMode, true);
109
        }
110
111 1
        $text = implode("\n", array_map([$this, 'formatMessage'], $this->messages)) . "\n";
112 1
        if (($fp = @fopen($this->logFile, 'a')) === false) {
0 ignored issues
show
Bug introduced by
It seems like $this->logFile can also be of type null; however, parameter $filename of fopen() does only seem to accept string, maybe add an additional type check? ( Ignorable by Annotation )

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

112
        if (($fp = @fopen(/** @scrutinizer ignore-type */ $this->logFile, 'a')) === false) {
Loading history...
113
            throw new InvalidConfigException("Unable to append to log file: {$this->logFile}");
114
        }
115 1
        @flock($fp, LOCK_EX);
0 ignored issues
show
Security Best Practice introduced by
It seems like you do not handle an error condition for flock(). 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

115
        /** @scrutinizer ignore-unhandled */ @flock($fp, LOCK_EX);

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...
116 1
        if ($this->enableRotation) {
117
            // clear stat cache to ensure getting the real current file size and not a cached one
118
            // this may result in rotating twice when cached file size is used on subsequent calls
119 1
            clearstatcache();
120
        }
121 1
        if ($this->enableRotation && @filesize($this->logFile) > $this->maxFileSize * 1024) {
0 ignored issues
show
Bug introduced by
It seems like $this->logFile can also be of type null; however, parameter $filename of filesize() does only seem to accept string, maybe add an additional type check? ( Ignorable by Annotation )

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

121
        if ($this->enableRotation && @filesize(/** @scrutinizer ignore-type */ $this->logFile) > $this->maxFileSize * 1024) {
Loading history...
122 1
            $this->rotateFiles();
123 1
            @flock($fp, LOCK_UN);
124 1
            @fclose($fp);
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

124
            /** @scrutinizer ignore-unhandled */ @fclose($fp);

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...
125 1
            $writeResult = @file_put_contents($this->logFile, $text, FILE_APPEND | LOCK_EX);
0 ignored issues
show
Bug introduced by
It seems like $this->logFile can also be of type null; however, parameter $filename of file_put_contents() does only seem to accept string, maybe add an additional type check? ( Ignorable by Annotation )

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

125
            $writeResult = @file_put_contents(/** @scrutinizer ignore-type */ $this->logFile, $text, FILE_APPEND | LOCK_EX);
Loading history...
126 1
            if ($writeResult === false) {
127
                $error = error_get_last();
128
                throw new LogRuntimeException("Unable to export log through file ({$this->logFile})!: {$error['message']}");
129
            }
130 1
            $textSize = strlen($text);
131 1
            if ($writeResult < $textSize) {
132 1
                throw new LogRuntimeException("Unable to export whole log through file ({$this->logFile})! Wrote $writeResult out of $textSize bytes.");
133
            }
134
        } else {
135 1
            $writeResult = @fwrite($fp, $text);
136 1
            if ($writeResult === false) {
137
                $error = error_get_last();
138
                throw new LogRuntimeException("Unable to export log through file ({$this->logFile})!: {$error['message']}");
139
            }
140 1
            $textSize = strlen($text);
141 1
            if ($writeResult < $textSize) {
142
                throw new LogRuntimeException("Unable to export whole log through file ({$this->logFile})! Wrote $writeResult out of $textSize bytes.");
143
            }
144 1
            @flock($fp, LOCK_UN);
145 1
            @fclose($fp);
146
        }
147 1
        if ($this->fileMode !== null) {
148
            @chmod($this->logFile, $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

148
            /** @scrutinizer ignore-unhandled */ @chmod($this->logFile, $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...
Bug introduced by
It seems like $this->logFile can also be of type null; however, parameter $filename of chmod() does only seem to accept string, maybe add an additional type check? ( Ignorable by Annotation )

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

148
            @chmod(/** @scrutinizer ignore-type */ $this->logFile, $this->fileMode);
Loading history...
149
        }
150 1
    }
151
152
    /**
153
     * Rotates log files.
154
     */
155 1
    protected function rotateFiles()
156
    {
157 1
        $file = $this->logFile;
158 1
        for ($i = $this->maxLogFiles; $i >= 0; --$i) {
159
            // $i == 0 is the original log file
160 1
            $rotateFile = $file . ($i === 0 ? '' : '.' . $i);
161 1
            if (is_file($rotateFile)) {
162
                // suppress errors because it's possible multiple processes enter into this section
163 1
                if ($i === $this->maxLogFiles) {
164 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

164
                    /** @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...
165 1
                    continue;
166
                }
167 1
                $newFile = $this->logFile . '.' . ($i + 1);
168 1
                $this->rotateByCopy($rotateFile, $newFile);
169 1
                if ($i === 0) {
170 1
                    $this->clearLogFile($rotateFile);
171
                }
172
            }
173
        }
174 1
    }
175
176
    /***
177
     * Clear log file without closing any other process open handles
178
     * @param string $rotateFile
179
     */
180 1
    private function clearLogFile($rotateFile)
181
    {
182 1
        if ($filePointer = @fopen($rotateFile, 'a')) {
183 1
            @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

183
            /** @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...
184 1
            @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

184
            /** @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...
185
        }
186 1
    }
187
188
    /***
189
     * Copy rotated file into new file
190
     * @param string $rotateFile
191
     * @param string $newFile
192
     */
193 1
    private function rotateByCopy($rotateFile, $newFile)
194
    {
195 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

195
        /** @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...
196 1
        if ($this->fileMode !== null) {
197
            @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

197
            /** @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...
198
        }
199 1
    }
200
}
201