Passed
Push — 8.0 ( 207796...55dae4 )
by liu
12:15
created

Request::input()   A

Complexity

Conditions 4
Paths 4

Size

Total Lines 18
Code Lines 8

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 4
CRAP Score 7.456

Importance

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

881
            $this->param = array_merge($this->param, /** @scrutinizer ignore-type */ $this->get(false), $vars, $this->route(false));
Loading history...
882
883
            $this->mergeParam = true;
884
        }
885
886
        if (is_array($name)) {
887
            return $this->only($name, $this->param, $filter);
888
        }
889
890
        return $this->input($this->param, $name, $default, $filter);
891
    }
892
893
    /**
894
     * 获取包含文件在内的请求参数
895
     * @access public
896
     * @param  string|array $name 变量名
897
     * @param  string|array|null $filter 过滤方法
898
     * @return mixed
899
     */
900
    public function all(string | array $name = '', string | array | null $filter = '')
901
    {
902
        $data = array_merge($this->param(), $this->file() ?: []);
0 ignored issues
show
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

902
        $data = array_merge($this->param(), /** @scrutinizer ignore-type */ $this->file() ?: []);
Loading history...
Bug introduced by
$this->param() of type null|object is incompatible with the type array expected by parameter $arrays of array_merge(). ( Ignorable by Annotation )

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

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

1111
            return $this->session->/** @scrutinizer ignore-call */ all();
Loading history...
1112
        }
1113
        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

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

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

1627
                $tempIP = trim(explode(',', /** @scrutinizer ignore-type */ $tempIP)[0]);
Loading history...
1628
1629
                if (!$this->isValidIP($tempIP)) {
1630
                    $tempIP = null;
1631
                } else {
1632
                    break;
1633
                }
1634
            }
1635
1636
            // tempIP不为空,说明获取到了一个IP地址
1637
            // 这时我们检查 REMOTE_ADDR 是不是指定的前端代理服务器之一
1638
            // 如果是的话说明该 IP头 是由前端代理服务器设置的
1639
            // 否则则是伪装的
1640
            if (!empty($tempIP)) {
1641
                $realIPBin = $this->ip2bin($this->realIP);
1642
1643
                foreach ($proxyIp as $ip) {
1644
                    $serverIPElements = explode('/', $ip);
1645
                    $serverIP         = $serverIPElements[0];
1646
                    $serverIPPrefix   = $serverIPElements[1] ?? 128;
1647
                    $serverIPBin      = $this->ip2bin($serverIP);
1648
1649
                    // IP类型不符
1650
                    if (strlen($realIPBin) !== strlen($serverIPBin)) {
1651
                        continue;
1652
                    }
1653
1654
                    if (strncmp($realIPBin, $serverIPBin, (int) $serverIPPrefix) === 0) {
1655
                        $this->realIP = $tempIP;
1656
                        break;
1657
                    }
1658
                }
1659
            }
1660
        }
1661
1662
        if (!$this->isValidIP($this->realIP)) {
1663
            $this->realIP = '0.0.0.0';
1664
        }
1665
1666
        return $this->realIP;
1667
    }
1668
1669
    /**
1670
     * 检测是否是合法的IP地址
1671
     *
1672
     * @param string $ip   IP地址
1673
     * @param string $type IP地址类型 (ipv4, ipv6)
1674
     *
1675
     * @return boolean
1676
     */
1677
    public function isValidIP(string $ip, string $type = ''): bool
1678
    {
1679
        $flag = match (strtolower($type)) {
1680
            'ipv4'  => FILTER_FLAG_IPV4,
1681
            'ipv6'  => FILTER_FLAG_IPV6,
1682
            default => 0,
1683
        };
1684
1685
        return boolval(filter_var($ip, FILTER_VALIDATE_IP, $flag));
1686
    }
1687
1688
    /**
1689
     * 将IP地址转换为二进制字符串
1690
     *
1691
     * @param string $ip
1692
     *
1693
     * @return string
1694
     */
1695
    public function ip2bin(string $ip): string
1696
    {
1697
        if ($this->isValidIP($ip, 'ipv6')) {
1698
            $IPHex = str_split(bin2hex(inet_pton($ip)), 4);
1699
            foreach ($IPHex as $key => $value) {
1700
                $IPHex[$key] = intval($value, 16);
1701
            }
1702
            $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

1702
            $IPBin = vsprintf('%016b%016b%016b%016b%016b%016b%016b%016b', /** @scrutinizer ignore-type */ $IPHex);
Loading history...
1703
        } else {
1704
            $IPHex = str_split(bin2hex(inet_pton($ip)), 2);
1705
            foreach ($IPHex as $key => $value) {
1706
                $IPHex[$key] = intval($value, 16);
1707
            }
1708
            $IPBin = vsprintf('%08b%08b%08b%08b', $IPHex);
1709
        }
1710
1711
        return $IPBin;
1712
    }
