Passed
Push — master ( 6b4bcb...d7f1de )
by luo
02:13
created

system_check()   A

Complexity

Conditions 5
Paths 4

Size

Total Lines 13
Code Lines 7

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
eloc 7
c 0
b 0
f 0
dl 0
loc 13
rs 9.6111
cc 5
nc 4
nop 0
1
<?php
2
/**
3
 * 助手函数
4
 *
5
 * @author mybsdc <[email protected]>
6
 * @date 2019/3/3
7
 * @time 16:34
8
 */
9
10
use Luolongfei\App\Exceptions\LlfException;
11
use Luolongfei\Lib\Argv;
12
use Luolongfei\Lib\Config;
13
use Luolongfei\Lib\Log;
14
use Luolongfei\Lib\Env;
15
use Luolongfei\Lib\Lang;
16
use Luolongfei\Lib\PhpColor;
17
18
if (!function_exists('config')) {
19
    /**
20
     * 获取配置
21
     *
22
     * @param string $key 键,支持点式访问
23
     * @param string $default 默认值
24
     *
25
     * @return array|mixed
26
     */
27
    function config($key = '', $default = null)
28
    {
29
        return Config::instance()->get($key, $default);
30
    }
31
}
32
33
if (!function_exists('lang')) {
34
    /**
35
     * 读取语言包
36
     *
37
     * @param string $key 键,支持点式访问
38
     *
39
     * @return array|mixed|null
40
     */
41
    function lang($key = '')
42
    {
43
        return Lang::instance()->get($key);
44
    }
45
}
46
47
if (!function_exists('system_log')) {
48
    /**
49
     * 写日志
50
     *
51
     * @param $content
52
     * @param array $response
53
     * @param string $fileName
54
     * @description 受支持的着色标签
55
     * 'reset', 'bold', 'dark', 'italic', 'underline', 'blink', 'reverse', 'concealed', 'default', 'black', 'red',
56
     * 'green', 'yellow', 'blue', 'magenta', 'cyan', 'light_gray', 'dark_gray', 'light_red', 'light_green',
57
     * 'light_yellow', 'light_blue', 'light_magenta', 'light_cyan', 'white', 'bg_default', 'bg_black', 'bg_red',
58
     * 'bg_green', 'bg_yellow', 'bg_blue', 'bg_magenta', 'bg_cyan', 'bg_light_gray', 'bg_dark_gray', 'bg_light_red',
59
     * 'bg_light_green','bg_light_yellow', 'bg_light_blue', 'bg_light_magenta', 'bg_light_cyan', 'bg_white'
60
     */
61
    function system_log($content, array $response = [], $fileName = '')
62
    {
63
        try {
64
            $path = sprintf('%s/logs/%s/', ROOT_PATH, date('Y-m'));
0 ignored issues
show
Bug introduced by
The constant ROOT_PATH was not found. Maybe you did not declare it correctly or list all dependencies?
Loading history...
65
            $file = $path . ($fileName ?: date('d')) . '.log';
66
67
            if (!is_dir($path)) {
68
                mkdir($path, 0777, true);
69
                chmod($path, 0777);
70
            }
71
72
            $handle = fopen($file, 'a'); // 追加而非覆盖
73
74
            if (!filesize($file)) {
75
                chmod($file, 0666);
76
            }
77
78
            $msg = sprintf(
79
                "[%s] %s %s\n",
80
                date('Y-m-d H:i:s'),
81
                is_string($content) ? $content : json_encode($content),
82
                $response ? json_encode($response, JSON_UNESCAPED_UNICODE) : '');
83
84
            // 尝试为消息着色
85
            $c = PhpColor::instance()->getColorInstance();
86
            echo $c($msg)->colorize();
87
88
            // 干掉着色标签
89
            $msg = strip_tags($msg); // 不完整或者破损标签将导致更多的数据被删除
90
91
            fwrite($handle, $msg);
0 ignored issues
show
Bug introduced by
It seems like $handle can also be of type false; however, parameter $handle of fwrite() does only seem to accept resource, 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

91
            fwrite(/** @scrutinizer ignore-type */ $handle, $msg);
Loading history...
92
            fclose($handle);
0 ignored issues
show
Bug introduced by
It seems like $handle can also be of type false; however, parameter $handle of fclose() does only seem to accept resource, 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

92
            fclose(/** @scrutinizer ignore-type */ $handle);
Loading history...
93
94
            flush();
95
        } catch (\Exception $e) {
96
            // do nothing
97
        }
98
    }
99
}
100
101
if (!function_exists('is_locked')) {
102
    /**
103
     * 检查任务是否已被锁定
104
     *
105
     * @param string $taskName
106
     * @param bool $always 是否被永久锁定
107
     *
108
     * @return bool
109
     * @throws Exception
110
     */
111
    function is_locked($taskName = '', $always = false)
112
    {
113
        try {
114
            $lock = sprintf(
115
                '%s/num_limit/%s/%s.lock',
116
                APP_PATH,
0 ignored issues
show
Bug introduced by
The constant APP_PATH was not found. Maybe you did not declare it correctly or list all dependencies?
Loading history...
117
                $always ? 'always' : date('Y-m-d'),
118
                $taskName
119
            );
120
121
            return file_exists($lock);
122
        } catch (\Exception $e) {
123
            system_log(sprintf('检查任务%s是否锁定时出错,错误原因:%s', $taskName, $e->getMessage()));
124
        }
125
126
        return false;
127
    }
128
}
129
130
if (!function_exists('lock_task')) {
131
    /**
132
     * 锁定任务
133
     *
134
     * 防止重复执行
135
     *
136
     * @param string $taskName
137
     * @param bool $always 是否永久锁定
138
     *
139
     * @return bool
140
     */
141
    function lock_task($taskName = '', $always = false)
142
    {
143
        try {
144
            $lock = sprintf(
145
                '%s/num_limit/%s/%s.lock',
146
                APP_PATH,
0 ignored issues
show
Bug introduced by
The constant APP_PATH was not found. Maybe you did not declare it correctly or list all dependencies?
Loading history...
147
                $always ? 'always' : date('Y-m-d'),
148
                $taskName
149
            );
150
151
            $path = dirname($lock);
152
            if (!is_dir($path)) {
153
                mkdir($path, 0777, true);
154
                chmod($path, 0777);
155
            }
156
157
            if (file_exists($lock)) {
158
                return true;
159
            }
160
161
            $handle = fopen($lock, 'a'); // 追加而非覆盖
162
163
            if (!filesize($lock)) {
164
                chmod($lock, 0666);
165
            }
166
167
            fwrite($handle, sprintf(
0 ignored issues
show
Bug introduced by
It seems like $handle can also be of type false; however, parameter $handle of fwrite() does only seem to accept resource, 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

167
            fwrite(/** @scrutinizer ignore-type */ $handle, sprintf(
Loading history...
168
                    "Locked at %s.\n",
169
                    date('Y-m-d H:i:s')
170
                )
171
            );
172
173
            fclose($handle);
0 ignored issues
show
Bug introduced by
It seems like $handle can also be of type false; however, parameter $handle of fclose() does only seem to accept resource, 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

173
            fclose(/** @scrutinizer ignore-type */ $handle);
Loading history...
174
175
            Log::info(sprintf('%s已被锁定,此任务%s已不会再执行,请知悉', $taskName, $always ? '' : '今天内'));
176
        } catch (\Exception $e) {
177
            system_log(sprintf('创建锁定任务文件%s时出错,错误原因:%s', $lock, $e->getMessage()));
178
179
            return false;
180
        }
181
182
        return true;
183
    }
184
}
185
186
if (!function_exists('env')) {
187
    /**
188
     * 获取环境变量值
189
     *
190
     * @param string $key
191
     * @param string $default 默认值
192
     *
193
     * @return array | bool | false | null | string
194
     */
195
    function env($key = '', $default = null)
196
    {
197
        return Env::instance()->get($key, $default);
198
    }
199
}
200
201
if (!function_exists('get_argv')) {
202
    /**
203
     * 获取命令行传参
204
     *
205
     * @param string $name
206
     * @param string $default 默认值
207
     *
208
     * @return mixed|string
209
     */
210
    function get_argv(string $name, string $default = '')
211
    {
212
        return Argv::instance()->get($name, $default);
213
    }
214
}
215
216
if (!function_exists('system_check')) {
217
    /**
218
     * 检查环境是否满足要求
219
     *
220
     * @throws LlfException
221
     */
222
    function system_check()
223
    {
224
        if (!function_exists('putenv')) {
225
            throw new LlfException(34520005);
226
        }
227
228
        if (version_compare(PHP_VERSION, '7.0.0') < 0) {
229
            throw new LlfException(34520006);
230
        }
231
232
        $envFile = ROOT_PATH . '/.env';
0 ignored issues
show
Bug introduced by
The constant ROOT_PATH was not found. Maybe you did not declare it correctly or list all dependencies?
Loading history...
233
        if (!file_exists($envFile)) {
234
            throw new LlfException(copy(ROOT_PATH . '/.env.example', $envFile) ? 34520007 : 34520008);
235
        }
236
    }
237
}