Passed
Push — 8.0 ( e229cb...c71a61 )
by liu
12:51
created

Request::only()   B

Complexity

Conditions 8
Paths 22

Size

Total Lines 32
Code Lines 18

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 72

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 8
eloc 18
nc 22
nop 3
dl 0
loc 32
ccs 0
cts 13
cp 0
crap 72
rs 8.4444
c 1
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
     * @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 2
                    $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
        } elseif (!$this->method) {
749
            if (isset($this->post[$this->varMethod])) {
750
                $method = strtolower($this->post[$this->varMethod]);
751
                if (in_array($method, ['get', 'post', 'put', 'patch', 'delete'])) {
752
                    $this->method    = strtoupper($method);
753
                    $this->{$method} = $this->post;
754
                } else {
755
                    $this->method = 'POST';
756
                }
757
                unset($this->post[$this->varMethod]);
758
            } elseif ($this->server('HTTP_X_HTTP_METHOD_OVERRIDE')) {
759
                $this->method = strtoupper($this->server('HTTP_X_HTTP_METHOD_OVERRIDE'));
760
            } else {
761
                $this->method = $this->server('REQUEST_METHOD') ?: 'GET';
762
            }
763
        }
764
765
        return $this->method;
766
    }
767
768
    /**
769
     * 是否为GET请求
770
     * @access public
771
     * @return bool
772
     */
773
    public function isGet(): bool
774
    {
775
        return $this->method() == 'GET';
776
    }
777
778
    /**
779
     * 是否为POST请求
780
     * @access public
781
     * @return bool
782
     */
783
    public function isPost(): bool
784
    {
785
        return $this->method() == 'POST';
786
    }
787
788
    /**
789
     * 是否为PUT请求
790
     * @access public
791
     * @return bool
792
     */
793
    public function isPut(): bool
794
    {
795
        return $this->method() == 'PUT';
796
    }
797
798
    /**
799
     * 是否为DELTE请求
800
     * @access public
801
     * @return bool
802
     */
803
    public function isDelete(): bool
804
    {
805
        return $this->method() == 'DELETE';
806
    }
807
808
    /**
809
     * 是否为HEAD请求
810
     * @access public
811
     * @return bool
812
     */
813
    public function isHead(): bool
814
    {
815
        return $this->method() == 'HEAD';
816
    }
817
818
    /**
819
     * 是否为PATCH请求
820
     * @access public
821
     * @return bool
822
     */
823
    public function isPatch(): bool
824
    {
825
        return $this->method() == 'PATCH';
826
    }
827
828
    /**
829
     * 是否为OPTIONS请求
830
     * @access public
831
     * @return bool
832
     */
833
    public function isOptions(): bool
834
    {
835
        return $this->method() == 'OPTIONS';
836
    }
837
838
    /**
839
     * 是否为cli
840
     * @access public
841
     * @return bool
842
     */
843
    public function isCli(): bool
844
    {
845
        return PHP_SAPI == 'cli';
846
    }
847
848
    /**
849
     * 是否为cgi
850
     * @access public
851
     * @return bool
852
     */
853
    public function isCgi(): bool
854
    {
855
        return str_starts_with(PHP_SAPI, 'cgi');
856
    }
857
858
    /**
859
     * 获取当前请求的参数
860
     * @access public
861
     * @param  string|array $name 变量名
862
     * @param  mixed $default 默认值
863
     * @param  string|array|null $filter 过滤方法
864
     * @return mixed
865
     */
866
    public function param($name = '', $default = null, string|array|null $filter = '')