1713
1714
    /**
1715
     * 检测是否使用手机访问
1716
     * @access public
1717
     * @return bool
1718
     */
1719
    public function isMobile(): bool
1720
    {
1721
        if ($this->server('HTTP_VIA') && stristr($this->server('HTTP_VIA'), "wap")) {
1722
            return true;
1723
        } elseif ($this->server('HTTP_ACCEPT') && str_contains(strtoupper($this->server('HTTP_ACCEPT')), "VND.WAP.WML")) {
1724
            return true;
1725
        } elseif ($this->server('HTTP_X_WAP_PROFILE') || $this->server('HTTP_PROFILE')) {
1726
            return true;
1727
        } 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'))) {
1728
            return true;
1729
        }
1730
1731
        return false;
1732
    }
1733
1734
    /**
1735
     * 当前URL地址中的scheme参数
1736
     * @access public
1737
     * @return string
1738
     */
1739
    public function scheme(): string
1740
    {
1741
        return $this->isSsl() ? 'https' : 'http';
1742
    }
1743
1744
    /**
1745
     * 当前请求URL地址中的query参数
1746
     * @access public
1747
     * @return string
1748
     */
1749
    public function query(): string
1750
    {
1751
        return $this->server('QUERY_STRING', '');
1752
    }
1753
1754
    /**
1755
     * 设置当前请求的host(包含端口)
1756
     * @access public
1757
     * @param  string $host 主机名(含端口)
1758
     * @return $this
1759
     */
1760
    public function setHost(string $host)
1761
    {
1762
        $this->host = $host;
1763
1764
        return $this;
1765
    }
1766
1767
    /**
1768
     * 当前请求的host
1769
     * @access public
1770
     * @param bool $strict  true 仅仅获取HOST
1771
     * @return string
1772
     */
1773
    public function host(bool $strict = false): string
1774
    {
1775
        if ($this->host) {
1776
            $host = $this->host;
1777
        } else {
1778
            $host = strval($this->server('HTTP_X_FORWARDED_HOST') ?: $this->server('HTTP_HOST'));
1779
        }
1780
1781
        return true === $strict && str_contains($host, ':') ? strstr($host, ':', true) : $host;
1782
    }
1783
1784
    /**
1785
     * 当前请求URL地址中的port参数
1786
     * @access public
1787
     * @return int
1788
     */
1789
    public function port(): int
1790
    {
1791
        return (int) ($this->server('HTTP_X_FORWARDED_PORT') ?: $this->server('SERVER_PORT', ''));
1792
    }
1793
1794
    /**
1795
     * 当前请求 SERVER_PROTOCOL
1796
     * @access public
1797
     * @return string
1798
     */
1799
    public function protocol(): string
1800
    {
1801
        return $this->server('SERVER_PROTOCOL', '');
1802
    }
1803
1804
    /**
1805
     * 当前请求 REMOTE_PORT
1806
     * @access public
1807
     * @return int
1808
     */
1809
    public function remotePort(): int
1810
    {
1811
        return (int) $this->server('REMOTE_PORT', '');
1812
    }
1813
1814
    /**
1815
     * 当前请求 HTTP_CONTENT_TYPE
1816
     * @access public
1817
     * @return string
1818
     */
1819
    public function contentType(): string
1820
    {
1821
        $contentType = $this->header('Content-Type');
1822
1823
        if ($contentType) {
1824
            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

1824
            if (str_contains(/** @scrutinizer ignore-type */ $contentType, ';')) {
Loading history...
1825
                [$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

1825
                [$type] = explode(';', /** @scrutinizer ignore-type */ $contentType);
Loading history...
1826
            } else {
1827
                $type = $contentType;
1828 27
            }
1829
            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

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

1933
        $this->session->/** @scrutinizer ignore-call */ 
1934
                        set($name, $token);
Loading history...
1934
1935
        return $token;
1936
    }
1937
1938
    /**
1939
     * 检查请求令牌
1940
     * @access public
1941
     * @param  string $token 令牌名称
1942
     * @param  array  $data  表单数据
1943
     * @return bool
1944
     */
1945
    public function checkToken(string $token = '__token__', array $data = []): bool
1946
    {
1947
        if (in_array($this->method(), ['GET', 'HEAD', 'OPTIONS'], true)) {
1948
            return true;
1949
        }
1950
1951
        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

1951
        if (!$this->session->/** @scrutinizer ignore-call */ has($token)) {
Loading history...
1952
            // 令牌数据无效
1953
            return false;
1954
        }
1955
1956
        // Header验证
1957
        if ($this->header('X-CSRF-TOKEN') && $this->session->get($token) === $this->header('X-CSRF-TOKEN')) {
1958
            // 防止重复提交
1959
            $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

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