Completed
Push — 6.0 ( ece68e...ed6998 )
by liu
04:02
created

error()   C

Complexity

Conditions 11
Paths 168

Size

Total Lines 32
Code Lines 19

Duplication

Lines 0
Ratio 0 %

Importance

Changes 2
Bugs 0 Features 0
Metric Value
cc 11
eloc 19
c 2
b 0
f 0
nc 168
nop 5
dl 0
loc 32
rs 6.75

How to fix   Complexity   

Long Method

Small methods make your code easier to understand, in particular if combined with a good name. Besides, if your method is small, finding a good name is usually much easier.

For example, if you find yourself adding comments to a method's body, this is usually a good sign to extract the commented part to a new method, and use the comment as a starting point when coming up with a good name for this new method.

Commonly applied refactorings include:

1
<?php
2
// +----------------------------------------------------------------------
1 ignored issue
show
Coding Style introduced by
You must use "/**" style comments for a file comment
Loading history...
3
// | ThinkPHP [ WE CAN DO IT JUST THINK ]
4
// +----------------------------------------------------------------------
5
// | Copyright (c) 2006~2019 http://thinkphp.cn All rights reserved.
6
// +----------------------------------------------------------------------
7
// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
8
// +----------------------------------------------------------------------
9
// | Author: liu21st <[email protected]>
10
// +----------------------------------------------------------------------
11
declare (strict_types = 1);
12
13
//------------------------
14
// ThinkPHP 助手函数
15
//-------------------------
16
17
use think\App;
18
use think\Container;
19
use think\db\Raw;
20
use think\exception\HttpException;
0 ignored issues
show
Bug introduced by
This use statement conflicts with another class in this namespace, HttpException. Consider defining an alias.

Let?s assume that you have a directory layout like this:

.
|-- OtherDir
|   |-- Bar.php
|   `-- Foo.php
`-- SomeDir
    `-- Foo.php

and let?s assume the following content of Bar.php:

// Bar.php
namespace OtherDir;

use SomeDir\Foo; // This now conflicts the class OtherDir\Foo

If both files OtherDir/Foo.php and SomeDir/Foo.php are loaded in the same runtime, you will see a PHP error such as the following:

PHP Fatal error:  Cannot use SomeDir\Foo as Foo because the name is already in use in OtherDir/Foo.php

However, as OtherDir/Foo.php does not necessarily have to be loaded and the error is only triggered if it is loaded before OtherDir/Bar.php, this problem might go unnoticed for a while. In order to prevent this error from surfacing, you must import the namespace with a different alias:

// Bar.php
namespace OtherDir;

use SomeDir\Foo as SomeDirFoo; // There is no conflict anymore.
Loading history...
21
use think\exception\HttpResponseException;
0 ignored issues
show
Bug introduced by
This use statement conflicts with another class in this namespace, HttpResponseException. Consider defining an alias.

Let?s assume that you have a directory layout like this:

.
|-- OtherDir
|   |-- Bar.php
|   `-- Foo.php
`-- SomeDir
    `-- Foo.php

and let?s assume the following content of Bar.php:

// Bar.php
namespace OtherDir;

use SomeDir\Foo; // This now conflicts the class OtherDir\Foo

If both files OtherDir/Foo.php and SomeDir/Foo.php are loaded in the same runtime, you will see a PHP error such as the following:

PHP Fatal error:  Cannot use SomeDir\Foo as Foo because the name is already in use in OtherDir/Foo.php

However, as OtherDir/Foo.php does not necessarily have to be loaded and the error is only triggered if it is loaded before OtherDir/Bar.php, this problem might go unnoticed for a while. In order to prevent this error from surfacing, you must import the namespace with a different alias:

// Bar.php
namespace OtherDir;

use SomeDir\Foo as SomeDirFoo; // There is no conflict anymore.
Loading history...
22
use think\facade\Cache;
23
use think\facade\Config;
24
use think\facade\Cookie;
25
use think\facade\Db;
26
use think\facade\Env;
27
use think\facade\Event;
0 ignored issues
show
Bug introduced by
This use statement conflicts with another class in this namespace, Event. Consider defining an alias.

Let?s assume that you have a directory layout like this:

