Passed
Push — 8.0 ( a38b61...0c3de4 )
by liu
10:57
created

Request::url()   B

Complexity

Conditions 8
Paths 14

Size

Total Lines 17
Code Lines 13

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 72

Importance

Changes 0
Metric Value
cc 8
eloc 13
nc 14
nop 1
dl 0
loc 17
ccs 0
cts 13
cp 0
crap 72
rs 8.4444
c 0
b 0
f 0
1
<?php
2
// +----------------------------------------------------------------------
3
// | ThinkPHP [ WE CAN DO IT JUST THINK ]
4
// +----------------------------------------------------------------------
5
// | Copyright (c) 2006~2023 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
namespace think;
14
15
use ArrayAccess;
16
use think\facade\Lang;
0 ignored issues
show
Bug introduced by
This use statement conflicts with another class in this namespace, think\Lang. 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...
17
use think\file\UploadedFile;
18
use think\route\Rule;
19
20
/**
21
 * 请求管理类
22
 * @package think
23
 */
24
class Request implements ArrayAccess
25
{
26
    /**
27
     * 兼容PATH_INFO获取
28
     * @var array
29
     */
30
    protected $pathinfoFetch = ['ORIG_PATH_INFO', 'REDIRECT_PATH_INFO', 'REDIRECT_URL'];
31
32
    /**
33
     * PATHINFO变量名 用于兼容模式
34
     * @var string
35
     */
36
    protected $varPathinfo = 's';
37
38
    /**
39
     * 请求类型
40
     * @var string
41
     */
42
    protected $varMethod = '_method';
43
44
    /**
45
     * 表单ajax伪装变量
46
     * @var string
47
     */
48
    protected $varAjax = '_ajax';
49
50
    /**
51
     * 表单pjax伪装变量
52
     * @var string
53
     */
54
    protected $varPjax = '_pjax';
55
56
    /**
57
     * 域名根
58
     * @var string
59
     */
60
    protected $rootDomain = '';
61
62
    /**
63
     * 特殊域名根标识 用于识别com.cn org.cn 这种
64
     * @var array
65
     */
66
    protected $domainSpecialSuffix = ['com', 'net', 'org', 'edu', 'gov', 'mil', 'co', 'info'];
67
68
    /**
69
     * HTTPS代理标识
70
     * @var string
71
     */
72
    protected $httpsAgentName = '';
73
74
    /**
75
     * 前端代理服务器IP
76
     * @var array
77
     */
78
    protected $proxyServerIp = [];
79
80
    /**
81
     * 前端代理服务器真实IP头
82
     * @var array
83
     */
84
    protected $proxyServerIpHeader = ['HTTP_X_REAL_IP', 'HTTP_X_FORWARDED_FOR', 'HTTP_CLIENT_IP', 'HTTP_X_CLIENT_IP', 'HTTP_X_CLUSTER_CLIENT_IP'];
85
86
    /**
87
     * 请求类型
88
     * @var string
89
     */
90
    protected $method;
91
92
    /**
93
     * 域名(含协议及端口)
94
     * @var string
95
     */
96
    protected $domain;
97
98
    /**
99
     * HOST(含端口)
100
     * @var string
101
     */
102
    protected $host;
103
104
    /**
105
     * 子域名
106
     * @var string
107
     */
108
    protected $subDomain;
109
110
    /**
111
     * 泛域名
112
     * @var string
113
     */
114
    protected $panDomain;
115
116
    /**
117
     * 当前URL地址
118
     * @var string
119
     */
120
    protected $url;
121
122
    /**
123
     * 基础URL
124
     * @var string
125
     */
126
    protected $baseUrl;
127
128
    /**
129
     * 当前执行的文件
130
     * @var string
131
     */
132
    protected $baseFile;
133
134
    /**
135
     * 访问的ROOT地址
136
     * @var string
137
     */
138
    protected $root;
139
140
    /**
141
     * pathinfo
142
     * @var string
143
     */
144
    protected $pathinfo;
145
146
    /**
147
     * pathinfo(不含后缀)
148
     * @var string
149
     */
150
    protected $path;
151
152
    /**
153
     * 当前请求的IP地址
154
     * @var string
155
     */
156
    protected $realIP;
157
158
    /**
159
     * 当前控制器名
160
     * @var string
161
     */
162
    protected $controller;
163
164
    /**
165
     * 当前操作名
166
     * @var string
167
     */
168
    protected $action;
169
170
    /**
171
     * 当前请求参数
172
     * @var array
173
     */
174
    protected $param = [];
175
176
    /**
177
     * 当前GET参数
178
     * @var array
179
     */
180
    protected $get = [];
181
182
    /**
183
     * 当前POST参数
184
     * @var array
185
     */
186
    protected $post = [];
187
188
    /**
189
     * 当前REQUEST参数
190
     * @var array
191
     */
192
    protected $request = [];
193
194
    /**
195
     * 当前路由对象
196
     * @var Rule
197
     */
198
    protected $rule;
199
200
    /**
201
     * 当前ROUTE参数
202
     * @var array
203
     */
204
    protected $route = [];
205
206
    /**
207
     * 中间件传递的参数
208
     * @var array
209
     */
210
    protected $middleware = [];
211
212
    /**
213
     * 当前PUT参数
214
     * @var array
215
     */
216
    protected $put;
217
218
    /**
219
     * SESSION对象
220
     * @var Session
221
     */
222
    protected $session;
223
224
    /**
225
     * COOKIE数据
226
     * @var array
227
     */
228
    protected $cookie = [];
229
230
    /**
231
     * ENV对象
232
     * @var Env
233
     */
234
    protected $env;
235
236
    /**
237
     * 当前SERVER参数
238
     * @var array
239
     */
240
    protected $server = [];
241
242
    /**
243
     * 当前FILE参数
244
     * @var array
245
     */
246
    protected $file = [];
247
248
    /**
249
     * 当前HEADER参数
250
     * @var array
251
     */
252
    protected $header = [];
253
254
    /**
255
     * 资源类型定义
256
     * @var array
257
     */
258
    protected $mimeType = [
259
        'xml'   => 'application/xml,text/xml,application/x-xml',
260
        'json'  => 'application/json,text/x-json,application/jsonrequest,text/json',
261
        'js'    => 'text/javascript,application/javascript,application/x-javascript',
262
        'css'   => 'text/css',
263
        'rss'   => 'application/rss+xml',
264
        'yaml'  => 'application/x-yaml,text/yaml',
265
        'atom'  => 'application/atom+xml',
266
        'pdf'   => 'application/pdf',
267
        'text'  => 'text/plain',
268
        'image' => 'image/png,image/jpg,image/jpeg,image/pjpeg,image/gif,image/webp,image/*',
269
        'csv'   => 'text/csv',
270
        'html'  => 'text/html,application/xhtml+xml,*/*',
271
    ];
272
273
    /**
274
     * 当前请求内容
275
     * @var string
276
     */
277
    protected $content;
278
279
    /**
280
     * 全局过滤规则
281
     * @var array
282
     */
283
    protected $filter;
284
285
    /**
286
     * php://input内容
287
     * @var string
288
     */
289
    // php://input
290
    protected $input;
291
292
    /**
293
     * 请求安全Key
294
     * @var string
295
     */
296
    protected $secureKey;
297
298
    /**
299
     * 是否合并Param
300
     * @var bool
301
     */
302
    protected $mergeParam = false;
303
304
    /**
305
     * 架构函数
306
     * @access public
307
     */
308 27
    public function __construct()
309
    {
310
        // 保存 php://input
311 27
        $this->input = file_get_contents('php://input');
312
    }
313
314 27
    public static function __make(App $app)
315
    {
316 27
        $request = new static();
317
318 27
        if (function_exists('apache_request_headers') && $result = apache_request_headers()) {
319
            $header = $result;
320
        } else {
321 27
            $header = [];
322 27
            $server = $_SERVER;
323 27
            foreach ($server as $key => $val) {
324 27
                if (str_starts_with($key, 'HTTP_')) {
325
                    $key          = str_replace('_', '-', strtolower(substr($key, 5)));
326
                    $header[$key] = $val;
327
                }
328
            }
329 27
            if (isset($server['CONTENT_TYPE'])) {
330
                $header['content-type'] = $server['CONTENT_TYPE'];
331
            }
332 27
            if (isset($server['CONTENT_LENGTH'])) {
333
                $header['content-length'] = $server['CONTENT_LENGTH'];
334
            }
335
        }
336
337 27
        $request->header = array_change_key_case($header);
0 ignored issues
show
Bug introduced by
It seems like $header can also be of type true; however, parameter $array of array_change_key_case() does only seem to accept array, 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

337
        $request->header = array_change_key_case(/** @scrutinizer ignore-type */ $header);
Loading history...
338 27
        $request->server = $_SERVER;
339 27
        $request->env    = $app->env;
340
341 27
        $inputData = $request->getInputData($request->input);
342
343 27
        $request->get     = $_GET;
344 27
        $request->post    = $_POST ?: $inputData;
345 27
        $request->put     = $inputData;
346 27
        $request->request = $_REQUEST;
347 27
        $request->cookie  = $_COOKIE;
348 27
        $request->file    = $_FILES ?? [];
349
350 27
        return $request;
351
    }
352
353
    /**
354
     * 设置当前包含协议的域名
355
     * @access public
356
     * @param  string $domain 域名
357
     * @return $this
358
     */
359
    public function setDomain(string $domain)
360
    {
361
        $this->domain = $domain;
362
        return $this;
363
    }
364
365
    /**
366
     * 获取当前包含协议的域名
367
     * @access public
368
     * @param  bool $port 是否需要去除端口号
369
     * @return string
370
     */
371
    public function domain(bool $port = false): string
372
    {
373
        return $this->scheme() . '://' . $this->host($port);
374
    }
375
376
    /**
377
     * 获取当前根域名
378
     * @access public
379
     * @return string
380
     */
381 27
    public function rootDomain(): string
382
    {
383 27
        $root = $this->rootDomain;
384
385 27
        if (!$root) {
386 27
            $item  = explode('.', $this->host(true));
387 27
            $count = count($item);
388 27
            if ($count > 1) {
389 3
                $root = $item[$count - 2] . '.' . $item[$count - 1];
390 3
                if ($count > 2 && in_array($item[$count - 2], $this->domainSpecialSuffix)) {
391 3
                    $root = $item[$count - 3] . '.' . $root;
392
                }
393
            } else {
394 24
                $root  = $item[0];
395
            }
396
        }
397
398 27
        return $root;
399
    }
400
401
    /**
402
     * 设置当前泛域名的值
403
     * @access public
404
     * @param  string $domain 域名
405
     * @return $this
406
     */
407
    public function setSubDomain(string $domain)
408
    {
409
        $this->subDomain = $domain;
410
        return $this;
411
    }
412
413
    /**
414
     * 获取当前子域名
415
     * @access public
416
     * @return string
417
     */
418 27
    public function subDomain(): string
419
    {
420 27
        if (is_null($this->subDomain)) {
0 ignored issues
show
introduced by
The condition is_null($this->subDomain) is always false.
Loading history...
421
            // 获取当前主域名
422 27
            $rootDomain = $this->rootDomain();
423
424 27
            if ($rootDomain) {
425 27
                $sub             = stristr($this->host(), $rootDomain, true);
426 27
                $this->subDomain = $sub ? rtrim($sub, '.') : '';
427
            } else {
428
                $this->subDomain = '';
429
            }
430
        }
431
432 27
        return $this->subDomain;
433
    }
434
435
    /**
436
     * 设置当前泛域名的值
437
     * @access public
438
     * @param  string $domain 域名
439
     * @return $this
440
     */
441
    public function setPanDomain(string $domain)
442
    {
443
        $this->panDomain = $domain;
444
        return $this;
445
    }
446
447
    /**
448
     * 获取当前泛域名的值
449
     * @access public
450
     * @return string
451
     */
452 3
    public function panDomain(): string
453
    {
454 3
        return $this->panDomain ?: '';
455
    }
456
457
    /**
458
     * 设置当前完整URL 包括QUERY_STRING
459
     * @access public
460
     * @param  string $url URL地址
461
     * @return $this
462
     */
463
    public function setUrl(string $url)
464
    {
465
        $this->url = $url;
466
        return $this;
467
    }
468
469
    /**
470
     * 获取当前完整URL 包括QUERY_STRING
471
     * @access public
472
     * @param  bool $complete 是否包含完整域名
473
     * @return string
474
     */
475
    public function url(bool $complete = false): string
476
    {
477
        if ($this->url) {
478
            $url = $this->url;
479
        } elseif ($this->server('HTTP_X_REWRITE_URL')) {
480
            $url = $this->server('HTTP_X_REWRITE_URL');
481
        } elseif ($this->server('REQUEST_URI')) {
482
            $url = $this->server('REQUEST_URI');
483
        } elseif ($this->server('ORIG_PATH_INFO')) {
484
            $url = $this->server('ORIG_PATH_INFO') . (!empty($this->server('QUERY_STRING')) ? '?' . $this->server('QUERY_STRING') : '');
485
        } elseif (isset($_SERVER['argv'][1])) {
486
            $url = $_SERVER['argv'][1];
487
        } else {
488
            $url = '';
489
        }
490
491
        return $complete ? $this->domain() . $url : $url;
492
    }
493
494
    /**
495
     * 设置当前URL 不含QUERY_STRING
496
     * @access public
497
     * @param  string $url URL地址
498
     * @return $this
499
     */
500
    public function setBaseUrl(string $url)
501
    {
502
        $this->baseUrl = $url;
503
        return $this;
504
    }
505
506
    /**
507
     * 获取当前URL 不含QUERY_STRING
508
     * @access public
509
     * @param  bool $complete 是否包含完整域名
510
     * @return string
511
     */
512
    public function baseUrl(bool $complete = false): string
513
    {
514
        if (!$this->baseUrl) {
515
            $str           = $this->url();
516
            $this->baseUrl = str_contains($str, '?') ? strstr($str, '?', true) : $str;
517
        }
518
519
        return $complete ? $this->domain() . $this->baseUrl : $this->baseUrl;
520
    }
521
522
    /**
523
     * 获取当前执行的文件 SCRIPT_NAME
524
     * @access public
525
     * @param  bool $complete 是否包含完整域名
526
     * @return string
527
     */
528
    public function baseFile(bool $complete = false): string
529
    {
530
        if (!$this->baseFile) {
531
            $url = '';
532
            if (!$this->isCli()) {
533
                $script_name = basename($this->server('SCRIPT_FILENAME'));
534
                if (basename($this->server('SCRIPT_NAME')) === $script_name) {
535
                    $url = $this->server('SCRIPT_NAME');
536
                } elseif (basename($this->server('PHP_SELF')) === $script_name) {
537
                    $url = $this->server('PHP_SELF');
538
                } elseif (basename($this->server('ORIG_SCRIPT_NAME')) === $script_name) {
539
                    $url = $this->server('ORIG_SCRIPT_NAME');
540
                } elseif (($pos = strpos($this->server('PHP_SELF'), '/' . $script_name)) !== false) {
541
                    $url = substr($this->server('SCRIPT_NAME'), 0, $pos) . '/' . $script_name;
542
                } elseif ($this->server('DOCUMENT_ROOT') && str_starts_with($this->server('SCRIPT_FILENAME'), $this->server('DOCUMENT_ROOT'))) {
543
                    $url = str_replace('\\', '/', str_replace($this->server('DOCUMENT_ROOT'), '', $this->server('SCRIPT_FILENAME')));
544
                }
545
            }
546
            $this->baseFile = $url;
547
        }
548
549
        return $complete ? $this->domain() . $this->baseFile : $this->baseFile;
550
    }
551
552
    /**
553
     * 设置URL访问根地址
554
     * @access public
555
     * @param  string $url URL地址
556
     * @return $this
557
     */
558
    public function setRoot(string $url)
559
    {
560
        $this->root = $url;
561
        return $this;
562
    }
563
564
    /**
565
     * 获取URL访问根地址
566
     * @access public
567
     * @param  bool $complete 是否包含完整域名
568
     * @return string
569
     */
570
    public function root(bool $complete = false): string
571
    {
572
        if (!$this->root) {
573
            $file = $this->baseFile();
574
            if ($file && !str_starts_with($this->url(), $file)) {
575
                $file = str_replace('\\', '/', dirname($file));
576
            }
577
            $this->root = rtrim($file, '/');
578
        }
579
580
        return $complete ? $this->domain() . $this->root : $this->root;
581
    }
582
583
    /**
584
     * 获取URL访问根目录
585
     * @access public
586
     * @return string
587
     */
588
    public function rootUrl(): string
589
    {
590
        $base = $this->root();
591
        $root = str_contains($base, '.') ? ltrim(dirname($base), DIRECTORY_SEPARATOR) : $base;
592
593
        if ('' != $root) {
594
            $root = '/' . ltrim($root, '/');
595
        }
596
597
        return $root;
598
    }
599
600
    /**
601
     * 设置当前请求的pathinfo
602
     * @access public
603
     * @param  string $pathinfo
604
     * @return $this
605
     */
606
    public function setPathinfo(string $pathinfo)
607
    {
608
        $this->pathinfo = $pathinfo;
609
        return $this;
610
    }
611
612
    /**
613
     * 获取当前请求URL的pathinfo信息(含URL后缀)
614
     * @access public
615
     * @return string
616
     */
617
    public function pathinfo(): string
618
    {
619
        if (is_null($this->pathinfo)) {
0 ignored issues
show
introduced by
The condition is_null($this->pathinfo) is always false.
Loading history...
620
            if (isset($_GET[$this->varPathinfo])) {
621
                // 判断URL里面是否有兼容模式参数
622
                $pathinfo = $_GET[$this->varPathinfo];
623
                unset($_GET[$this->varPathinfo]);
624
                unset($this->get[$this->varPathinfo]);
625
            } elseif ($this->server('PATH_INFO')) {
626
                $pathinfo = $this->server('PATH_INFO');
627
            } elseif (str_contains(PHP_SAPI, 'cli')) {
628
                $pathinfo = str_contains($this->server('REQUEST_URI'), '?') ? strstr($this->server('REQUEST_URI'), '?', true) : $this->server('REQUEST_URI');
629
            }
630
631
            // 分析PATHINFO信息
632
            if (!isset($pathinfo)) {
633
                foreach ($this->pathinfoFetch as $type) {
634
                    if ($this->server($type)) {
635
                        $pathinfo = str_starts_with($this->server($type), $this->server('SCRIPT_NAME')) ?
636
                            substr($this->server($type), strlen($this->server('SCRIPT_NAME'))) : $this->server($type);
637
                        break;
638
                    }
639
                }
640
            }
641
642
            if (!empty($pathinfo)) {
643
                unset($this->get[$pathinfo], $this->request[$pathinfo]);
644
            }
645
646
            $this->pathinfo = empty($pathinfo) || '/' == $pathinfo ? '' : ltrim($pathinfo, '/');
647
        }
648
649
        return $this->pathinfo;
650
    }
651
652
    /**
653
     * 当前URL的访问后缀
654
     * @access public
655
     * @return string
656
     */
657
    public function ext(): string
658
    {
659
        return pathinfo($this->pathinfo(), PATHINFO_EXTENSION);
660
    }
661
662
    /**
663
     * 获取当前请求的时间
664
     * @access public
665
     * @param  bool $float 是否使用浮点类型
666
     * @return integer|float
667
     */
668
    public function time(bool $float = false)
669
    {
670
        return $float ? $this->server('REQUEST_TIME_FLOAT') : $this->server('REQUEST_TIME');
671
    }
672
673
    /**
674
     * 当前请求的资源类型
675
     * @access public
676
     * @return string
677
     */
678 21
    public function type(): string
679
    {
680 21
        $accept = $this->server('HTTP_ACCEPT');
681
682 21
        if (empty($accept)) {
683 21
            return '';
684
        }
685
686
        foreach ($this->mimeType as $key => $val) {
687
            $array = explode(',', $val);
688
            foreach ($array as $k => $v) {
689
                if (stristr($accept, $v)) {
690
                    return $key;
691
                }
692
            }
693
        }
694
695
        return '';
696
    }
697
698
    /**
699
     * 设置资源类型
700
     * @access public
701
     * @param  string|array $type 资源类型名
702
     * @param  string       $val 资源类型
703
     * @return void
704
     */
705
    public function mimeType($type, $val = ''): void
706
    {
707
        if (is_array($type)) {
708
            $this->mimeType = array_merge($this->mimeType, $type);
709
        } else {
710
            $this->mimeType[$type] = $val;
711
        }
712
    }
713
714
    /**
715
     * 设置请求类型
716
     * @access public
717
     * @param  string $method 请求类型
718
     * @return $this
719
     */
720
    public function setMethod(string $method)
721
    {
722
        $this->method = strtoupper($method);
723
        return $this;
724
    }
725
726
    /**
727
     * 当前的请求类型
728
     * @access public
729
     * @param  bool $origin 是否获取原始请求类型
730
     * @return string
731
     */
732
    public function method(bool $origin = false): string
733
    {
734
        if ($origin) {
735
            // 获取原始请求类型
736
            return $this->server('REQUEST_METHOD') ?: 'GET';
737
        } elseif (!$this->method) {
738
            if (isset($this->post[$this->varMethod])) {
739
                $method = strtolower($this->post[$this->varMethod]);
740
                if (in_array($method, ['get', 'post', 'put', 'patch', 'delete'])) {
741
                    $this->method    = strtoupper($method);
742
                    $this->{$method} = $this->post;
743
                } else {
744
                    $this->method = 'POST';
745
                }
746
                unset($this->post[$this->varMethod]);
747
            } elseif ($this->server('HTTP_X_HTTP_METHOD_OVERRIDE')) {
748
                $this->method = strtoupper($this->server('HTTP_X_HTTP_METHOD_OVERRIDE'));
749
            } else {
750
                $this->method = $this->server('REQUEST_METHOD') ?: 'GET';
751
            }
752
        }
753
754
        return $this->method;
755
    }
756
757
    /**
758
     * 是否为GET请求
759
     * @access public
760
     * @return bool
761
     */
762
    public function isGet(): bool
763
    {
764
        return $this->method() == 'GET';
765
    }
766
767
    /**
768
     * 是否为POST请求
769
     * @access public
770
     * @return bool
771
     */
772
    public function isPost(): bool
773
    {
774
        return $this->method() == 'POST';
775
    }
776
777
    /**
778
     * 是否为PUT请求
779
     * @access public
780
     * @return bool
781
     */
782
    public function isPut(): bool
783
    {
784
        return $this->method() == 'PUT';
785
    }
786
787
    /**
788
     * 是否为DELTE请求
789
     * @access public
790
     * @return bool
791
     */
792
    public function isDelete(): bool
793
    {
794
        return $this->method() == 'DELETE';
795
    }
796
797
    /**
798
     * 是否为HEAD请求
799
     * @access public
800
     * @return bool
801
     */
802
    public function isHead(): bool
803
    {
804
        return $this->method() == 'HEAD';
805
    }
806
807
    /**
808
     * 是否为PATCH请求
809
     * @access public
810
     * @return bool
811
     */
812
    public function isPatch(): bool
813
    {
814
        return $this->method() == 'PATCH';
815
    }
816
817
    /**
818
     * 是否为OPTIONS请求
819
     * @access public
820
     * @return bool
821
     */
822
    public function isOptions(): bool
823
    {
824
        return $this->method() == 'OPTIONS';
825
    }
826
827
    /**
828
     * 是否为cli
829
     * @access public
830
     * @return bool
831
     */
832
    public function isCli(): bool
833
    {
834
        return PHP_SAPI == 'cli';
835
    }
836
837
    /**
838
     * 是否为cgi
839
     * @access public
840
     * @return bool
841
     */
842
    public function isCgi(): bool
843
    {
844
        return str_starts_with(PHP_SAPI, 'cgi');
845
    }
846
847
    /**
848
     * 获取当前请求的参数
849
     * @access public
850
     * @param  string|array $name 变量名
851
     * @param  mixed        $default 默认值
852
     * @param  string|array $filter 过滤方法
853
     * @return mixed
854
     */
855 27
    public function param($name = '', $default = null, $filter = '')
856
    {
857 27
        if (empty($this->mergeParam)) {
858 27
            $method = $this->method(true);
859
860
            // 自动获取请求变量
861 27
            $vars   =   match ($method) {
862 27
                'POST'  =>  $this->post(false),
863 27
                'PUT','DELETE','PATCH'  =>  $this->put(false),
864 27
                default =>  [],
865 27
            };
866
867
            // 当前请求参数和URL地址中的参数合并
868 27
            $this->param = array_merge($this->param, $this->get(false), $vars, $this->route(false));
0 ignored issues
show
Bug introduced by
It seems like $this->get(false) can also be of type null and object; however, parameter $arrays of array_merge() does only seem to accept array, 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

868
            $this->param = array_merge($this->param, /** @scrutinizer ignore-type */ $this->get(false), $vars, $this->route(false));
Loading history...
869
870 27
            $this->mergeParam = true;
871
        }
872
873 27
        if (is_array($name)) {
874
            return $this->only($name, $this->param, $filter);
875
        }
876
877 27
        return $this->input($this->param, $name, $default, $filter);
878
    }
879
880
    /**
881
     * 获取包含文件在内的请求参数
882
     * @access public
883
     * @param  string|array $name 变量名
884
     * @param  string|array $filter 过滤方法
885
     * @return mixed
886
     */
887
    public function all(string|array $name = '', string|array $filter = '')
888
    {
889
        $data = array_merge($this->param(), $this->file() ?: []);
0 ignored issues
show
Bug introduced by
It seems like $this->param() can also be of type null and object; however, parameter $arrays of array_merge() does only seem to accept array, 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

889
        $data = array_merge(/** @scrutinizer ignore-type */ $this->param(), $this->file() ?: []);
Loading history...
Bug introduced by
It seems like $this->file() ?: array() can also be of type think\file\UploadedFile; however, parameter $arrays of array_merge() does only seem to accept array, 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

889
        $data = array_merge($this->param(), /** @scrutinizer ignore-type */ $this->file() ?: []);
Loading history...
890
891
        if (is_array($name)) {
892
            $data = $this->only($name, $data, $filter);
893
        } elseif ($name) {
894
            $data = $data[$name] ?? null;
895
        }
896
897
        return $data;
898
    }
899
900
    /**
901
     * 设置路由变量
902
     * @access public
903
     * @param  Rule $rule 路由对象
904
     * @return $this
905
     */
906 27
    public function setRule(Rule $rule)
907
    {
908 27
        $this->rule = $rule;
909 27
        return $this;
910
    }
911
912
    /**
913
     * 获取当前路由对象
914
     * @access public
915
     * @return Rule|null
916
     */
917 3
    public function rule()
918
    {
919 3
        return $this->rule;
920
    }
921
922
    /**
923
     * 设置路由变量
924
     * @access public
925
     * @param  array $route 路由变量
926
     * @return $this
927
     */
928 27
    public function setRoute(array $route)
929
    {
930 27
        $this->route      = array_merge($this->route, $route);
931 27
        $this->mergeParam = false;
932 27
        return $this;
933
    }
934
935
    /**
936
     * 获取路由参数
937
     * @access public
938
     * @param  string|array|bool $name 变量名
939
     * @param  mixed        $default 默认值
940
     * @param  string|array $filter 过滤方法
941
     * @return mixed
942
     */
943 27
    public function route(string|array|bool $name = '', $default = null, string|array $filter = '')
944
    {
945 27
        if (is_array($name)) {
946
            return $this->only($name, $this->route, $filter);
947
        }
948
949 27
        return $this->input($this->route, $name, $default, $filter);
950
    }
951
952
    /**
953
     * 获取GET参数
954
     * @access public
955
     * @param  string|array|bool $name 变量名
956
     * @param  mixed        $default 默认值
957
     * @param  string|array $filter 过滤方法
958
     * @return mixed
959
     */
960 27
    public function get(string|array|bool $name = '', $default = null, string|array $filter = '')
961
    {
962 27
        if (is_array($name)) {
963
            return $this->only($name, $this->get, $filter);
964
        }
965
966 27
        return $this->input($this->get, $name, $default, $filter);
967
    }
968
969
    /**
970
     * 获取中间件传递的参数
971
     * @access public
972
     * @param  string $name 变量名
973
     * @param  mixed $default 默认值
974
     * @return mixed
975
     */
976
    public function middleware(string $name, $default = null)
977
    {
978
        return $this->middleware[$name] ?? $default;
979
    }
980
981
    /**
982
     * 获取POST参数
983
     * @access public
984
     * @param  bool|string|array $name 变量名
985
     * @param  mixed        $default 默认值
986
     * @param  string|array $filter 过滤方法
987
     * @return mixed
988
     */
989 3
    public function post(string|array|bool $name = '', $default = null, string|array $filter = '')
990
    {
991 3
        if (is_array($name)) {
992
            return $this->only($name, $this->post, $filter);
993
        }
994
995 3
        return $this->input($this->post, $name, $default, $filter);
996
    }
997
998
    /**
999
     * 获取PUT参数
1000
     * @access public
1001
     * @param  string|array|bool $name 变量名
1002
     * @param  mixed        $default 默认值
1003
     * @param  string|array $filter 过滤方法
1004
     * @return mixed
1005
     */
1006
    public function put(string|array|bool $name = '', $default = null, string|array $filter = '')
1007
    {
1008
        if (is_array($name)) {
1009
            return $this->only($name, $this->put, $filter);
1010
        }
1011
1012
        return $this->input($this->put, $name, $default, $filter);
1013
    }
1014
1015 27
    protected function getInputData(string $content): array
1016
    {
1017 27
        $contentType = $this->contentType();
1018 27
        if ('application/x-www-form-urlencoded' == $contentType) {
1019
            parse_str($content, $data);
1020
            return $data;
1021 27
        } elseif (str_contains($contentType, 'json')) {
1022
            return (array) json_decode($content, true);
1023
        }
1024
1025 27
        return [];
1026
    }
1027
1028
    /**
1029
     * 设置获取DELETE参数
1030
     * @access public
1031
     * @param  mixed        $name 变量名
1032
     * @param  mixed        $default 默认值
1033
     * @param  string|array $filter 过滤方法
1034
     * @return mixed
1035
     */
1036
    public function delete(string|array|bool $name = '', $default = null, string|array $filter = '')
1037
    {
1038
        return $this->put($name, $default, $filter);
1039
    }
1040
1041
    /**
1042
     * 设置获取PATCH参数
1043
     * @access public
1044
     * @param  mixed        $name 变量名
1045
     * @param  mixed        $default 默认值
1046
     * @param  string|array $filter 过滤方法
1047
     * @return mixed
1048
     */
1049
    public function patch(string|array|bool $name = '', $default = null, string|array $filter = '')
1050
    {
1051
        return $this->put($name, $default, $filter);
1052
    }
1053
1054
    /**
1055
     * 获取request变量
1056
     * @access public
1057
     * @param  string|array $name 数据名称
1058
     * @param  mixed        $default 默认值
1059
     * @param  string|array $filter 过滤方法
1060
     * @return mixed
1061
     */
1062
    public function request(string|array|bool $name = '', $default = null, string|array $filter = '')
1063
    {
1064
        if (is_array($name)) {
1065
            return $this->only($name, $this->request, $filter);
1066
        }
1067
1068
        return $this->input($this->request, $name, $default, $filter);
1069
    }
1070
1071
    /**
1072
     * 获取环境变量
1073
     * @access public
1074
     * @param  string $name 数据名称
1075
     * @param  string $default 默认值
1076
     * @return mixed
1077
     */
1078
    public function env(string $name = '', string $default = null)
1079
    {
1080
        if (empty($name)) {
1081
            return $this->env->get();
1082
        }
1083
        return $this->env->get(strtoupper($name), $default);
1084
    }
1085
1086
    /**
1087
     * 获取session数据
1088
     * @access public
1089
     * @param  string $name 数据名称
1090
     * @param  string $default 默认值
1091
     * @return mixed
1092
     */
1093
    public function session(string $name = '', $default = null)
1094
    {
1095
        if ('' === $name) {
1096
            return $this->session->all();
0 ignored issues
show
Bug introduced by
The method all() does not exist on think\Session. Since you implemented __call, 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

1096
            return $this->session->/** @scrutinizer ignore-call */ all();
Loading history...
1097
        }
1098
        return $this->session->get($name, $default);
0 ignored issues
show
Bug introduced by
The method get() does not exist on think\Session. Since you implemented __call, 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

1098
        return $this->session->/** @scrutinizer ignore-call */ get($name, $default);
Loading history...
1099
    }
1100
1101
    /**
1102
     * 获取cookie参数
1103
     * @access public
1104
     * @param  mixed        $name 数据名称
1105
     * @param  string       $default 默认值
1106
     * @param  string|array $filter 过滤方法
1107
     * @return mixed
1108
     */
1109
    public function cookie(string $name = '', $default = null, $filter = '')
1110
    {
1111
        if (!empty($name)) {
1112
            $data = $this->getData($this->cookie, $name, $default);
1113
        } else {
1114
            $data = $this->cookie;
1115
        }
1116
1117
        // 解析过滤器
1118
        $filter = $this->getFilter($filter, $default);
1119
1120
        if (is_array($data)) {
1121
            array_walk_recursive($data, [$this, 'filterValue'], $filter);
1122
        } else {
1123
            $this->filterValue($data, $name, $filter);
1124
        }
1125
1126
        return $data;
1127
    }
1128
1129
    /**
1130
     * 获取server参数
1131
     * @access public
1132
     * @param  string $name 数据名称
1133
     * @param  string $default 默认值
1134
     * @return mixed
1135
     */
1136 21
    public function server(string $name = '', string $default = '')
1137
    {
1138 21
        if (empty($name)) {
1139
            return $this->server;
1140
        }
1141 21
        return $this->server[strtoupper($name)] ?? $default;
1142
    }
1143
1144
    /**
1145
     * 获取上传的文件信息
1146
     * @access public
1147
     * @param  string $name 名称
1148
     * @return null|array|UploadedFile
1149
     */
1150
    public function file(string $name = '')
1151
    {
1152
        $files = $this->file;
1153
        if (!empty($files)) {
1154
            if (str_contains($name, '.')) {
1155
                [$name, $sub] = explode('.', $name);
1156
            }
1157
1158
            // 处理上传文件
1159
            $array = $this->dealUploadFile($files, $name);
1160
1161
            if ('' === $name) {
1162
                // 获取全部文件
1163
                return $array;
1164
            } elseif (isset($sub) && isset($array[$name][$sub])) {
1165
                return $array[$name][$sub];
1166
            } elseif (isset($array[$name])) {
1167
                return $array[$name];
1168
            }
1169
        }
1170
    }
1171
1172
    protected function dealUploadFile(array $files, string $name): array
1173
    {
1174
        $array = [];
1175
        foreach ($files as $key => $file) {
1176
            if (is_array($file['name'])) {
1177
                $item  = [];
1178
                $keys  = array_keys($file);
1179
                $count = count($file['name']);
1180
1181
                for ($i = 0; $i < $count; $i++) {
1182
                    if ($file['error'][$i] > 0) {
1183
                        if ($name == $key) {
1184
                            $this->throwUploadFileError($file['error'][$i]);
1185
                        } else {
1186
                            continue;
1187
                        }
1188
                    }
1189
1190
                    $temp['key'] = $key;
1191
1192
                    foreach ($keys as $_key) {
1193
                        $temp[$_key] = $file[$_key][$i];
1194
                    }
1195
1196
                    $item[] = new UploadedFile($temp['tmp_name'], $temp['name'], $temp['type'], $temp['error']);
1197
                }
1198
1199
                $array[$key] = $item;
1200
            } else {
1201
                if ($file instanceof File) {
1202
                    $array[$key] = $file;
1203
                } else {
1204
                    if ($file['error'] > 0) {
1205
                        if ($key == $name) {
1206
                            $this->throwUploadFileError($file['error']);
1207
                        } else {
1208
                            continue;
1209
                        }
1210
                    }
1211
1212
                    $array[$key] = new UploadedFile($file['tmp_name'], $file['name'], $file['type'], $file['error']);
1213
                }
1214
            }
1215
        }
1216
1217
        return $array;
1218
    }
1219
1220
    protected function throwUploadFileError($error)
1221
    {
1222
        static $fileUploadErrors = [
1223
            1 => 'upload File size exceeds the maximum value',
1224
            2 => 'upload File size exceeds the maximum value',
1225
            3 => 'only the portion of file is uploaded',
1226
            4 => 'no file to uploaded',
1227
            6 => 'upload temp dir not found',
1228
            7 => 'file write error',
1229
        ];
1230
1231
        $msg = Lang::get($fileUploadErrors[$error]);
0 ignored issues
show
Bug introduced by
The method get() does not exist on think\facade\Lang. 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

1231
        /** @scrutinizer ignore-call */ 
1232
        $msg = Lang::get($fileUploadErrors[$error]);
Loading history...
1232
        throw new Exception($msg, $error);
1233
    }
1234
1235
    /**
1236
     * 设置或者获取当前的Header
1237
     * @access public
1238
     * @param  string $name header名称
1239
     * @param  string $default 默认值
1240
     * @return string|array|null
1241
     */
1242 27
    public function header(string $name = '', string $default = null)
1243
    {
1244 27
        if ('' === $name) {
1245
            return $this->header;
1246
        }
1247
1248 27
        $name = str_replace('_', '-', strtolower($name));
1249 27
        return $this->header[$name] ?? $default;
1250
    }
1251
1252
    /**
1253
     * 获取变量 支持过滤和默认值
1254
     * @access public
1255
     * @param  array        $data 数据源
1256
     * @param  string|false $name 字段名
1257
     * @param  mixed        $default 默认值
1258
     * @param  string|array $filter 过滤函数
1259
     * @return mixed
1260
     */
1261 27
    public function input(array $data = [], string|bool $name = '', $default = null, string|array $filter = '')
1262
    {
1263 27
        if (false === $name) {
1264
            // 获取原始数据
1265 27
            return $data;
1266
        }
1267
1268 27
        $name = (string) $name;
1269 27
        if ('' != $name) {
1270
            // 解析name
1271
            if (str_contains($name, '/')) {
1272
                [$name, $type] = explode('/', $name);
1273
            }
1274
1275
            $data = $this->getData($data, $name);
1276
1277
            if (is_null($data)) {
1278
                return $default;
1279
            }
1280
1281
            if (is_object($data)) {
1282
                return $data;
1283
            }
1284
        }
1285
1286 27
        $data = $this->filterData($data, $filter, $name, $default);
1287
1288 27
        if (isset($type) && $data !== $default) {
1289
            // 强制类型转换
1290
            $this->typeCast($data, $type);
1291
        }
1292
1293 27
        return $data;
1294
    }
1295
1296 27
    protected function filterData($data, $filter, $name, $default)
1297
    {
1298
        // 解析过滤器
1299 27
        $filter = $this->getFilter($filter, $default);
1300
1301 27
        if (is_array($data)) {
1302 27
            array_walk_recursive($data, [$this, 'filterValue'], $filter);
1303
        } else {
1304
            $this->filterValue($data, $name, $filter);
1305
        }
1306
1307 27
        return $data;
1308
    }
1309
1310
    /**
1311
     * 强制类型转换
1312
     * @access protected
1313
     * @param  mixed  $data
1314
     * @param  string $type
1315
     * @return mixed
1316
     */
1317
    protected function typeCast(&$data, string $type)
1318
    {
1319
        $type = strtolower($type);
1320
        if (in_array($type, ['a', 'b', 'd', 'f', 's'])) {
1321
            $data   =   match ($type) {
1322
                'a'     =>  (array) $data,  // 数组
1323
                'b'     =>  (bool) $data,   // 布尔
1324
                'd'     =>  (int) $data,    // 数字
1325
                'f'     =>  (float) $data,  // 浮点
1326
                's'     =>  is_scalar($data) ? (string) $data : throw new \InvalidArgumentException('variable type error:' . gettype($data)), //字符串
1327
            };
1328
        }
1329
    }
1330
1331
    /**
1332
     * 获取数据
1333
     * @access protected
1334
     * @param  array  $data 数据源
1335
     * @param  string $name 字段名
1336
     * @param  mixed  $default 默认值
1337
     * @return mixed
1338
     */
1339
    protected function getData(array $data, string $name, $default = null)
1340
    {
1341
        foreach (explode('.', $name) as $val) {
1342
            if (isset($data[$val])) {
1343
                $data = $data[$val];
1344
            } else {
1345
                return $default;
1346
            }
1347
        }
1348
1349
        return $data;
1350
    }
1351
1352
    /**
1353
     * 设置或获取当前的过滤规则
1354
     * @access public
1355
     * @param  mixed $filter 过滤规则
1356
     * @return mixed
1357
     */
1358
    public function filter($filter = null)
1359
    {
1360
        if (is_null($filter)) {
1361
            return $this->filter;
1362
        }
1363
1364
        $this->filter = $filter;
1365
1366
        return $this;
1367
    }
1368
1369 27
    protected function getFilter($filter, $default): array
1370
    {
1371 27
        if (is_null($filter)) {
1372
            $filter = [];
1373
        } else {
1374 27
            $filter = $filter ?: $this->filter;
1375 27
            if (is_string($filter) && !str_contains($filter, '/')) {
1376
                $filter = explode(',', $filter);
1377
            } else {
1378 27
                $filter = (array) $filter;
1379
            }
1380
        }
1381
1382 27
        $filter[] = $default;
1383
1384 27
        return $filter;
1385
    }
1386
1387
    /**
1388
     * 递归过滤给定的值
1389
     * @access public
1390
     * @param  mixed $value 键值
1391
     * @param  mixed $key 键名
1392
     * @param  array $filters 过滤方法+默认值
1393
     * @return mixed
1394
     */
1395
    public function filterValue(&$value, $key, $filters)
1396
    {
1397
        $default = array_pop($filters);
1398
1399
        foreach ($filters as $filter) {
1400
            if (is_callable($filter)) {
1401
                // 调用函数或者方法过滤
1402
                if (is_null($value)) {
1403
                    continue;
1404
                }
1405
1406
                $value = call_user_func($filter, $value);
1407
            } elseif (is_scalar($value)) {
1408
                if (is_string($filter) && str_contains($filter, '/')) {
1409
                    // 正则过滤
1410
                    if (!preg_match($filter, $value)) {
1411
                        // 匹配不成功返回默认值
1412
                        $value = $default;
1413
                        break;
1414
                    }
1415
                } elseif (!empty($filter)) {
1416
                    // filter函数不存在时, 则使用filter_var进行过滤
1417
                    // filter为非整形值时, 调用filter_id取得过滤id
1418
                    $value = filter_var($value, is_int($filter) ? $filter : filter_id($filter));
1419
                    if (false === $value) {
1420
                        $value = $default;
1421
                        break;
1422
                    }
1423
                }
1424
            }
1425
        }
1426
1427
        return $value;
1428
    }
1429
1430
    /**
1431
     * 是否存在某个请求参数
1432
     * @access public
1433
     * @param  string $name 变量名
1434
     * @param  string $type 变量类型
1435
     * @param  bool   $checkEmpty 是否检测空值
1436
     * @return bool
1437
     */
1438
    public function has(string $name, string $type = 'param', bool $checkEmpty = false): bool
1439
    {
1440
        if (!in_array($type, ['param', 'get', 'post', 'put', 'patch', 'route', 'delete', 'cookie', 'session', 'env', 'request', 'server', 'header', 'file'])) {
1441
            return false;
1442
        }
1443
1444
        $param = empty($this->$type) ? $this->$type() : $this->$type;
1445
1446
        if (is_object($param)) {
1447
            return $param->has($name);
1448
        }
1449
1450
        // 按.拆分成多维数组进行判断
1451
        foreach (explode('.', $name) as $val) {
1452
            if (isset($param[$val])) {
1453
                $param = $param[$val];
1454
            } else {
1455
                return false;
1456
            }
1457
        }
1458
1459
        return ($checkEmpty && '' === $param) ? false : true;
1460
    }
1461
1462
    /**
1463
     * 获取指定的参数
1464
     * @access public
1465
     * @param  array        $name 变量名
1466
     * @param  mixed        $data 数据或者变量类型
1467
     * @param  string|array $filter 过滤方法
1468
     * @return array
1469
     */
1470
    public function only(array $name, $data = 'param', $filter = ''): array
1471
    {
1472
        $data = is_array($data) ? $data : $this->$data();
1473
1474
        $item = [];
1475
        foreach ($name as $key => $val) {
1476
1477
            if (is_int($key)) {
1478
                $default = null;
1479
                $key     = $val;
1480
                if (!key_exists($key, $data)) {
1481
                    continue;
1482
                }
1483
            } else {
1484
                $default = $val;
1485
            }
1486
1487
            $item[$key] = $this->filterData($data[$key] ?? $default, $filter, $key, $default);
1488
        }
1489
1490
        return $item;
1491
    }
1492
1493
    /**
1494
     * 排除指定参数获取
1495
     * @access public
1496
     * @param  array  $name 变量名
1497
     * @param  string $type 变量类型
1498
     * @return mixed
1499
     */
1500
    public function except(array $name, string $type = 'param'): array
1501
    {
1502
        $param = $this->$type();
1503
1504
        foreach ($name as $key) {
1505
            if (isset($param[$key])) {
1506
                unset($param[$key]);
1507
            }
1508
        }
1509
1510
        return $param;
1511
    }
1512
1513
    /**
1514
     * 当前是否ssl
1515
     * @access public
1516
     * @return bool
1517
     */
1518
    public function isSsl(): bool
1519
    {
1520
        if ($this->server('HTTPS') && ('1' == $this->server('HTTPS') || 'on' == strtolower($this->server('HTTPS')))) {
1521
            return true;
1522
        } elseif ('https' == $this->server('REQUEST_SCHEME')) {
1523
            return true;
1524
        } elseif ('443' == $this->server('SERVER_PORT')) {
1525
            return true;
1526
        } elseif ('https' == $this->server('HTTP_X_FORWARDED_PROTO')) {
1527
            return true;
1528
        } elseif ($this->httpsAgentName && $this->server($this->httpsAgentName)) {
1529
            return true;
1530
        }
1531
1532
        return false;
1533
    }
1534
1535
    /**
1536
     * 当前是否JSON请求
1537
     * @access public
1538
     * @return bool
1539
     */
1540 21
    public function isJson(): bool
1541
    {
1542 21
        $acceptType = $this->type();
1543
1544 21
        return str_contains($acceptType, 'json');
1545
    }
1546
1547
    /**
1548
     * 当前是否Ajax请求
1549
     * @access public
1550
     * @param  bool $ajax true 获取原始ajax请求
1551
     * @return bool
1552
     */
1553
    public function isAjax(bool $ajax = false): bool
1554
    {
1555
        $value  = $this->server('HTTP_X_REQUESTED_WITH');
1556
        $result = $value && 'xmlhttprequest' == strtolower($value) ? true : false;
1557
1558
        if (true === $ajax) {
1559
            return $result;
1560
        }
1561
1562
        return $this->param($this->varAjax) ? true : $result;
1563
    }
1564
1565
    /**
1566
     * 当前是否Pjax请求
1567
     * @access public
1568
     * @param  bool $pjax true 获取原始pjax请求
1569
     * @return bool
1570
     */
1571
    public function isPjax(bool $pjax = false): bool
1572
    {
1573
        $result = !empty($this->server('HTTP_X_PJAX')) ? true : false;
1574
1575
        if (true === $pjax) {
1576
            return $result;
1577
        }
1578
1579
        return $this->param($this->varPjax) ? true : $result;
1580
    }
1581
1582
    /**
1583
     * 获取客户端IP地址
1584
     * @access public
1585
     * @return string
1586
     */
1587
    public function ip(): string
1588
    {
1589
        if (!empty($this->realIP)) {
1590
            return $this->realIP;
1591
        }
1592
1593
        $this->realIP = $this->server('REMOTE_ADDR', '');
1594
1595
        // 如果指定了前端代理服务器IP以及其会发送的IP头
1596
        // 则尝试获取前端代理服务器发送过来的真实IP
1597
        $proxyIp       = $this->proxyServerIp;
1598
        $proxyIpHeader = $this->proxyServerIpHeader;
1599
1600
        if (count($proxyIp) > 0 && count($proxyIpHeader) > 0) {
1601
            // 从指定的HTTP头中依次尝试获取IP地址
1602
            // 直到获取到一个合法的IP地址
1603
            foreach ($proxyIpHeader as $header) {
1604
                $tempIP = $this->server($header);
1605
1606
                if (empty($tempIP)) {
1607
                    continue;
1608
                }
1609
1610
                $tempIP = trim(explode(',', $tempIP)[0]);
0 ignored issues
show
Bug introduced by
It seems like $tempIP can also be of type array; however, parameter $string of explode() does only seem to accept string, 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

1610
                $tempIP = trim(explode(',', /** @scrutinizer ignore-type */ $tempIP)[0]);
Loading history...
1611
1612
                if (!$this->isValidIP($tempIP)) {
1613
                    $tempIP = null;
1614
                } else {
1615
                    break;
1616
                }
1617
            }
1618
1619
            // tempIP不为空,说明获取到了一个IP地址
1620
            // 这时我们检查 REMOTE_ADDR 是不是指定的前端代理服务器之一
1621
            // 如果是的话说明该 IP头 是由前端代理服务器设置的
1622
            // 否则则是伪装的
1623
            if (!empty($tempIP)) {
1624
                $realIPBin = $this->ip2bin($this->realIP);
1625
1626
                foreach ($proxyIp as $ip) {
1627
                    $serverIPElements = explode('/', $ip);
1628
                    $serverIP         = $serverIPElements[0];
1629
                    $serverIPPrefix   = $serverIPElements[1] ?? 128;
1630
                    $serverIPBin      = $this->ip2bin($serverIP);
1631
1632
                    // IP类型不符
1633
                    if (strlen($realIPBin) !== strlen($serverIPBin)) {
1634
                        continue;
1635
                    }
1636
1637
                    if (strncmp($realIPBin, $serverIPBin, (int) $serverIPPrefix) === 0) {
1638
                        $this->realIP = $tempIP;
1639
                        break;
1640
                    }
1641
                }
1642
            }
1643
        }
1644
1645
        if (!$this->isValidIP($this->realIP)) {
1646
            $this->realIP = '0.0.0.0';
1647
        }
1648
1649
        return $this->realIP;
1650
    }
1651
1652
    /**
1653
     * 检测是否是合法的IP地址
1654
     *
1655
     * @param string $ip   IP地址
1656
     * @param string $type IP地址类型 (ipv4, ipv6)
1657
     *
1658
     * @return boolean
1659
     */
1660
    public function isValidIP(string $ip, string $type = ''): bool
1661
    {
1662
        $flag   =   match (strtolower($type)) {
1663
            'ipv4'  =>  FILTER_FLAG_IPV4,
1664
            'ipv6'  =>  FILTER_FLAG_IPV6,
1665
            default =>  0,
1666
        };
1667
1668
        return boolval(filter_var($ip, FILTER_VALIDATE_IP, $flag));
1669
    }
1670
1671
    /**
1672
     * 将IP地址转换为二进制字符串
1673
     *
1674
     * @param string $ip
1675
     *
1676
     * @return string
1677
     */
1678
    public function ip2bin(string $ip): string
1679
    {
1680
        if ($this->isValidIP($ip, 'ipv6')) {
1681
            $IPHex = str_split(bin2hex(inet_pton($ip)), 4);
1682
            foreach ($IPHex as $key => $value) {
1683
                $IPHex[$key] = intval($value, 16);
1684
            }
1685
            $IPBin = vsprintf('%016b%016b%016b%016b%016b%016b%016b%016b', $IPHex);
0 ignored issues
show
Bug introduced by
It seems like $IPHex can also be of type true; however, parameter $values of vsprintf() does only seem to accept array, 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

1685
            $IPBin = vsprintf('%016b%016b%016b%016b%016b%016b%016b%016b', /** @scrutinizer ignore-type */ $IPHex);
Loading history...
1686
        } else {
1687
            $IPHex = str_split(bin2hex(inet_pton($ip)), 2);
1688
            foreach ($IPHex as $key => $value) {
1689
                $IPHex[$key] = intval($value, 16);
1690
            }
1691
            $IPBin = vsprintf('%08b%08b%08b%08b', $IPHex);
1692
        }
1693
1694
        return $IPBin;
1695
    }
1696
1697
    /**
1698
     * 检测是否使用手机访问
1699
     * @access public
1700
     * @return bool
1701
     */
1702
    public function isMobile(): bool
1703
    {
1704
        if ($this->server('HTTP_VIA') && stristr($this->server('HTTP_VIA'), "wap")) {
1705
            return true;
1706
        } elseif ($this->server('HTTP_ACCEPT') && str_contains(strtoupper($this->server('HTTP_ACCEPT')), "VND.WAP.WML")) {
1707
            return true;
1708
        } elseif ($this->server('HTTP_X_WAP_PROFILE') || $this->server('HTTP_PROFILE')) {
1709
            return true;
1710
        } elseif ($this->server('HTTP_USER_AGENT') && preg_match('/(blackberry|configuration\/cldc|hp |hp-|htc |htc_|htc-|iemobile|kindle|midp|mmp|motorola|mobile|nokia|opera mini|opera |Googlebot-Mobile|YahooSeeker\/M1A1-R2D2|android|iphone|ipod|mobi|palm|palmos|pocket|portalmmm|ppc;|smartphone|sonyericsson|sqh|spv|symbian|treo|up.browser|up.link|vodafone|windows ce|xda |xda_)/i', $this->server('HTTP_USER_AGENT'))) {
1711
            return true;
1712
        }
1713
1714
        return false;
1715
    }
1716
1717
    /**
1718
     * 当前URL地址中的scheme参数
1719
     * @access public
1720
     * @return string
1721
     */
1722
    public function scheme(): string
1723
    {
1724
        return $this->isSsl() ? 'https' : 'http';
1725
    }
1726
1727
    /**
1728
     * 当前请求URL地址中的query参数
1729
     * @access public
1730
     * @return string
1731
     */
1732
    public function query(): string
1733
    {
1734
        return $this->server('QUERY_STRING', '');
1735
    }
1736
1737
    /**
1738
     * 设置当前请求的host(包含端口)
1739
     * @access public
1740
     * @param  string $host 主机名(含端口)
1741
     * @return $this
1742
     */
1743
    public function setHost(string $host)
1744
    {
1745
        $this->host = $host;
1746
1747
        return $this;
1748
    }
1749
1750
    /**
1751
     * 当前请求的host
1752
     * @access public
1753
     * @param bool $strict  true 仅仅获取HOST
1754
     * @return string
1755
     */
1756
    public function host(bool $strict = false): string
1757
    {
1758
        if ($this->host) {
1759
            $host = $this->host;
1760
        } else {
1761
            $host = strval($this->server('HTTP_X_FORWARDED_HOST') ?: $this->server('HTTP_HOST'));
1762
        }
1763
1764
        return true === $strict && str_contains($host, ':') ? strstr($host, ':', true) : $host;
1765
    }
1766
1767
    /**
1768
     * 当前请求URL地址中的port参数
1769
     * @access public
1770
     * @return int
1771
     */
1772
    public function port(): int
1773
    {
1774
        return (int) ($this->server('HTTP_X_FORWARDED_PORT') ?: $this->server('SERVER_PORT', ''));
1775
    }
1776
1777
    /**
1778
     * 当前请求 SERVER_PROTOCOL
1779
     * @access public
1780
     * @return string
1781
     */
1782
    public function protocol(): string
1783
    {
1784
        return $this->server('SERVER_PROTOCOL', '');
1785
    }
1786
1787
    /**
1788
     * 当前请求 REMOTE_PORT
1789
     * @access public
1790
     * @return int
1791
     */
1792
    public function remotePort(): int
1793
    {
1794
        return (int) $this->server('REMOTE_PORT', '');
1795
    }
1796
1797
    /**
1798
     * 当前请求 HTTP_CONTENT_TYPE
1799
     * @access public
1800
     * @return string
1801
     */
1802 27
    public function contentType(): string
1803
    {
1804 27
        $contentType = $this->header('Content-Type');
1805
1806 27
        if ($contentType) {
1807
            if (str_contains($contentType, ';')) {
0 ignored issues
show
Bug introduced by
It seems like $contentType can also be of type array; however, parameter $haystack of str_contains() does only seem to accept string, 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

1807
            if (str_contains(/** @scrutinizer ignore-type */ $contentType, ';')) {
Loading history...
1808
                [$type] = explode(';', $contentType);
0 ignored issues
show
Bug introduced by
It seems like $contentType can also be of type array; however, parameter $string of explode() does only seem to accept string, 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

1808
                [$type] = explode(';', /** @scrutinizer ignore-type */ $contentType);
Loading history...
1809
            } else {
1810
                $type = $contentType;
1811
            }
1812
            return trim($type);
0 ignored issues
show
Bug introduced by
It seems like $type can also be of type array; however, parameter $string of trim() does only seem to accept string, 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

1812
            return trim(/** @scrutinizer ignore-type */ $type);
Loading history...
1813
        }
1814
1815 27
        return '';
1816
    }
1817
1818
    /**
1819
     * 获取当前请求的安全Key
1820
     * @access public
1821
     * @return string
1822
     */
1823
    public function secureKey(): string
1824
    {
1825
        if (is_null($this->secureKey)) {
0 ignored issues
show
introduced by
The condition is_null($this->secureKey) is always false.
Loading history...
1826
            $this->secureKey = uniqid('', true);
1827
        }
1828
1829
        return $this->secureKey;
1830
    }
1831
1832
    /**
1833
     * 设置当前的控制器名
1834
     * @access public
1835
     * @param  string $controller 控制器名
1836
     * @return $this
1837
     */
1838 12
    public function setController(string $controller)
1839
    {
1840 12
        $this->controller = $controller;
1841 12
        return $this;
1842
    }
1843
1844
    /**
1845
     * 设置当前的操作名
1846
     * @access public
1847
     * @param  string $action 操作名
1848
     * @return $this
1849
     */
1850 12
    public function setAction(string $action)
1851
    {
1852 12
        $this->action = $action;
1853 12
        return $this;
1854
    }
1855
1856
    /**
1857
     * 获取当前的控制器名
1858
     * @access public
1859
     * @param  bool $convert 转换为小写
1860
     * @return string
1861
     */
1862
    public function controller(bool $convert = false): string
1863
    {
1864
        $name = $this->controller ?: '';
1865
        return $convert ? strtolower($name) : $name;
1866
    }
1867
1868
    /**
1869
     * 获取当前的操作名
1870
     * @access public
1871
     * @param  bool $convert 转换为小写
1872
     * @return string
1873
     */
1874 6
    public function action(bool $convert = false): string
1875
    {
1876 6
        $name = $this->action ?: '';
1877 6
        return $convert ? strtolower($name) : $name;
1878
    }
1879
1880
    /**
1881
     * 设置或者获取当前请求的content
1882
     * @access public
1883
     * @return string
1884
     */
1885
    public function getContent(): string
1886
    {
1887
        if (is_null($this->content)) {
0 ignored issues
show
introduced by
The condition is_null($this->content) is always false.
Loading history...
1888
            $this->content = $this->input;
1889
        }
1890
1891
        return $this->content;
1892
    }
1893
1894
    /**
1895
     * 获取当前请求的php://input
1896
     * @access public
1897
     * @return string
1898
     */
1899
    public function getInput(): string
1900
    {
1901
        return $this->input;
1902
    }
1903
1904
    /**
1905
     * 生成请求令牌
1906
     * @access public
1907
     * @param  string $name 令牌名称
1908
     * @param  mixed  $type 令牌生成方法
1909
     * @return string
1910
     */
1911
    public function buildToken(string $name = '__token__', $type = 'md5'): string
1912
    {
1913
        $type  = is_callable($type) ? $type : 'md5';
1914
        $token = call_user_func($type, $this->server('REQUEST_TIME_FLOAT'));
1915
1916
        $this->session->set($name, $token);
0 ignored issues
show
Bug introduced by
The method set() does not exist on think\Session. Since you implemented __call, 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

1916
        $this->session->/** @scrutinizer ignore-call */ 
1917
                        set($name, $token);
Loading history...
1917
1918
        return $token;
1919
    }
1920
1921
    /**
1922
     * 检查请求令牌
1923
     * @access public
1924
     * @param  string $token 令牌名称
1925
     * @param  array  $data  表单数据
1926
     * @return bool
1927
     */
1928
    public function checkToken(string $token = '__token__', array $data = []): bool
1929
    {
1930
        if (in_array($this->method(), ['GET', 'HEAD', 'OPTIONS'], true)) {
1931
            return true;
1932
        }
1933
1934
        if (!$this->session->has($token)) {
0 ignored issues
show
Bug introduced by
The method has() does not exist on think\Session. Since you implemented __call, 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

1934
        if (!$this->session->/** @scrutinizer ignore-call */ has($token)) {
Loading history...
1935
            // 令牌数据无效
1936
            return false;
1937
        }
1938
1939
        // Header验证
1940
        if ($this->header('X-CSRF-TOKEN') && $this->session->get($token) === $this->header('X-CSRF-TOKEN')) {
1941
            // 防止重复提交
1942
            $this->session->delete($token); // 验证完成销毁session
0 ignored issues
show
Bug introduced by
The method delete() does not exist on think\Session. Since you implemented __call, 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

1942
            $this->session->/** @scrutinizer ignore-call */ 
1943
                            delete($token); // 验证完成销毁session
Loading history...
1943
            return true;
1944
        }
1945
1946
        if (empty($data)) {
1947
            $data = $this->post();
1948
        }
1949
1950
        // 令牌验证
1951
        if (isset($data[$token]) && $this->session->get($token) === $data[$token]) {
1952
            // 防止重复提交
1953
            $this->session->delete($token); // 验证完成销毁session
1954
            return true;
1955
        }
1956
1957
        // 开启TOKEN重置
1958
        $this->session->delete($token);
1959
        return false;
1960
    }
1961
1962
    /**
1963
     * 设置在中间件传递的数据
1964
     * @access public
1965
     * @param  array $middleware 数据
1966
     * @return $this
1967
     */
1968
    public function withMiddleware(array $middleware)
1969
    {
1970
        $this->middleware = array_merge($this->middleware, $middleware);
1971
        return $this;
1972
    }
1973
1974
    /**
1975
     * 设置GET数据
1976
     * @access public
1977
     * @param  array $get 数据
1978
     * @return $this
1979
     */
1980
    public function withGet(array $get)
1981
    {
1982
        $this->get = $get;
1983
        return $this;
1984
    }
1985
1986
    /**
1987
     * 设置POST数据
1988
     * @access public
1989
     * @param  array $post 数据
1990
     * @return $this
1991
     */
1992
    public function withPost(array $post)
1993
    {
1994
        $this->post = $post;
1995
        return $this;
1996
    }
1997
1998
    /**
1999
     * 设置COOKIE数据
2000
     * @access public
2001
     * @param array $cookie 数据
2002
     * @return $this
2003
     */
2004
    public function withCookie(array $cookie)
2005
    {
2006
        $this->cookie = $cookie;
2007
        return $this;
2008
    }
2009
2010
    /**
2011
     * 设置SESSION数据
2012
     * @access public
2013
     * @param Session $session 数据
2014
     * @return $this
2015
     */
2016
    public function withSession(Session $session)
2017
    {
2018
        $this->session = $session;
2019
        return $this;
2020
    }
2021
2022
    /**
2023
     * 设置SERVER数据
2024
     * @access public
2025
     * @param  array $server 数据
2026
     * @return $this
2027
     */
2028
    public function withServer(array $server)
2029
    {
2030
        $this->server = array_change_key_case($server, CASE_UPPER);
2031
        return $this;
2032
    }
2033
2034
    /**
2035
     * 设置HEADER数据
2036
     * @access public
2037
     * @param  array $header 数据
2038
     * @return $this
2039
     */
2040
    public function withHeader(array $header)
2041
    {
2042
        $this->header = array_change_key_case($header);
2043
        return $this;
2044
    }
2045
2046
    /**
2047
     * 设置ENV数据
2048
     * @access public
2049
     * @param Env $env 数据
2050
     * @return $this
2051
     */
2052
    public function withEnv(Env $env)
2053
    {
2054
        $this->env = $env;
2055
        return $this;
2056
    }
2057
2058
    /**
2059
     * 设置php://input数据
2060
     * @access public
2061
     * @param string $input RAW数据
2062
     * @return $this
2063
     */
2064
    public function withInput(string $input)
2065
    {
2066
        $this->input = $input;
2067
        if (!empty($input)) {
2068
            $inputData = $this->getInputData($input);
2069
            if (!empty($inputData)) {
2070
                $this->post = $inputData;
2071
                $this->put  = $inputData;
2072
            }
2073
        }
2074
        return $this;
2075
    }
2076
2077
    /**
2078
     * 设置文件上传数据
2079
     * @access public
2080
     * @param  array $files 上传信息
2081
     * @return $this
2082
     */
2083
    public function withFiles(array $files)
2084
    {
2085
        $this->file = $files;
2086
        return $this;
2087
    }
2088
2089
    /**
2090
     * 设置ROUTE变量
2091
     * @access public
2092
     * @param  array $route 数据
2093
     * @return $this
2094
     */
2095
    public function withRoute(array $route)
2096
    {
2097
        $this->route = $route;
2098
        return $this;
2099
    }
2100
2101
    /**
2102
     * 设置中间传递数据
2103
     * @access public
2104
     * @param  string    $name  参数名
2105
     * @param  mixed     $value 值
2106
     */
2107
    public function __set(string $name, $value)
2108
    {
2109
        $this->middleware[$name] = $value;
2110
    }
2111
2112
    /**
2113
     * 获取中间传递数据的值
2114
     * @access public
2115
     * @param  string $name 名称
2116
     * @return mixed
2117
     */
2118
    public function __get(string $name)
2119
    {
2120
        return $this->middleware($name);
2121
    }
2122
2123
    /**
2124
     * 检测中间传递数据的值
2125
     * @access public
2126
     * @param  string $name 名称
2127
     * @return boolean
2128
     */
2129
    public function __isset(string $name): bool
2130
    {
2131
        return isset($this->middleware[$name]);
2132
    }
2133
2134
    // ArrayAccess
2135
    public function offsetExists(mixed $name): bool
2136
    {
2137
        return $this->has($name);
2138
    }
2139
2140
    public function offsetGet(mixed $name): mixed
2141
    {
2142
        return $this->param($name);
2143
    }
2144
2145
    public function offsetSet(mixed $name, mixed $value): void
2146
    {
2147
    }
2148
2149
    public function offsetUnset(mixed $name): void
2150
    {
2151
    }
2152
}
2153