Issues (183)

src/helper.php (1 issue)

php_analyzer.type_inference.infeasible_condition.generic

Unknown
1
<?php
2
// +----------------------------------------------------------------------
3
// | ThinkPHP [ WE CAN DO IT JUST THINK ]
4
// +----------------------------------------------------------------------
5
// | Copyright (c) 2006~2021 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\exception\HttpException;
20
use think\exception\HttpResponseException;
21
use think\facade\Cache;
22
use think\facade\Config;
23
use think\facade\Cookie;
24
use think\facade\Env;
25
use think\facade\Event;
26
use think\facade\Lang;
27
use think\facade\Log;
28
use think\facade\Request;
29
use think\facade\Route;
30
use think\facade\Session;
31
use think\Response;
32
use think\response\File;
33
use think\response\Json;
34
use think\response\Jsonp;
35
use think\response\Redirect;
36
use think\response\View;
37
use think\response\Xml;
38
use think\route\Url as UrlBuild;
39
use think\Validate;
40
41
if (!function_exists('abort')) {
42
    /**
43
     * 抛出HTTP异常
44
     * @param integer|Response $code    状态码 或者 Response对象实例
45
     * @param string           $message 错误信息
46
     * @param array            $header  参数
47
     */
48
    function abort($code, string $message = '', array $header = [])
49
    {
50
        if ($code instanceof Response) {
51
            throw new HttpResponseException($code);
52
        } else {
53
            throw new HttpException($code, $message, null, $header);
54
        }
55
    }
56
}
57
58
if (!function_exists('app')) {
59
    /**
60
     * 快速获取容器中的实例 支持依赖注入
61
     * @template T
62
     * @param string|class-string<T> $name        类名或标识 默认获取当前应用实例
63
     * @param array                  $args        参数
64
     * @param bool                   $newInstance 是否每次创建新的实例
65
     * @return T|object|App
66
     */
67
    function app(string $name = '', array $args = [], bool $newInstance = false)
68
    {
69
        return Container::getInstance()->make($name ?: App::class, $args, $newInstance);
70
    }
71
}
72
73
if (!function_exists('bind')) {
74
    /**
75
     * 绑定一个类到容器
76
     * @param string|array $abstract 类标识、接口(支持批量绑定)
77
     * @param mixed        $concrete 要绑定的类、闭包或者实例
78
     * @return Container
79
     */
80
    function bind($abstract, $concrete = null)
81
    {
82
        return Container::getInstance()->bind($abstract, $concrete);
83
    }
84
}
85
86
if (!function_exists('cache')) {
87
    /**
88
     * 缓存管理
89
     * @param string $name    缓存名称
90
     * @param mixed  $value   缓存值
91
     * @param mixed  $options 缓存参数
92
     * @param string $tag     缓存标签
93
     * @return mixed
94
     */
95
    function cache(string $name = null, $value = '', $options = null, $tag = null)
96
    {
97
        if (is_null($name)) {
98
            return app('cache');
99
        }
100
101
        if ('' === $value) {
102
            // 获取缓存
103
            return 0 === strpos($name, '?') ? Cache::has(substr($name, 1)) : Cache::get($name);
104
        } elseif (is_null($value)) {
105
            // 删除缓存
106
            return Cache::delete($name);
107
        }
108
109
        // 缓存数据
110
        if (is_array($options)) {
111
            $expire = $options['expire'] ?? null; //修复查询缓存无法设置过期时间
112
        } else {
113
            $expire = $options;
114
        }
115
116
        if (is_null($tag)) {
117
            return Cache::set($name, $value, $expire);
118
        } else {
119
            return Cache::tag($tag)->set($name, $value, $expire);
120
        }
121
    }
122
}
123
124
if (!function_exists('config')) {
125
    /**
126
     * 获取和设置配置参数
127
     * @param string|array $name  参数名
128
     * @param mixed        $value 参数值
129
     * @return mixed
130
     */
131
    function config($name = '', $value = null)
132
    {
133
        if (is_array($name)) {
134
            return Config::set($name, $value);
135
        }
136
137
        return 0 === strpos($name, '?') ? Config::has(substr($name, 1)) : Config::get($name, $value);
138
    }
139
}
140
141
if (!function_exists('cookie')) {
142
    /**
143
     * Cookie管理
144
     * @param string $name   cookie名称
145
     * @param mixed  $value  cookie值
146
     * @param mixed  $option 参数
147
     * @return mixed
148
     */
149
    function cookie(string $name, $value = '', $option = null)
150
    {
151
        if (is_null($value)) {
152
            // 删除
153
            Cookie::delete($name, $option ?: []);
154
        } elseif ('' === $value) {
155
            // 获取
156
            return 0 === strpos($name, '?') ? Cookie::has(substr($name, 1)) : Cookie::get($name);
157
        } else {
158
            // 设置
159
            return Cookie::set($name, $value, $option);
160
        }
161
    }
162
}
163
164
if (!function_exists('download')) {
165
    /**
166
     * 获取\think\response\Download对象实例
167
     * @param string $filename 要下载的文件
168
     * @param string $name     显示文件名
169
     * @param bool   $content  是否为内容
170
     * @param int    $expire   有效期(秒)
171
     * @return \think\response\File
172
     */
173
    function download(string $filename, string $name = '', bool $content = false, int $expire = 180): File
174
    {
175
        return Response::create($filename, 'file')->name($name)->isContent($content)->expire($expire);
176
    }
177
}
178
179
if (!function_exists('dump')) {
180
    /**
181
     * 浏览器友好的变量输出
182
     * @param mixed $vars 要输出的变量
183
     * @return void
184
     */
185
    function dump(...$vars)
186
    {
187
        ob_start();
188
        var_dump(...$vars);
189
190
        $output = ob_get_clean();
191
        $output = preg_replace('/\]\=\>\n(\s+)/m', '] => ', $output);
192
193
        if (PHP_SAPI == 'cli') {
194
            $output = PHP_EOL . $output . PHP_EOL;
195
        } else {
196
            if (!extension_loaded('xdebug')) {
197
                $output = htmlspecialchars($output, ENT_SUBSTITUTE);
198
            }
199
            $output = '<pre>' . $output . '</pre>';
200
        }
201
202
        echo $output;
203
    }
204
}
205
206
if (!function_exists('env')) {
207
    /**
208
     * 获取环境变量值
209
     * @access public
210
     * @param string $name    环境变量名(支持二级 .号分割)
211
     * @param string $default 默认值
212
     * @return mixed
213
     */
214
    function env(string $name = null, $default = null)
215
    {
216
        return Env::get($name, $default);
217
    }
218
}
219
220
if (!function_exists('event')) {
221
    /**
222
     * 触发事件
223
     * @param mixed $event 事件名(或者类名)
224
     * @param mixed $args  参数
225
     * @return mixed
226
     */
227
    function event($event, $args = null)
228
    {
229
        return Event::trigger($event, $args);
230
    }
231
}
232
233
if (!function_exists('halt')) {
234
    /**
235
     * 调试变量并且中断输出
236
     * @param mixed $vars 调试变量或者信息
237
     */
238
    function halt(...$vars)
239
    {
240
        dump(...$vars);
241
242
        throw new HttpResponseException(Response::create());
243
    }
244
}
245
246
if (!function_exists('input')) {
247
    /**
248
     * 获取输入数据 支持默认值和过滤
249
     * @param string $key     获取的变量名
250
     * @param mixed  $default 默认值
251
     * @param string $filter  过滤方法
252
     * @return mixed
253
     */
254
    function input(string $key = '', $default = null, $filter = '')
255
    {
256
        if (0 === strpos($key, '?')) {
257
            $key = substr($key, 1);
258
            $has = true;
259
        }
260
261
        if ($pos = strpos($key, '.')) {
262
            // 指定参数来源
263
            $method = substr($key, 0, $pos);
264
            if (in_array($method, ['get', 'post', 'put', 'patch', 'delete', 'route', 'param', 'request', 'session', 'cookie', 'server', 'env', 'path', 'file'])) {
265
                $key = substr($key, $pos + 1);
266
                if ('server' == $method && is_null($default)) {
267
                    $default = '';
268
                }
269
            } else {
270
                $method = 'param';
271
            }
272
        } else {
273
            // 默认为自动判断
274
            $method = 'param';
275
        }
276
277
        return isset($has) ?
278
        request()->has($key, $method) :
279
        request()->$method($key, $default, $filter);
280
    }
281
}
282
283
if (!function_exists('invoke')) {
284
    /**
285
     * 调用反射实例化对象或者执行方法 支持依赖注入
286
     * @param mixed $call 类名或者callable
287
     * @param array $args 参数
288
     * @return mixed
289
     */
290
    function invoke($call, array $args = [])
291
    {
292
        if (is_callable($call)) {
293
            return Container::getInstance()->invoke($call, $args);
294
        }
295
296
        return Container::getInstance()->invokeClass($call, $args);
297
    }
298
}
299
300
if (!function_exists('json')) {
301
    /**
302
     * 获取\think\response\Json对象实例
303
     * @param mixed $data    返回的数据
304
     * @param int   $code    状态码
305
     * @param array $header  头部
306
     * @param array $options 参数
307
     * @return \think\response\Json
308
     */
309
    function json($data = [], $code = 200, $header = [], $options = []): Json
310
    {
311
        return Response::create($data, 'json', $code)->header($header)->options($options);
312
    }
313
}
314
315
if (!function_exists('jsonp')) {
316
    /**
317
     * 获取\think\response\Jsonp对象实例
318
     * @param mixed $data    返回的数据
319
     * @param int   $code    状态码
320
     * @param array $header  头部
321
     * @param array $options 参数
322
     * @return \think\response\Jsonp
323
     */
324
    function jsonp($data = [], $code = 200, $header = [], $options = []): Jsonp
325
    {
326
        return Response::create($data, 'jsonp', $code)->header($header)->options($options);
327
    }
328
}
329
330
if (!function_exists('lang')) {
331
    /**
332
     * 获取语言变量值
333
     * @param string $name 语言变量名
334
     * @param array  $vars 动态变量值
335
     * @param string $lang 语言
336
     * @return mixed
337
     */
338
    function lang(string $name, array $vars = [], string $lang = '')
339
    {
340
        return Lang::get($name, $vars, $lang);
341
    }
342
}
343
344
if (!function_exists('parse_name')) {
345
    /**
346
     * 字符串命名风格转换
347
     * type 0 将Java风格转换为C的风格 1 将C风格转换为Java的风格
348
     * @param string $name    字符串
349
     * @param int    $type    转换类型
350
     * @param bool   $ucfirst 首字母是否大写(驼峰规则)
351
     * @return string
352
     */
353
    function parse_name(string $name, int $type = 0, bool $ucfirst = true): string
354
    {
355
        if ($type) {
356
            $name = preg_replace_callback('/_([a-zA-Z])/', function ($match) {
357
                return strtoupper($match[1]);
358
            }, $name);
359
360
            return $ucfirst ? ucfirst($name) : lcfirst($name);
361
        }
362
363
        return strtolower(trim(preg_replace('/[A-Z]/', '_\\0', $name), '_'));
364
    }
365
}
366
367
if (!function_exists('redirect')) {
368
    /**
369
     * 获取\think\response\Redirect对象实例
370
     * @param string $url  重定向地址
371
     * @param int    $code 状态码
372
     * @return \think\response\Redirect
373
     */
374
    function redirect(string $url = '', int $code = 302): Redirect
375
    {
376
        return Response::create($url, 'redirect', $code);
377
    }
378
}
379
380
if (!function_exists('request')) {
381
    /**
382
     * 获取当前Request对象实例
383
     * @return Request
384
     */
385
    function request(): \think\Request
386
    {
387
        return app('request');
388
    }
389
}
390
391
if (!function_exists('response')) {
392
    /**
393
     * 创建普通 Response 对象实例
394
     * @param mixed      $data   输出数据
395
     * @param int|string $code   状态码
396
     * @param array      $header 头信息
397
     * @param string     $type
398
     * @return Response
399
     */
400
    function response($data = '', $code = 200, $header = [], $type = 'html'): Response
401
    {
402
        return Response::create($data, $type, $code)->header($header);
403
    }
404
}
405
406
if (!function_exists('session')) {
407
    /**
408
     * Session管理
409
     * @param string $name  session名称
410
     * @param mixed  $value session值
411
     * @return mixed
412
     */
413
    function session($name = '', $value = '')
414
    {
415
        if (is_null($name)) {
0 ignored issues
show
The condition is_null($name) is always false.
Loading history...
416
            // 清除
417
            Session::clear();
418
        } elseif ('' === $name) {
419
            return Session::all();
420
        } elseif (is_null($value)) {
421
            // 删除
422
            Session::delete($name);
423
        } elseif ('' === $value) {
424
            // 判断或获取
425
            return 0 === strpos($name, '?') ? Session::has(substr($name, 1)) : Session::get($name);
426
        } else {
427
            // 设置
428
            Session::set($name, $value);
429
        }
430
    }
431
}
432
433
if (!function_exists('token')) {
434
    /**
435
     * 获取Token令牌
436
     * @param string $name 令牌名称
437
     * @param mixed  $type 令牌生成方法
438
     * @return string
439
     */
440
    function token(string $name = '__token__', string $type = 'md5'): string
441
    {
442
        return Request::buildToken($name, $type);
443
    }
444
}
445
446
if (!function_exists('token_field')) {
447
    /**
448
     * 生成令牌隐藏表单
449
     * @param string $name 令牌名称
450
     * @param mixed  $type 令牌生成方法
451
     * @return string
452
     */
453
    function token_field(string $name = '__token__', string $type = 'md5'): string
454
    {
455
        $token = Request::buildToken($name, $type);
456
457
        return '<input type="hidden" name="' . $name . '" value="' . $token . '" />';
458
    }
459
}
460
461
if (!function_exists('token_meta')) {
462
    /**
463
     * 生成令牌meta
464
     * @param string $name 令牌名称
465
     * @param mixed  $type 令牌生成方法
466
     * @return string
467
     */
468
    function token_meta(string $name = '__token__', string $type = 'md5'): string
469
    {
470
        $token = Request::buildToken($name, $type);
471
472
        return '<meta name="csrf-token" content="' . $token . '">';
473
    }
474
}
475
476
if (!function_exists('trace')) {
477
    /**
478
     * 记录日志信息
479
     * @param mixed  $log   log信息 支持字符串和数组
480
     * @param string $level 日志级别
481
     * @return array|void
482
     */
483
    function trace($log = '[think]', string $level = 'log')
484
    {
485
        if ('[think]' === $log) {
486
            return Log::getLog();
487
        }
488
489
        Log::record($log, $level);
490
    }
491
}
492
493
if (!function_exists('url')) {
494
    /**
495
     * Url生成
496
     * @param string      $url    路由地址
497
     * @param array       $vars   变量
498
     * @param bool|string $suffix 生成的URL后缀
499
     * @param bool|string $domain 域名
500
     * @return UrlBuild
501
     */
502
    function url(string $url = '', array $vars = [], $suffix = true, $domain = false): UrlBuild
503
    {
504
        return Route::buildUrl($url, $vars)->suffix($suffix)->domain($domain);
505
    }
506
}
507
508
if (!function_exists('validate')) {
509
    /**
510
     * 生成验证对象
511
     * @param string|array $validate      验证器类名或者验证规则数组
512
     * @param array        $message       错误提示信息
513
     * @param bool         $batch         是否批量验证
514
     * @param bool         $failException 是否抛出异常
515
     * @return Validate
516
     */
517
    function validate($validate = '', array $message = [], bool $batch = false, bool $failException = true): Validate
518
    {
519
        if (is_array($validate) || '' === $validate) {
520
            $v = new Validate();
521
            if (is_array($validate)) {
522
                $v->rule($validate);
523
            }
524
        } else {
525
            if (strpos($validate, '.')) {
526
                // 支持场景
527
                [$validate, $scene] = explode('.', $validate);
528
            }
529
530
            $class = false !== strpos($validate, '\\') ? $validate : app()->parseClass('validate', $validate);
531
532
            $v = new $class();
533
534
            if (!empty($scene)) {
535
                $v->scene($scene);
536
            }
537
        }
538
539
        return $v->message($message)->batch($batch)->failException($failException);
540
    }
541
}
542
543
if (!function_exists('view')) {
544
    /**
545
     * 渲染模板输出
546
     * @param string   $template 模板文件
547
     * @param array    $vars     模板变量
548
     * @param int      $code     状态码
549
     * @param callable $filter   内容过滤
550
     * @return \think\response\View
551
     */
552
    function view(string $template = '', $vars = [], $code = 200, $filter = null): View
553
    {
554
        return Response::create($template, 'view', $code)->assign($vars)->filter($filter);
555
    }
556
}
557
558
if (!function_exists('display')) {
559
    /**
560
     * 渲染模板输出
561
     * @param string   $content 渲染内容
562
     * @param array    $vars    模板变量
563
     * @param int      $code    状态码
564
     * @param callable $filter  内容过滤
565
     * @return \think\response\View
566
     */
567
    function display(string $content, $vars = [], $code = 200, $filter = null): View
568
    {
569
        return Response::create($content, 'view', $code)->isContent(true)->assign($vars)->filter($filter);
570
    }
571
}
572
573
if (!function_exists('xml')) {
574
    /**
575
     * 获取\think\response\Xml对象实例
576
     * @param mixed $data    返回的数据
577
     * @param int   $code    状态码
578
     * @param array $header  头部
579
     * @param array $options 参数
580
     * @return \think\response\Xml
581
     */
582
    function xml($data = [], $code = 200, $header = [], $options = []): Xml
583
    {
584
        return Response::create($data, 'xml', $code)->header($header)->options($options);
585
    }
586
}
587
588
if (!function_exists('app_path')) {
589
    /**
590
     * 获取当前应用目录
591
     *
592
     * @param string $path
593
     * @return string
594
     */
595
    function app_path($path = '')
596
    {
597
        return app()->getAppPath() . ($path ? $path . DIRECTORY_SEPARATOR : $path);
598
    }
599
}
600
601
if (!function_exists('base_path')) {
602
    /**
603
     * 获取应用基础目录
604
     *
605
     * @param string $path
606
     * @return string
607
     */
608
    function base_path($path = '')
609
    {
610
        return app()->getBasePath() . ($path ? $path . DIRECTORY_SEPARATOR : $path);
611
    }
612
}
613
614
if (!function_exists('config_path')) {
615
    /**
616
     * 获取应用配置目录
617
     *
618
     * @param string $path
619
     * @return string
620
     */
621
    function config_path($path = '')
622
    {
623
        return app()->getConfigPath() . ($path ? $path . DIRECTORY_SEPARATOR : $path);
624
    }
625
}
626
627
if (!function_exists('public_path')) {
628
    /**
629
     * 获取web根目录
630
     *
631
     * @param string $path
632
     * @return string
633
     */
634
    function public_path($path = '')
635
    {
636
        return app()->getRootPath() . 'public' . DIRECTORY_SEPARATOR . ($path ? ltrim($path, DIRECTORY_SEPARATOR) . DIRECTORY_SEPARATOR : $path);
637
    }
638
}
639
640
if (!function_exists('runtime_path')) {
641
    /**
642
     * 获取应用运行时目录
643
     *
644
     * @param string $path
645
     * @return string
646
     */
647
    function runtime_path($path = '')
648
    {
649
        return app()->getRuntimePath() . ($path ? $path . DIRECTORY_SEPARATOR : $path);
650
    }
651
}
652
653
if (!function_exists('root_path')) {
654
    /**
655
     * 获取项目根目录
656
     *
657
     * @param string $path
658
     * @return string
659
     */
660
    function root_path($path = '')
661
    {
662
        return app()->getRootPath() . ($path ? $path . DIRECTORY_SEPARATOR : $path);
663
    }
664
}
665