.
|-- OtherDir
|   |-- Bar.php
|   `-- Foo.php
`-- SomeDir
    `-- Foo.php

and let?s assume the following content of Bar.php:

// Bar.php
namespace OtherDir;

use SomeDir\Foo; // This now conflicts the class OtherDir\Foo

If both files OtherDir/Foo.php and SomeDir/Foo.php are loaded in the same runtime, you will see a PHP error such as the following:

PHP Fatal error:  Cannot use SomeDir\Foo as Foo because the name is already in use in OtherDir/Foo.php

However, as OtherDir/Foo.php does not necessarily have to be loaded and the error is only triggered if it is loaded before OtherDir/Bar.php, this problem might go unnoticed for a while. In order to prevent this error from surfacing, you must import the namespace with a different alias:

// Bar.php
namespace OtherDir;

use SomeDir\Foo as SomeDirFoo; // There is no conflict anymore.
Loading history...
28
use think\facade\Lang;
29
use think\facade\Log;
30
use think\facade\Request;
31
use think\facade\Route;
32
use think\facade\Session;
33
use think\Model;
34
use think\model\Collection as ModelCollection;
35
use think\Response;
36
use think\route\RuleItem;
37
use think\Validate;
38
39
if (!function_exists('abort')) {
40
    /**
41
     * 抛出HTTP异常
42
     * @param integer|Response $code    状态码 或者 Response对象实例
43
     * @param string           $message 错误信息
44
     * @param array            $header  参数
45
     */
0 ignored issues
show
Coding Style introduced by
Missing @return tag in function comment
Loading history...
46
    function abort($code, string $message = null, array $header = [])
47
    {
48
        if ($code instanceof Response) {
49
            throw new HttpResponseException($code);
50
        } else {
51
            throw new HttpException($code, $message, null, $header);
52
        }
53
    }
54
}
55
56
if (!function_exists('app')) {
57
    /**
58
     * 快速获取容器中的实例 支持依赖注入
59
     * @param string $name        类名或标识 默认获取当前应用实例
1 ignored issue
show
Coding Style introduced by
Tag value for @param tag indented incorrectly; expected 2 spaces but found 1
Loading history...
60
     * @param array  $args        参数
1 ignored issue
show
Coding Style introduced by
Tag value for @param tag indented incorrectly; expected 2 spaces but found 1
Loading history...
61
     * @param bool   $newInstance 是否每次创建新的实例
1 ignored issue
show
Coding Style introduced by
Tag value for @param tag indented incorrectly; expected 2 spaces but found 1
Loading history...
62
     * @return object|App
63
     */
64
    function app(string $name = '', array $args = [], bool $newInstance = false)
65
    {
66
        return Container::getInstance()->make($name ?: App::class, $args, $newInstance);
67
    }
68
}
69
70
if (!function_exists('bind')) {
71
    /**
72
     * 绑定一个类到容器
73
     * @param  string|array $abstract 类标识、接口(支持批量绑定)
74
     * @param  mixed        $concrete 要绑定的类、闭包或者实例
75
     * @return Container
76
     */
77
    function bind($abstract, $concrete = null)
0 ignored issues
show
Best Practice introduced by
It is generally recommended to explicitly declare the visibility for methods.

Adding explicit visibility (private, protected, or public) is generally recommend to communicate to other developers how, and from where this method is intended to be used.

Loading history...
78
    {
79
        return Container::getInstance()->bind($abstract, $concrete);
80
    }
81
}
82
83
if (!function_exists('cache')) {
84
    /**
85
     * 缓存管理
86
     * @param  mixed  $name    缓存名称,如果为数组表示进行缓存设置
87
     * @param  mixed  $value   缓存值
88
     * @param  mixed  $options 缓存参数
89
     * @param  string $tag     缓存标签
90
     * @return mixed
91
     */
92
    function cache($name, $value = '', $options = null, $tag = null)
93
    {
94
        if (is_array($name)) {
95
            // 缓存初始化
96
            return Cache::connect($name);
97
        }
98
99
        if ('' === $value) {
100
            // 获取缓存
101
            return 0 === strpos($name, '?') ? Cache::has(substr($name, 1)) : Cache::get($name);
102
        } elseif (is_null($value)) {
103
            // 删除缓存
104
            return Cache::rm($name);
105
        }
106
107
        // 缓存数据
108
        if (is_array($options)) {
109
            $expire = $options['expire'] ?? null; //修复查询缓存无法设置过期时间
110
        } else {
111
            $expire = $options;
112
        }
113
114
        if (is_null($tag)) {
115
            return Cache::set($name, $value, $expire);
116
        } else {
117
            return Cache::tag($tag)->set($name, $value, $expire);
118
        }
119
    }
120
}
121
122
if (!function_exists('call')) {
123
    /**
124
     * 调用反射执行callable 支持依赖注入
125
     * @param  mixed $callable 支持闭包等callable写法
126
     * @param  array $args     参数
127
     * @return mixed
128
     */
129
    function call(callable $callable, array $args = [])
130
    {
131
        return Container::getInstance()->invoke($callable, $args);
132
    }
133
}
134
135
if (!function_exists('class_basename')) {
136
    /**
137
     * 获取类名(不包含命名空间)
138
     *
139
     * @param  mixed $class 类名
140
     * @return string
141
     */
142
    function class_basename($class): string
0 ignored issues
show
Coding Style introduced by
Function name "class_basename" is prefixed with a package name but does not begin with a capital letter
Loading history...
Coding Style introduced by
Function name "class_basename" is invalid; consider "Class_basename" instead
Loading history...
143
    {
144
        $class = is_object($class) ? get_class($class) : $class;
145
        return basename(str_replace('\\', '/', $class));
146
    }
147
}
148
149
if (!function_exists('class_uses_recursive')) {
150
    /**
151
     *获取一个类里所有用到的trait,包括父类的
0 ignored issues
show
Coding Style introduced by
Expected 1 space after asterisk; 0 found
Loading history...
152
     *
153
     * @param  mixed $class 类名
154
     * @return array
155
     */
156
    function class_uses_recursive($class): array
0 ignored issues
show
Coding Style introduced by
Function name "class_uses_recursive" is prefixed with a package name but does not begin with a capital letter
Loading history...
Coding Style introduced by
Function name "class_uses_recursive" is invalid; consider "Class_Uses_recursive" instead
Loading history...
157
    {
158
        if (is_object($class)) {
159
            $class = get_class($class);
160
        }
161
162
        $results = [];
163
        $classes = array_merge([$class => $class], class_parents($class));
164
        foreach ($classes as $class) {
0 ignored issues
show
introduced by
$class is overwriting one of the parameters of this function.
Loading history...
165
            $results += trait_uses_recursive($class);
166
        }
167
168
        return array_unique($results);
169
    }
170
}
171
172
if (!function_exists('config')) {
173
    /**
174
     * 获取和设置配置参数
175
     * @param  string|array $name  参数名
176
     * @param  mixed        $value 参数值
177
     * @return mixed
178
     */
179
    function config($name = '', $value = null)
180
    {
181
        if (is_array($name)) {
182
            return Config::set($name, $value);
183
        }
184
185
        return 0 === strpos($name, '?') ? Config::has(substr($name, 1)) : Config::get($name, $value);
186
    }
187
}
188
189
if (!function_exists('cookie')) {
190
    /**
191
     * Cookie管理
192
     * @param  string $name   cookie名称
193
     * @param  mixed  $value  cookie值
194
     * @param  mixed  $option 参数
195
     * @return mixed
196
     */
197
    function cookie(string $name, $value = '', $option = null)
198
    {
199
        if (is_null($value)) {
200
            // 删除
201
            Cookie::delete($name);
202
        } elseif ('' === $value) {
203
            // 获取
204
            return 0 === strpos($name, '?') ? Request::has(substr($name, 1), 'cookie') : Request::cookie($name);
205
        } else {
206
            // 设置
207
            return Cookie::set($name, $value, $option);
208
        }
209
    }
210
}
211
212
if (!function_exists('download')) {
213
    /**
214
     * 获取\think\response\Download对象实例
215
     * @param  string $filename 要下载的文件
216
     * @param  string $name     显示文件名
217
     * @param  bool   $content  是否为内容
218
     * @param  int    $expire   有效期(秒)
219
     * @return \think\response\File
220
     */
221
    function download(string $filename, string $name = '', bool $content = false, int $expire = 180)
222
    {
223
        return Response::create($filename, 'file')->name($name)->isContent($content)->expire($expire);
0 ignored issues
show
Bug introduced by
The method name() does not exist on think\Response. It seems like you code against a sub-type of think\Response such as think\response\File. ( Ignorable by Annotation )

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

223
        return Response::create($filename, 'file')->/** @scrutinizer ignore-call */ name($name)->isContent($content)->expire($expire);
Loading history...
224
    }
225
}
226
227
if (!function_exists('dump')) {
228
    /**
229
     * 浏览器友好的变量输出
230
     * @param  mixed  $var   变量
231
     * @param  bool   $echo  是否输出 默认为true 如果为false 则返回输出字符串
232
     * @param  string $label 标签 默认为空
233
     * @return void|string
234
     */
235
    function dump($var, bool $echo = true, string $label = null)
236
    {
237
        $label = (null === $label) ? '' : rtrim($label) . ':';
238
        if ($var instanceof Model || $var instanceof ModelCollection) {
239
            $var = $var->toArray();
240
        }
241
242
        ob_start();
243
        var_dump($var);
0 ignored issues
show
Security Debugging Code introduced by
var_dump($var) looks like debug code. Are you sure you do not want to remove it?
Loading history...
244
245
        $output = ob_get_clean();
246
        $output = preg_replace('/\]\=\>\n(\s+)/m', '] => ', $output);
247
248
        if (PHP_SAPI == 'cli') {
249
            $output = PHP_EOL . $label . $output . PHP_EOL;
250
        } else {
251
            if (!extension_loaded('xdebug')) {
252
                $output = htmlspecialchars($output, ENT_SUBSTITUTE);
253
            }
254
            $output = '<pre>' . $label . $output . '</pre>';
255
        }
256
257
        if ($echo) {
258
            echo $output;
259
            return;
260
        }
261
262
        return $output;
263
    }
264
}
265
266
if (!function_exists('env')) {
267
    /**
268
     * 获取环境变量值
269
     * @access public
270
     * @param  string $name    环境变量名(支持二级 .号分割)
271
     * @param  string $default 默认值
272
     * @return mixed
273
     */
274
    function env(string $name = null, $default = null)
275
    {
276
        return Env::get($name, $default);
277
    }
278
}
279
280
if (!function_exists('error')) {
281
    /**
282
     * 操作错误跳转的快捷方法
283
     * @param  mixed   $msg 提示信息
0 ignored issues
show
Coding Style introduced by
Expected 4 spaces after parameter name; 1 found
Loading history...
284
     * @param  string  $url 跳转的URL地址
0 ignored issues
show
Coding Style introduced by
Expected 4 spaces after parameter name; 1 found
Loading history...
285
     * @param  mixed   $data 返回的数据
0 ignored issues
show
Coding Style introduced by
Expected 3 spaces after parameter name; 1 found
Loading history...
286
     * @param  integer $wait 跳转等待时间
0 ignored issues
show
Coding Style introduced by
Expected 3 spaces after parameter name; 1 found
Loading history...
287
     * @param  array   $header 发送的Header信息
288
     * @return Response
289
     */
290
    function error($msg = '', string $url = null, $data = '', int $wait = 3, array $header = []): Response
291
    {
292
        if (is_null($url)) {
293
            $url = request()->isAjax() ? '' : 'javascript:history.back(-1);';
294
        } elseif ($url) {
295
            $url = (strpos($url, '://') || 0 === strpos($url, '/')) ? $url : app('route')->buildUrl($url);
0 ignored issues
show
Bug introduced by
The method buildUrl() does not exist on think\App. ( Ignorable by Annotation )

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

295
            $url = (strpos($url, '://') || 0 === strpos($url, '/')) ? $url : app('route')->/** @scrutinizer ignore-call */ buildUrl($url);

This check looks for calls to methods that do not seem to exist on a given type. It looks for the method on the type itself as well as in inherited classes or implemented interfaces.

This is most likely a typographical error or the method has been renamed.

Loading history...
296
        }
297
298
        $result = [
299
            'code' => 0,
300
            'msg'  => $msg,
301
            'data' => $data,
302
            'url'  => $url,
303
            'wait' => $wait,
304
        ];
305
306
        $type = (request()->isJson() || request()->isAjax()) ? 'json' : 'html';
0 ignored issues
show
Bug introduced by
The method isJson() does not exist on think\facade\Request. ( Ignorable by Annotation )

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

306
        $type = (request()->/** @scrutinizer ignore-call */ isJson() || request()->isAjax()) ? 'json' : 'html';

This check looks for calls to methods that do not seem to exist on a given type. It looks for the method on the type itself as well as in inherited classes or implemented interfaces.

This is most likely a typographical error or the method has been renamed.

Loading history...
307
        if ('html' == strtolower($type)) {
308
            $type = 'jump';
309
        }
310
311
        $response = Response::create($result, $type)->header($header)->options(['jump_template' => app('config')->get('app.dispatch_error_tmpl')]);
312
313
        $trace = debug_backtrace(DEBUG_BACKTRACE_IGNORE_ARGS, 3);
314
315
        foreach ($trace as $call) {
316
            if ('__construct' == $call['function']) {
317
                throw new HttpResponseException($response);
318
            }
319
        }
320
321
        return $response;
322
    }
323
}
324
325
if (!function_exists('event')) {
326
    /**
327
     * 触发事件
328
     * @param  mixed $event 事件名(或者类名)
329
     * @param  mixed $args  参数
330
     * @return mixed
331
     */
332
    function event($event, $args = null)
333
    {
334
        return Event::trigger($event, $args);
335
    }
336
}
337
338
if (!function_exists('exception')) {
339
    /**
340
     * 抛出异常处理
341
     *
342
     * @param string $msg       异常消息
343
     * @param int    $code      异常代码 默认为0
344
     * @param string $exception 异常类
345
     *
346
     * @throws Exception
347
     */
0 ignored issues
show
Coding Style introduced by
Missing @return tag in function comment
Loading history...
348
    function exception(string $msg, int $code = 0, string $exception = '')
349
    {
350
        $e = $exception ?: '\think\Exception';
351
        throw new $e($msg, $code);
352
    }
353
}
354
355
if (!function_exists('halt')) {
356
    /**
357
     * 调试变量并且中断输出
358
     * @param mixed $var 调试变量或者信息
359
     */
0 ignored issues
show
Coding Style introduced by
Missing @return tag in function comment
Loading history...
360
    function halt($var)
361
    {
362
        dump($var);
363
364
        throw new HttpResponseException(new Response);
365
    }
366
}
367
368
if (!function_exists('input')) {
369
    /**
370
     * 获取输入数据 支持默认值和过滤
371
     * @param  string $key     获取的变量名
372
     * @param  mixed  $default 默认值
373
     * @param  string $filter  过滤方法
374
     * @return mixed
375
     */
376
    function input(string $key = '', $default = null, $filter = '')
377
    {
378
        if (0 === strpos($key, '?')) {
379
            $key = substr($key, 1);
380
            $has = true;
381
        }
382
383
        if ($pos = strpos($key, '.')) {
384
            // 指定参数来源
385
            $method = substr($key, 0, $pos);
386
            if (in_array($method, ['get', 'post', 'put', 'patch', 'delete', 'route', 'param', 'request', 'session', 'cookie', 'server', 'env', 'path', 'file'])) {
387
                $key = substr($key, $pos + 1);
388
            } else {
389
                $method = 'param';
390
            }
391
        } else {
392
            // 默认为自动判断
393
            $method = 'param';
394
        }
395
396
        return isset($has) ?
397
        request()->has($key, $method) :
398
        request()->$method($key, $default, $filter);
399
    }
400
}
401
402
if (!function_exists('invoke')) {
403
    /**
404
     * 调用反射实例化对象 支持依赖注入
405
     * @param  string $class 类名
406
     * @param  array  $args  参数
407
     * @return mixed
408
     */
409
    function invoke(string $class, array $args = [])
410
    {
411
        return Container::getInstance()->invokeClass($class, $args);
412
    }
413
}
414
415
if (!function_exists('json')) {
416
    /**
417
     * 获取\think\response\Json对象实例
418
     * @param  mixed $data    返回的数据
419
     * @param  int   $code    状态码
420
     * @param  array $header  头部
421
     * @param  array $options 参数
422
     * @return \think\response\Json
423
     */
424
    function json($data = [], $code = 200, $header = [], $options = [])
425
    {
426
        return Response::create($data, 'json', $code)->header($header)->options($options);
427
    }
428
}
429
430
if (!function_exists('jsonp')) {
431
    /**
432
     * 获取\think\response\Jsonp对象实例
433
     * @param  mixed $data    返回的数据
434
     * @param  int   $code    状态码
435
     * @param  array $header  头部
436
     * @param  array $options 参数
437
     * @return \think\response\Jsonp
438
     */
439
    function jsonp($data = [], $code = 200, $header = [], $options = [])
440
    {
441
        return Response::create($data, 'jsonp', $code)->header($header)->options($options);
442
    }
443
}
444
445
if (!function_exists('lang')) {
446
    /**
447
     * 获取语言变量值
448
     * @param  string $name 语言变量名
449
     * @param  array  $vars 动态变量值
450
     * @param  string $lang 语言
451
     * @return mixed
452
     */
453
    function lang(string $name, array $vars = [], string $lang = '')
454
    {
455
        return Lang::get($name, $vars, $lang);
456
    }
457
}
458
459
if (!function_exists('parse_name')) {
460
    /**
461
     * 字符串命名风格转换
462
     * type 0 将Java风格转换为C的风格 1 将C风格转换为Java的风格
463
     * @param  string $name    字符串
464
     * @param  int    $type    转换类型
465
     * @param  bool   $ucfirst 首字母是否大写(驼峰规则)
466
     * @return string
467
     */
468
    function parse_name(string $name, int $type = 0, bool $ucfirst = true): string
0 ignored issues
show
Coding Style introduced by
Function name "parse_name" is prefixed with a package name but does not begin with a capital letter
Loading history...
Coding Style introduced by
Function name "parse_name" is invalid; consider "Parse_name" instead
Loading history...
469
    {
470
        if ($type) {
471
            $name = preg_replace_callback('/_([a-zA-Z])/', function ($match) {
0 ignored issues
show
Coding Style introduced by
The opening parenthesis of a multi-line function call should be the last content on the line.
Loading history...
472
                return strtoupper($match[1]);
473
            }, $name);
0 ignored issues
show
Coding Style introduced by
For multi-line function calls, the closing parenthesis should be on a new line.

If a function call spawns multiple lines, the coding standard suggests to move the closing parenthesis to a new line:

someFunctionCall(
    $firstArgument,
    $secondArgument,
    $thirdArgument
); // Closing parenthesis on a new line.
Loading history...
474
475
            return $ucfirst ? ucfirst($name) : lcfirst($name);
476
        }
477
478
        return strtolower(trim(preg_replace("/[A-Z]/", "_\\0", $name), "_"));
479
    }
480
}
481
482
if (!function_exists('raw')) {
483
    /**
484
     * 生成一个数据库的Raw对象
485
     * @param  string $sql SQL指令
486
     * @return \think\db\Raw
487
     */
488
    function raw(string $sql): Raw
489
    {
490
        return Db::raw($sql);
491
    }
492
}
493
494
if (!function_exists('redirect')) {
495
    /**
496
     * 获取\think\response\Redirect对象实例
497
     * @param  mixed         $url    重定向地址 支持Url::build方法的地址
498
     * @param  array|integer $params 额外参数
499
     * @param  int           $code   状态码
500
     * @return \think\response\Redirect
501
     */
502
    function redirect($url = [], $params = [], $code = 302)
503
    {
504
        if (is_integer($params)) {
505
            $code   = $params;
506
            $params = [];
507
        }
508
509
        return Response::create($url, 'redirect', $code)->params($params);
0 ignored issues
show
Bug introduced by
The method params() does not exist on think\Response. It seems like you code against a sub-type of think\Response such as think\response\Redirect. ( Ignorable by Annotation )

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

509
        return Response::create($url, 'redirect', $code)->/** @scrutinizer ignore-call */ params($params);
Loading history...
510
    }
511
}
512
513
if (!function_exists('request')) {
514
    /**
515
     * 获取当前Request对象实例
516
     * @return Request
517
     */
518
    function request()
519
    {
520
        return app('request');
0 ignored issues
show
Bug Best Practice introduced by
The expression return app('request') also could return the type think\App which is incompatible with the documented return type think\facade\Request.
Loading history...
521
    }
522
}
523
524
if (!function_exists('response')) {
525
    /**
526
     * 创建普通 Response 对象实例
527
     * @param  mixed      $data   输出数据
528
     * @param  int|string $code   状态码
529
     * @param  array      $header 头信息
530
     * @param  string     $type
0 ignored issues
show
Coding Style introduced by
Missing parameter comment
Loading history...
531
     * @return Response
532
     */
533
    function response($data = '', $code = 200, $header = [], $type = 'html')
534
    {
535
        return Response::create($data, $type, $code)->header($header);
0 ignored issues
show
Bug introduced by
It seems like $code can also be of type string; however, parameter $code of think\Response::create() does only seem to accept integer, 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

535
        return Response::create($data, $type, /** @scrutinizer ignore-type */ $code)->header($header);
Loading history...
536
    }
537
}
538
539
if (!function_exists('result')) {
540
    /**
541
     * 返回封装后的API数据到客户端
542
     * @param  mixed   $data 要返回的数据
0 ignored issues
show
Coding Style introduced by
Expected 3 spaces after parameter name; 1 found
Loading history...
543
     * @param  integer $code 返回的code
0 ignored issues
show
Coding Style introduced by
Expected 3 spaces after parameter name; 1 found
Loading history...
544
     * @param  mixed   $msg 提示信息
0 ignored issues
show
Coding Style introduced by
Expected 4 spaces after parameter name; 1 found
Loading history...
545
     * @param  string  $type 返回数据格式
0 ignored issues
show
Coding Style introduced by
Expected 3 spaces after parameter name; 1 found
Loading history...
546
     * @param  array   $header 发送的Header信息
547
     * @return Response
548
     */
549
    function result($data, int $code = 0, $msg = '', string $type = '', array $header = []): Response
550
    {
551
        $result = [
552
            'code' => $code,
553
            'msg'  => $msg,
554
            'time' => time(),
555
            'data' => $data,
556
        ];
557
558
        $type     = $type ?: 'json';
559
        $response = Response::create($result, $type)->header($header);
560
561
        $trace = debug_backtrace(DEBUG_BACKTRACE_IGNORE_ARGS, 3);
562
563
        foreach ($trace as $call) {
564
            if ('__construct' == $call['function']) {
565
                throw new HttpResponseException($response);
566
            }
567
        }
568
569
        return $response;
570
    }
571
}
572
573
if (!function_exists('route')) {
574
    /**
575
     * 路由注册
576
     * @param  string $rule   路由规则
577
     * @param  mixed  $route  路由地址
578
     * @param  string $method 请求类型
579
     * @return RuleItem
580
     */
581
    function route(string $rule, $route, $method = '*'): RuleItem
582
    {
583
        return Route::rule($rule, $route, $method);
0 ignored issues
show
Unused Code introduced by
The call to think\facade\Route::rule() has too many arguments starting with $rule. ( Ignorable by Annotation )

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

583
        return Route::/** @scrutinizer ignore-call */ rule($rule, $route, $method);

This check compares calls to functions or methods with their respective definitions. If the call has more arguments than are defined, it raises an issue.

If a function is defined several times with a different number of parameters, the check may pick up the wrong definition and report false positives. One codebase where this has been known to happen is Wordpress. Please note the @ignore annotation hint above.

Loading history...
584
    }
585
}
586
587
if (!function_exists('session')) {
588
    /**
589
     * Session管理
590
     * @param  string $name  session名称
591
     * @param  mixed  $value session值
592
     * @return mixed
593
     */
594
    function session(string $name = null, $value = '')
595
    {
596
        if (is_null($name)) {
597
            // 清除
598
            Session::clear();
599
        } elseif (is_null($value)) {
600
            // 删除
601
            Session::delete($name);
602
        } elseif ('' === $value) {
603
            // 判断或获取
604
            return 0 === strpos($name, '?') ? Session::has(substr($name, 1)) : Session::get($name);
605
        } else {
606
            // 设置
607
            Session::set($name, $value);
608
        }
609
    }
610
}
611
612
if (!function_exists('success')) {
613
    /**
614
     * 操作成功跳转的快捷方法
615
     * @param  mixed     $msg 提示信息
0 ignored issues
show
Coding Style introduced by
Expected 4 spaces after parameter name; 1 found
Loading history...
616
     * @param  string    $url 跳转的URL地址
0 ignored issues
show
Coding Style introduced by
Expected 4 spaces after parameter name; 1 found
Loading history...
617
     * @param  mixed     $data 返回的数据
0 ignored issues
show
Coding Style introduced by
Expected 3 spaces after parameter name; 1 found
Loading history...
618
     * @param  integer   $wait 跳转等待时间
0 ignored issues
show
Coding Style introduced by
Expected 3 spaces after parameter name; 1 found
Loading history...
619
     * @param  array     $header 发送的Header信息
620
     * @return Response
621
     */
622
    function success($msg = '', string $url = null, $data = '', int $wait = 3, array $header = []): Response
623
    {
624
        if (is_null($url) && isset($_SERVER["HTTP_REFERER"])) {
625
            $url = $_SERVER["HTTP_REFERER"];
626
        } elseif ($url) {
627
            $url = (strpos($url, '://') || 0 === strpos($url, '/')) ? $url : app('route')->buildUrl($url);
628
        }
629
630
        $result = [
631
            'code' => 1,
632
            'msg'  => $msg,
633
            'data' => $data,
634
            'url'  => $url,
635
            'wait' => $wait,
636
        ];
637
638
        $type = (request()->isJson() || request()->isAjax()) ? 'json' : 'html';
639
        // 把跳转模板的渲染下沉,这样在 response_send 行为里通过getData()获得的数据是一致性的格式
640
        if ('html' == strtolower($type)) {
641
            $type = 'jump';
642
        }
643
644
        $response = Response::create($result, $type)->header($header)->options(['jump_template' => app('config')->get('app.dispatch_success_tmpl')]);
645
646
        $trace = debug_backtrace(DEBUG_BACKTRACE_IGNORE_ARGS, 3);
647
648
        foreach ($trace as $call) {
649
            if ('__construct' == $call['function']) {
650
                throw new HttpResponseException($response);
651
            }
652
        }
653
654
        return $response;
655
    }
656
}
657
658
if (!function_exists('token')) {
659
    /**
660
     * 获取Token令牌
661
     * @param  string $name 令牌名称
662
     * @param  mixed  $type 令牌生成方法
663
     * @return string
664
     */
665
    function token(string $name = '__token__', string $type = 'md5'): string
666
    {
667
        return Request::buildToken($name, $type);
0 ignored issues
show
Bug introduced by
The method buildToken() does not exist on think\facade\Request. Since you implemented __callStatic, consider adding a @method annotation. ( Ignorable by Annotation )

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

667
        return Request::/** @scrutinizer ignore-call */ buildToken($name, $type);
Loading history...
668
    }
669
}
670
671
if (!function_exists('token_field')) {
672
    /**
673
     * 生成令牌隐藏表单
674
     * @param  string $name 令牌名称
675
     * @param  mixed  $type 令牌生成方法
676
     * @return string
677
     */
678
    function token_field(string $name = '__token__', string $type = 'md5'): string
0 ignored issues
show
Coding Style introduced by
Function name "token_field" is prefixed with a package name but does not begin with a capital letter
Loading history...
Coding Style introduced by
Function name "token_field" is invalid; consider "Token_field" instead
Loading history...
679
    {
680
        $token = Request::buildToken($name, $type);
681
682
        return '<input type="hidden" name="' . $name . '" value="' . $token . '" />';
683
    }
684
}
685
686
if (!function_exists('token_meta')) {
687
    /**
688
     * 生成令牌meta
689
     * @param  string $name 令牌名称
690
     * @param  mixed  $type 令牌生成方法
691
     * @return string
692
     */
693
    function token_meta(string $name = '__token__', string $type = 'md5'): string
0 ignored issues
show
Coding Style introduced by
Function name "token_meta" is prefixed with a package name but does not begin with a capital letter
Loading history...
Coding Style introduced by
Function name "token_meta" is invalid; consider "Token_meta" instead
Loading history...
694
    {
695
        $token = Request::buildToken($name, $type);
696
697
        return '<meta name="csrf-token" content="' . $token . '">';
698
    }
699
}
700
701
if (!function_exists('trace')) {
702
    /**
703
     * 记录日志信息
704
     * @param  mixed  $log   log信息 支持字符串和数组
705
     * @param  string $level 日志级别
706
     * @return array|void
707
     */
708
    function trace($log = '[think]', string $level = 'log')
709
    {
710
        if ('[think]' === $log) {
711
            return Log::getLog();
712
        }
713
714
        Log::record($log, $level);
715
    }
716
}
717
718
if (!function_exists('trait_uses_recursive')) {
719
    /**
720
     * 获取一个trait里所有引用到的trait
721
     *
722
     * @param  string $trait Trait
723
     * @return array
724
     */
725
    function trait_uses_recursive(string $trait): array
0 ignored issues
show
Coding Style introduced by
Function name "trait_uses_recursive" is prefixed with a package name but does not begin with a capital letter
Loading history...
Coding Style introduced by
Function name "trait_uses_recursive" is invalid; consider "Trait_Uses_recursive" instead
Loading history...
726
    {
727
        $traits = class_uses($trait);
728
        foreach ($traits as $trait) {
729
            $traits += trait_uses_recursive($trait);
730
        }
731
732
        return $traits;
733
    }
734
}
735
736
if (!function_exists('url')) {
737
    /**
738
     * Url生成
739
     * @param string      $url    路由地址
1 ignored issue
show
Coding Style introduced by
Tag value for @param tag indented incorrectly; expected 2 spaces but found 1
Loading history...
740
     * @param array       $vars   变量
1 ignored issue
show
Coding Style introduced by
Tag value for @param tag indented incorrectly; expected 2 spaces but found 1
Loading history...
741
     * @param bool|string $suffix 生成的URL后缀
1 ignored issue
show
Coding Style introduced by
Tag value for @param tag indented incorrectly; expected 2 spaces but found 1
Loading history...
742
     * @param bool|string $domain 域名
1 ignored issue
show
Coding Style introduced by
Tag value for @param tag indented incorrectly; expected 2 spaces but found 1
Loading history...
743
     * @return string
744
     */
745
    function url(string $url = '', array $vars = [], $suffix = true, $domain = false): string
746
    {
747
        return Route::buildUrl($url, $vars, $suffix, $domain);
748
    }
749
}
750
751
if (!function_exists('validate')) {
752
    /**
753
     * 验证数据
754
     * @param  array        $data     数据
755
     * @param  string|array $validate 验证器名或者验证规则数组
756
     * @param  array        $message  提示信息
757
     * @param  bool         $batch    是否批量验证
758
     * @return bool
759
     * @throws ValidateException
760
     */
761
    function validate(array $data, $validate, array $message = [], bool $batch = false): bool
762
    {
763
        if (is_array($validate)) {
764
            $v = new Validate();
765
            $v->rule($validate);
766
        } else {
767
            if (strpos($validate, '.')) {
768
                // 支持场景
769
                list($validate, $scene) = explode('.', $validate);
770
            }
771
772
            $class = false !== strpos($validate, '\\') ? $validate : app()->parseClass('validate', $validate);
773
774
            $v = new $class();
775
776
            if (!empty($scene)) {
777
                $v->scene($scene);
778
            }
779
        }
780
781
        return $v->message($message)->batch($batch)->failException(true)->check($data);
782
    }
783
}
784
785
if (!function_exists('view')) {
786
    /**
787
     * 渲染模板输出
788
     * @param string    $template 模板文件
1 ignored issue
show
Coding Style introduced by
Tag value for @param tag indented incorrectly; expected 2 spaces but found 1
Loading history...
789
     * @param array     $vars 模板变量
1 ignored issue
show
Coding Style introduced by
Expected 5 spaces after parameter name; 1 found
Loading history...
Coding Style introduced by
Tag value for @param tag indented incorrectly; expected 2 spaces but found 1
Loading history...
790
     * @param int       $code 状态码
1 ignored issue
show
Coding Style introduced by
Expected 5 spaces after parameter name; 1 found
Loading history...
Coding Style introduced by
Tag value for @param tag indented incorrectly; expected 2 spaces but found 1
Loading history...
791
     * @param callable  $filter 内容过滤
1 ignored issue
show
Coding Style introduced by
Expected 3 spaces after parameter name; 1 found
Loading history...
Coding Style introduced by
Tag value for @param tag indented incorrectly; expected 2 spaces but found 1
Loading history...
792
     * @return \think\response\View
793
     */
794
    function view(string $template = '', $vars = [], $code = 200, $filter = null)
795
    {
796
        return Response::create($template, 'view', $code)->assign($vars)->filter($filter);
0 ignored issues
show
Bug introduced by
The method assign() does not exist on think\Response. It seems like you code against a sub-type of think\Response such as think\response\View. ( Ignorable by Annotation )

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

796
        return Response::create($template, 'view', $code)->/** @scrutinizer ignore-call */ assign($vars)->filter($filter);
Loading history...
797
    }
798
}
799
800
if (!function_exists('xml')) {
801
    /**
802
     * 获取\think\response\Xml对象实例
803
     * @param  mixed $data    返回的数据
804
     * @param  int   $code    状态码
805
     * @param  array $header  头部
806
     * @param  array $options 参数
807
     * @return \think\response\Xml
808
     */
809
    function xml($data = [], $code = 200, $header = [], $options = [])
810
    {
811
        return Response::create($data, 'xml', $code)->header($header)->options($options);
812
    }
813
}
814
815
if (!function_exists('yaconf')) {
816
    /**
817
     * 获取yaconf配置
818
     *
819
     * @param  string $name    配置参数名
820
     * @param  mixed  $default 默认值
821
     * @return mixed
822
     */
823
    function yaconf(string $name, $default = null)
824
    {
825
        return Config::yaconf($name, $default);
826
    }
827
}
828