Completed
Push — 6.0 ( ec6ebc...6a45c3 )
by liu
03:05
created

token_field()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 5
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 1
eloc 2
c 0
b 0
f 0
nc 1
nop 2
dl 0
loc 5
rs 10
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 = App::class, array $args = [], bool $newInstance = false)
65
    {
66
        return Container::pull($name, $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)
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 void
289
     */
290
    function error($msg = '', string $url = null, $data = '', int $wait = 3, array $header = []): void
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);
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
        throw new HttpResponseException($response);
314
    }
315
}
316
317
if (!function_exists('event')) {
318
    /**
319
     * 触发事件
320
     * @param  mixed $event 事件名(或者类名)
321
     * @param  mixed $args  参数
322
     * @return mixed
323
     */
324
    function event($event, $args = null)
325
    {
326
        return Event::trigger($event, $args);
327
    }
328
}
329
330
if (!function_exists('exception')) {
331
    /**
332
     * 抛出异常处理
333
     *
334
     * @param string $msg       异常消息
335
     * @param int    $code      异常代码 默认为0
336
     * @param string $exception 异常类
337
     *
338
     * @throws Exception
339
     */
0 ignored issues
show
Coding Style introduced by
Missing @return tag in function comment
Loading history...
340
    function exception(string $msg, int $code = 0, string $exception = '')
341
    {
342
        $e = $exception ?: '\think\Exception';
343
        throw new $e($msg, $code);
344
    }
345
}
346
347
if (!function_exists('halt')) {
348
    /**
349
     * 调试变量并且中断输出
350
     * @param mixed $var 调试变量或者信息
351
     */
0 ignored issues
show
Coding Style introduced by
Missing @return tag in function comment
Loading history...
352
    function halt($var)
353
    {
354
        dump($var);
355
356
        throw new HttpResponseException(new Response);
357
    }
358
}
359
360
if (!function_exists('input')) {
361
    /**
362
     * 获取输入数据 支持默认值和过滤
363
     * @param  string $key     获取的变量名
364
     * @param  mixed  $default 默认值
365
     * @param  string $filter  过滤方法
366
     * @return mixed
367
     */
368
    function input(string $key = '', $default = null, $filter = '')
369
    {
370
        if (0 === strpos($key, '?')) {
371
            $key = substr($key, 1);
372
            $has = true;
373
        }
374
375
        if ($pos = strpos($key, '.')) {
376
            // 指定参数来源
377
            $method = substr($key, 0, $pos);
378
            if (in_array($method, ['get', 'post', 'put', 'patch', 'delete', 'route', 'param', 'request', 'session', 'cookie', 'server', 'env', 'path', 'file'])) {
379
                $key = substr($key, $pos + 1);
380
            } else {
381
                $method = 'param';
382
            }
383
        } else {
384
            // 默认为自动判断
385
            $method = 'param';
386
        }
387
388
        return isset($has) ?
389
        request()->has($key, $method) :
390
        request()->$method($key, $default, $filter);
391
    }
392
}
393
394
if (!function_exists('invoke')) {
395
    /**
396
     * 调用反射实例化对象 支持依赖注入
397
     * @param  string $class 类名
398
     * @param  array  $args  参数
399
     * @return mixed
400
     */
401
    function invoke(string $class, array $args = [])
402
    {
403
        return Container::getInstance()->invokeClass($class, $args);
404
    }
405
}
406
407
if (!function_exists('json')) {
408
    /**
409
     * 获取\think\response\Json对象实例
410
     * @param  mixed $data    返回的数据
411
     * @param  int   $code    状态码
412
     * @param  array $header  头部
413
     * @param  array $options 参数
414
     * @return \think\response\Json
415
     */
416
    function json($data = [], $code = 200, $header = [], $options = [])
417
    {
418
        return Response::create($data, 'json', $code)->header($header)->options($options);
419
    }
420
}
421
422
if (!function_exists('jsonp')) {
423
    /**
424
     * 获取\think\response\Jsonp对象实例
425
     * @param  mixed $data    返回的数据
426
     * @param  int   $code    状态码
427
     * @param  array $header  头部
428
     * @param  array $options 参数
429
     * @return \think\response\Jsonp
430
     */
431
    function jsonp($data = [], $code = 200, $header = [], $options = [])
432
    {
433
        return Response::create($data, 'jsonp', $code)->header($header)->options($options);
434
    }
435
}
436
437
if (!function_exists('lang')) {
438
    /**
439
     * 获取语言变量值
440
     * @param  string $name 语言变量名
441
     * @param  array  $vars 动态变量值
442
     * @param  string $lang 语言
443
     * @return mixed
444
     */
445
    function lang(string $name, array $vars = [], string $lang = '')
446
    {
447
        return Lang::get($name, $vars, $lang);
448
    }
449
}
450
451
if (!function_exists('parse_name')) {
452
    /**
453
     * 字符串命名风格转换
454
     * type 0 将Java风格转换为C的风格 1 将C风格转换为Java的风格
455
     * @param  string $name    字符串
456
     * @param  int    $type    转换类型
457
     * @param  bool   $ucfirst 首字母是否大写(驼峰规则)
458
     * @return string
459
     */
460
    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...
461
    {
462
        if ($type) {
463
            $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...
464
                return strtoupper($match[1]);
465
            }, $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...
466
467
            return $ucfirst ? ucfirst($name) : lcfirst($name);
468
        }
469
470
        return strtolower(trim(preg_replace("/[A-Z]/", "_\\0", $name), "_"));
471
    }