867
    {
868
        if (empty($this->mergeParam)) {
869
            $method = $this->method(true);
870
871
            // 自动获取请求变量
872
            $vars   =   match ($method) {
873
                'POST'  =>  $this->post(false),
874
                'PUT','DELETE','PATCH'  =>  $this->put(false),
875
                default =>  [],
876
            };
877
878
            // 当前请求参数和URL地址中的参数合并
879
            $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

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

900
        $data = array_merge($this->param(), /** @scrutinizer ignore-type */ $this->file() ?: []);
Loading history...
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

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

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

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

1242
        /** @scrutinizer ignore-call */ 
1243
        $msg = Lang::get($fileUploadErrors[$error]);
Loading history...
1243
        throw new Exception($msg, $error);
1244
    }
1245
1246
    /**
1247
     * 设置或者获取当前的Header
1248
     * @access public
1249
     * @param  string $name header名称
1250
     * @param  string $default 默认值
1251
     * @return string|array|null
1252
     */
1253 27
    public function header(string $name = '', string|null $default = null)
1254
    {
1255 27
        if ('' === $name) {
1256
            return $this->header;
1257
        }
1258
1259 27
        $name = str_replace('_', '-', strtolower($name));
1260 27
        return $this->header[$name] ?? $default;
1261
    }
1262
1263
    /**
1264
     * 获取变量 支持过滤和默认值
1265
     * @access public
1266
     * @param  array $data 数据源
1267
     * @param  string|false $name 字段名
1268
     * @param  mixed $default 默认值
1269
     * @param  string|array|null $filter 过滤函数
1270
     * @return mixed
1271
     */
1272 27
    public function input(array $data = [], string|bool $name = '', $default = null, string|array|null $filter = '')
1273
    {
1274 27
        if (false === $name) {
1275
            // 获取原始数据
1276
            return $data;
1277
        }
1278
1279 27
        $name = (string) $name;
1280 27
        if ('' != $name) {
1281
            // 解析name
1282
            if (str_contains($name, '/')) {
1283
                [$name, $type] = explode('/', $name);
1284
            }
1285
1286
            $data = $this->getData($data, $name);
1287
1288
            if (is_null($data)) {
1289
                return $default;
1290
            }
1291
1292
            if (is_object($data)) {
1293
                return $data;
1294
            }
1295
        }
1296
1297 27
        $data = $this->filterData($data, $filter, $name, $default);
1298
1299 27
        if (isset($type) && $data !== $default) {
1300
            // 强制类型转换
1301
            $this->typeCast($data, $type);
1302
        }
1303
1304 27
        return $data;
1305
    }
1306
1307 27
    protected function filterData($data, $filter, $name, $default)
1308
    {
1309
        // 解析过滤器
1310 27
        $filter = $this->getFilter($filter, $default);
1311
1312 27
        if (is_array($data)) {
1313 27
            array_walk_recursive($data, [$this, 'filterValue'], $filter);
1314
        } else {
1315
            $this->filterValue($data, $name, $filter);
1316
        }
1317
1318 27
        return $data;
1319
    }
1320
1321
    /**
1322
     * 强制类型转换
1323
     * @access protected
1324
     * @param  mixed  $data
1325
     * @param  string $type
1326
     * @return mixed
1327
     */
1328
    protected function typeCast(&$data, string $type)
1329
    {
1330
        $type = strtolower($type);
1331
        if (in_array($type, ['a', 'b', 'd', 'f', 's'])) {
1332
            $data   =   match ($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
            };
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 27
    protected function getFilter($filter, $default): array
1381
    {
1382 27
        if (is_null($filter)) {
1383
            $filter = [];
1384
        } else {
1385 27
            $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
            }
1391
        }
1392
1393 27
        $filter[] = $default;
1394
1395 27
        return $filter;
1396
    }
1397
1398
    /**
1399
     * 递归过滤给定的值
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
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);
1505
1506
            if (isset($type)) {
1507
                // 强制类型转换
1508
                $this->typeCast($item[$key], $type);
1509
            }
1510
        }
1511
1512
        return $item;
1513
    }
1514
1515
    /**
1516
     * 排除指定参数获取
1517
     * @access public
1518
     * @param  array  $name 变量名
1519
     * @param  string $type 变量类型
1520
     * @return mixed
1521
     */
1522
    public function except(array $name, string $type = 'param'): array
1523
    {
1524
        $param = $this->$type();
1525
1526
        foreach ($name as $key) {
1527
            if (isset($param[$key])) {
1528
                unset($param[$key]);
1529
            }
1530
        }
1531
1532
        return $param;
1533
    }
1534
1535
    /**
1536
     * 当前是否ssl
1537
     * @access public
1538
     * @return bool
1539
     */
1540
    public function isSsl(): bool
1541
    {
1542
        if ($this->server('HTTPS') && ('1' == $this->server('HTTPS') || 'on' == strtolower($this->server('HTTPS')))) {
1543
            return true;
1544
        } elseif ('https' == $this->server('REQUEST_SCHEME')) {
1545
            return true;
1546
        } elseif ('443' == $this->server('SERVER_PORT')) {
1547
            return true;
1548
        } elseif ('https' == $this->server('HTTP_X_FORWARDED_PROTO')) {
1549
            return true;
1550
        } elseif ($this->httpsAgentName && $this->server($this->httpsAgentName)) {
1551 21
            return true;
1552
        }
1553 21
1554
        return false;
1555 21
    }
1556
1557
    /**
1558
     * 当前是否JSON请求
1559
     * @access public
1560
     * @return bool
1561
     */
1562
    public function isJson(): bool
1563
    {
1564
        $acceptType = $this->type();
1565
1566
        return str_contains($acceptType, 'json');
1567
    }
1568
1569
    /**
1570
     * 当前是否Ajax请求
1571
     * @access public
1572
     * @param  bool $ajax true 获取原始ajax请求
1573
     * @return bool
1574
     */
1575
    public function isAjax(bool $ajax = false): bool
1576
    {
1577
        $value  = $this->server('HTTP_X_REQUESTED_WITH');
1578
        $result = $value && 'xmlhttprequest' == strtolower($value) ? true : false;
1579
1580
        if (true === $ajax) {
1581
            return $result;
1582
        }
1583
1584
        return $this->param($this->varAjax) ? true : $result;
1585
    }
1586
1587
    /**
1588
     * 当前是否Pjax请求
1589
     * @access public
1590
     * @param  bool $pjax true 获取原始pjax请求
1591
     * @return bool
1592
     */
1593
    public function isPjax(bool $pjax = false): bool
1594
    {
1595
        $result = !empty($this->server('HTTP_X_PJAX')) ? true : false;
1596
1597
        if (true === $pjax) {
1598
            return $result;
1599
        }
1600
1601
        return $this->param($this->varPjax) ? true : $result;
1602
    }
1603
1604
    /**
1605
     * 获取客户端IP地址
1606
     * @access public
1607
     * @return string
1608
     */
1609
    public function ip(): string
1610
    {
1611
        if (!empty($this->realIP)) {
1612
            return $this->realIP;
1613
        }
1614
1615
        $this->realIP = $this->server('REMOTE_ADDR', '');
1616
1617
        // 如果指定了前端代理服务器IP以及其会发送的IP头
1618
        // 则尝试获取前端代理服务器发送过来的真实IP
1619
        $proxyIp       = $this->proxyServerIp;
1620
        $proxyIpHeader = $this->proxyServerIpHeader;
1621
1622
        if (count($proxyIp) > 0 && count($proxyIpHeader) > 0) {
1623
            // 从指定的HTTP头中依次尝试获取IP地址
1624
            // 直到获取到一个合法的IP地址
1625
            foreach ($proxyIpHeader as $header) {
1626
                $tempIP = $this->server($header);
1627
1628
                if (empty($tempIP)) {
1629
                    continue;
1630
                }
1631
1632
                $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

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

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

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

1830
                [$type] = explode(';', /** @scrutinizer ignore-type */ $contentType);
Loading history...
1831
            } else {
1832
                $type = $contentType;
1833
            }
1834
            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

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

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

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

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