Passed
Push — master ( e61121...779b20 )
by 世昌
01:46
created

FileLogger::save()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 7
Code Lines 4

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 2
eloc 4
c 0
b 0
f 0
nc 2
nop 0
dl 0
loc 7
rs 10
1
<?php
2
namespace nebula\component\debug\log\logger;
3
4
use nebula\component\debug\log\LogLevel;
5
use nebula\component\debug\log\AbstractLogger;
6
use nebula\component\debug\log\logger\filelogger\AttachTrait;
0 ignored issues
show
Bug introduced by
The type nebula\component\debug\l...\filelogger\AttachTrait was not found. Maybe you did not declare it correctly or list all dependencies?

The issue could also be caused by a filter entry in the build configuration. If the path has been excluded in your configuration, e.g. excluded_paths: ["lib/*"], you can move it to the dependency path list as follows:

filter:
    dependency_paths: ["lib/*"]

For further information see https://scrutinizer-ci.com/docs/tools/php/php-scrutinizer/#list-dependency-paths

Loading history...
7
use nebula\component\debug\log\logger\filelogger\AttachAttribute;
0 ignored issues
show
Bug introduced by
The type nebula\component\debug\l...elogger\AttachAttribute was not found. Maybe you did not declare it correctly or list all dependencies?

The issue could also be caused by a filter entry in the build configuration. If the path has been excluded in your configuration, e.g. excluded_paths: ["lib/*"], you can move it to the dependency path list as follows:

filter:
    dependency_paths: ["lib/*"]

For further information see https://scrutinizer-ci.com/docs/tools/php/php-scrutinizer/#list-dependency-paths

Loading history...
8
9
class FileLogger extends AbstractLogger
10
{
11
12
13
    /**
14
     * 配置信息
15
     *
16
     * @var array
17
     */
18
    protected $config  = [
19
        'save-path' => './logs',
20
        'save-zip-path' => './logs/zip',
21
        'save-pack-path' => './logs/dump',
22
        'max-file-size' => 2097152,
23
        'file-name' => 'latest.log',
24
        'log-level' => 'debug',
25
        'log-format' => '[%level%] %message%',
26
    ];
27
28
    /**
29
     * 文件
30
     *
31
     * @var resource
32
     */
33
    protected $temp;
34
35
    /**
36
     * 临时文件名
37
     *
38
     * @var string
39
     */
40
    protected $tempname;
41
42
    /**
43
     * 移除文件
44
     *
45
     * @var array
46
     */
47
    protected $removeFiles = [];
48
49
    /**
50
     * 最后的日志
51
     *
52
     * @var string
53
     */
54
    protected $latest;
55
56
    public function __construct(array $config=[])
57
    {
58
        $this->applyConfig($config);
59
        $this->temp = tmpfile();
0 ignored issues
show
Documentation Bug introduced by
It seems like tmpfile() can also be of type false. However, the property $temp is declared as type resource. 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...
60
        if ($this->temp === false) {
61
            $this->tempname = $this->config['save-path'].'/log-'. microtime(true).'.tmp';
62
            $this->temp = fopen($this->tempname, 'w+');
63
        }
64
        $this->latest = $this->config['save-path'].'/'.$this->config['file-name'];
65
    }
66
67
    protected function packLogFile()
68
    {
69
        $logFile= $this->latest;
70
        $path=preg_replace('/[\\\\]+/', '/', $this->config['save-zip-path'] .'/'.date('Y-m-d').'.zip');
71
        $zip = new ZipArchive;
0 ignored issues
show
Bug introduced by
The type nebula\component\debug\log\logger\ZipArchive was not found. Did you mean ZipArchive? If so, make sure to prefix the type with \.
Loading history...
72
        $res = $zip->open($path, ZipArchive::CREATE);
73
        if ($res === true) {
74
            if ($zip->addFile($logFile, date('Y-m-d'). '-'. $zip->numFiles .'.log')) {
75
                array_push($this->removeFiles, $logFile);
76
            }
77
            $it = new \RecursiveIteratorIterator(new \RecursiveDirectoryIterator($this->config['save-pack-path']));
78
            foreach ($it as $dumpLog) {
79
                if ($zip->addFile($dumpLog, 'pack/'.basename($dumpLog))) {
80
                    array_push($this->removeFiles, $dumpLog);
81
                }
82
            }
83
            $zip->close();
84
        } else {
85
            if (is_file($logFile) && file_exists($logFile)) {
86
                rename($logFile, $this->config['save-path'] . '/' . date('Y-m-d'). '-'. substr(md5_file($logFile), 0, 8).'.log');
87
            }
88
        }
89
    }
90
91
    public function applyConfig(array $config)
92
    {
93
        foreach ($config as $name => $value) {
94
            if (in_array($name, array_keys($this->config))) {
95
                $this->config[$name] = $config[$name] ?? $this->config[$name];
96
            } else {
97
                throw new \Exception(sprintf(__CLASS__.' : unknown config property %s', $name));
98
            }
99
        }
100
    }
101
102
    /**
103
     * 检查日志文件大小
104
     *
105
     * @return boolean
106
     */
107
    protected function checkSize():bool
108
    {
109
        $logFile= $this->latest;
110
        if (file_exists($logFile)) {
111
            if (filesize($logFile) > $this->config['max-file-size']) {
112
                return true;
113
            }
114
        }
115
        return false;
116
    }
117
118
119
    public function log($level, string $message, array $context = [])
120
    {
121
        if (LogLevel::compare($level, $this->config['log-level']) >=0) {
122
            $replace = [];
123
            $message = $this->interpolate($message, $context);
124
            $replace['%level%'] = $level;
125
            $replace['%message%'] = $message;
126
            $write = \strtr($this->config['log-format'], $replace);
127
            \fwrite($this->temp, $write.PHP_EOL);
128
        }
129
    }
130
131
132
    public function interpolate(string $message, array $context)
133
    {
134
        $replace = [];
135
        foreach ($context as $key => $val) {
136
            $replace['{' . $key . '}'] = $val;
137
        }
138
        return strtr($message, $replace);
139
    }
140
141
    protected function rollLatest()
142
    {
143
        if (isset($this->latest)) {
144
            $size=ftell($this->temp);
145
            fseek($this->temp, 0);
146
            if ($size > 0) {
147
                $body=fread($this->temp, $size);
148
                file_put_contents($this->latest, $body, FILE_APPEND);
149
            }
150
            fclose($this->temp);
151
            if (isset($this->tempname)) {
152
                unlink($this->tempname);
153
            }
154
        }
155
    }
156
    
157
    protected function removePackFiles()
158
    {
159
        foreach ($this->removeFiles as $file) {
160
            if (\is_file($file) && \file_exists($file)) {
161
                unlink($file);
162
            }
163
        }
164
    }
165
166
    public function save()
167
    {
168
        if ($this->checkSize()) {
169
            $this->packLogFile();
170
        }
171
        $this->rollLatest();
172
        $this->removePackFiles();
173
    }
174
}
175