472
}
473
474
if (!function_exists('raw')) {
475
    /**
476
     * 生成一个数据库的Raw对象
477
     * @param  string $sql SQL指令
478
     * @return \think\db\Raw
479
     */
480
    function raw(string $sql): Raw
481
    {
482
        return Db::raw($sql);
483
    }
484
}
485
486
if (!function_exists('redirect')) {
487
    /**
488
     * 获取\think\response\Redirect对象实例
489
     * @param  mixed         $url    重定向地址 支持Url::build方法的地址
490
     * @param  array|integer $params 额外参数
491
     * @param  int           $code   状态码
492
     * @return \think\response\Redirect
493
     */
494
    function redirect($url = [], $params = [], $code = 302)
495
    {
496
        if (is_integer($params)) {
497
            $code   = $params;
498
            $params = [];
499
        }
500
501
        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

501
        return Response::create($url, 'redirect', $code)->/** @scrutinizer ignore-call */ params($params);
Loading history...
502
    }
503
}
504
505
if (!function_exists('request')) {
506
    /**
507
     * 获取当前Request对象实例
508
     * @return Request
509
     */
510
    function request()
511
    {
512
        return app('request');
513
    }
514
}
515
516
if (!function_exists('response')) {
517
    /**
518
     * 创建普通 Response 对象实例
519
     * @param  mixed      $data   输出数据
520
     * @param  int|string $code   状态码
521
     * @param  array      $header 头信息
522
     * @param  string     $type
0 ignored issues
show
Coding Style introduced by
Missing parameter comment
Loading history...
523
     * @return Response
524
     */
525
    function response($data = '', $code = 200, $header = [], $type = 'html')
526
    {
527
        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

527
        return Response::create($data, $type, /** @scrutinizer ignore-type */ $code)->header($header);
Loading history...
528
    }
529
}
530
531
if (!function_exists('result')) {
532
    /**
533
     * 返回封装后的API数据到客户端
534
     * @param  mixed   $data 要返回的数据
0 ignored issues
show
Coding Style introduced by
Expected 3 spaces after parameter name; 1 found
Loading history...
535
     * @param  integer $code 返回的code
0 ignored issues
show
Coding Style introduced by
Expected 3 spaces after parameter name; 1 found
Loading history...
536
     * @param  mixed   $msg 提示信息
0 ignored issues
show
Coding Style introduced by
Expected 4 spaces after parameter name; 1 found
Loading history...
537
     * @param  string  $type 返回数据格式
0 ignored issues
show
Coding Style introduced by
Expected 3 spaces after parameter name; 1 found
Loading history...
538
     * @param  array   $header 发送的Header信息
539
     * @return void
540
     */
541
    function result($data, int $code = 0, $msg = '', string $type = '', array $header = []): void
542
    {
543
        $result = [
544
            'code' => $code,
545
            'msg'  => $msg,
546
            'time' => time(),
547
            'data' => $data,
548
        ];
549
550
        $type     = $type ?: 'json';
551
        $response = Response::create($result, $type)->header($header);
552
553
        throw new HttpResponseException($response);
554
    }
555
}
556
557
if (!function_exists('route')) {
558
    /**
559
     * 路由注册
560
     * @param  string $rule   路由规则
561
     * @param  mixed  $route  路由地址
562
     * @param  string $method 请求类型
563
     * @return RuleItem
564
     */
565
    function route(string $rule, $route, $method = '*'): RuleItem
566
    {
567
        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

567
        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...
568
    }
569
}
570
571
if (!function_exists('session')) {
572
    /**
573
     * Session管理
574
     * @param  string $name  session名称
575
     * @param  mixed  $value session值
576
     * @return mixed
577
     */
578
    function session(string $name = null, $value = '')
579
    {
580
        if (is_null($name)) {
581
            // 清除
582
            Session::clear();
583
        } elseif (is_null($value)) {
584
            // 删除
585
            Session::delete($name);
586
        } elseif ('' === $value) {
587
            // 判断或获取
588
            return 0 === strpos($name, '?') ? Session::has(substr($name, 1)) : Session::get($name);
589
        } else {
590
            // 设置
591
            Session::set($name, $value);
592
        }
593
    }
594
}
595
596
if (!function_exists('success')) {
597
    /**
598
     * 操作成功跳转的快捷方法
599
     * @param  mixed     $msg 提示信息
0 ignored issues
show
Coding Style introduced by
Expected 4 spaces after parameter name; 1 found
Loading history...
600
     * @param  string    $url 跳转的URL地址
0 ignored issues
show
Coding Style introduced by
Expected 4 spaces after parameter name; 1 found
Loading history...
601
     * @param  mixed     $data 返回的数据
0 ignored issues
show
Coding Style introduced by
Expected 3 spaces after parameter name; 1 found
Loading history...
602
     * @param  integer   $wait 跳转等待时间
0 ignored issues
show
Coding Style introduced by
Expected 3 spaces after parameter name; 1 found
Loading history...
603
     * @param  array     $header 发送的Header信息
604
     * @return void
605
     */
606
    function success($msg = '', string $url = null, $data = '', int $wait = 3, array $header = []): void
607
    {
608
        if (is_null($url) && isset($_SERVER["HTTP_REFERER"])) {
609
            $url = $_SERVER["HTTP_REFERER"];
610
        } elseif ($url) {
611
            $url = (strpos($url, '://') || 0 === strpos($url, '/')) ? $url : app('route')->buildUrl($url);
612
        }
613
614
        $result = [
615
            'code' => 1,
616
            'msg'  => $msg,
617
            'data' => $data,
618
            'url'  => $url,
619
            'wait' => $wait,
620
        ];
621
622
        $type = (request()->isJson() || request()->isAjax()) ? 'json' : 'html';
623
        // 把跳转模板的渲染下沉,这样在 response_send 行为里通过getData()获得的数据是一致性的格式
624
        if ('html' == strtolower($type)) {
625
            $type = 'jump';
626
        }
627
628
        $response = Response::create($result, $type)->header($header)->options(['jump_template' => app('config')->get('app.dispatch_success_tmpl')]);
629
630
        throw new HttpResponseException($response);
631
    }
632
}
633
634
if (!function_exists('token')) {
635
    /**
636
     * 获取Token令牌
637
     * @param  string $name 令牌名称
638
     * @param  mixed  $type 令牌生成方法
639
     * @return string
640
     */
641
    function token(string $name = '__token__', string $type = 'md5'): string
642
    {
643
        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

643
        return Request::/** @scrutinizer ignore-call */ buildToken($name, $type);
Loading history...
644
    }
645
}
646
647
if (!function_exists('token_field')) {
648
    /**
649
     * 生成令牌隐藏表单
650
     * @param  string $name 令牌名称
651
     * @param  mixed  $type 令牌生成方法
652
     * @return string
653
     */
654
    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...
655
    {
656
        $token = Request::buildToken($name, $type);
657
658
        return '<input type="hidden" name="' . $name . '" value="' . $token . '" />';
659
    }
660
}
661
662
if (!function_exists('token_meta')) {
663
    /**
664
     * 生成令牌meta
665
     * @param  string $name 令牌名称
666
     * @param  mixed  $type 令牌生成方法
667
     * @return string
668
     */
669
    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...
670
    {
671
        $token = Request::buildToken($name, $type);
672
673
        return '<meta name="csrf-token" content="' . $token . '">';
674
    }
675
}
676
677
if (!function_exists('trace')) {
678
    /**
679
     * 记录日志信息
680
     * @param  mixed  $log   log信息 支持字符串和数组
681
     * @param  string $level 日志级别
682
     * @return array|void
683
     */
684
    function trace($log = '[think]', string $level = 'log')
685
    {
686
        if ('[think]' === $log) {
687
            return Log::getLog();
688
        }
689
690
        Log::record($log, $level);
691
    }
692
}
693
694
if (!function_exists('trait_uses_recursive')) {
695
    /**
696
     * 获取一个trait里所有引用到的trait
697
     *
698
     * @param  string $trait Trait
699
     * @return array
700
     */
701
    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...
702
    {
703
        $traits = class_uses($trait);
704
        foreach ($traits as $trait) {
705
            $traits += trait_uses_recursive($trait);
706
        }
707
708
        return $traits;
709
    }
710
}
711
712
if (!function_exists('url')) {
713
    /**
714
     * Url生成
715
     * @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...
716
     * @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...
717
     * @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...
718
     * @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...
719
     * @return string
720
     */
721
    function url(string $url = '', array $vars = [], $suffix = true, $domain = false): string
722
    {
723
        return Route::buildUrl($url, $vars, $suffix, $domain);
724
    }
725
}
726
727
if (!function_exists('validate')) {
728
    /**
729
     * 验证数据
730
     * @param  array        $data     数据
731
     * @param  string|array $validate 验证器名或者验证规则数组
732
     * @param  array        $message  提示信息
733
     * @param  bool         $batch    是否批量验证
734
     * @return bool
735
     * @throws ValidateException
736
     */
737
    function validate(array $data, $validate, array $message = [], bool $batch = false): bool
738
    {
739
        if (is_array($validate)) {
740
            $v = new Validate();
741
            $v->rule($validate);
742
        } else {
743
            if (strpos($validate, '.')) {
744
                // 支持场景
745
                list($validate, $scene) = explode('.', $validate);
746
            }
747
748
            $class = app()->parseClass('validate', $validate);
749
            $v     = new $class();
750
751
            if (!empty($scene)) {
752
                $v->scene($scene);
753
            }
754
        }
755
756
        return $v->message($message)->batch($batch)->failException(true)->check($data);
757
    }
758
}
759
760
if (!function_exists('view')) {
761
    /**
762
     * 渲染模板输出
763
     * @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...
764
     * @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...
765
     * @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...
766
     * @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...
767
     * @return \think\response\View
768
     */
769
    function view(string $template = '', $vars = [], $code = 200, $filter = null)
770
    {
771
        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

771
        return Response::create($template, 'view', $code)->/** @scrutinizer ignore-call */ assign($vars)->filter($filter);
Loading history...
772
    }
773
}
774
775
if (!function_exists('xml')) {
776
    /**
777
     * 获取\think\response\Xml对象实例
778
     * @param  mixed $data    返回的数据
779
     * @param  int   $code    状态码
780
     * @param  array $header  头部
781
     * @param  array $options 参数
782
     * @return \think\response\Xml
783
     */
784
    function xml($data = [], $code = 200, $header = [], $options = [])
785
    {
786
        return Response::create($data, 'xml', $code)->header($header)->options($options);
787
    }
788
}
789
790
if (!function_exists('yaconf')) {
791
    /**
792
     * 获取yaconf配置
793
     *
794
     * @param  string $name    配置参数名
795
     * @param  mixed  $default 默认值
796
     * @return mixed
797
     */
798
    function yaconf(string $name, $default = null)
799
    {
800
        return Config::yaconf($name, $default);
801
    }
802
}
803