Passed
Pull Request — 8.0 (#3080)
by
unknown
02:15
created

Request::isDelete()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 3
Code Lines 1

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 2

Importance

Changes 0
Metric Value
cc 1
eloc 1
nc 1
nop 0
dl 0
loc 3
ccs 0
cts 2
cp 0
crap 2
rs 10
c 0
b 0
f 0
1
<?php
2
// +----------------------------------------------------------------------
3
// | ThinkPHP [ WE CAN DO IT JUST THINK ]
4
// +----------------------------------------------------------------------
5
// | Copyright (c) 2006~2023 http://thinkphp.cn All rights reserved.
6
// +----------------------------------------------------------------------
7
// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
8
// +----------------------------------------------------------------------
9
// | Author: liu21st <[email protected]>
10
// +----------------------------------------------------------------------
11
declare(strict_types=1);
12
13
namespace think;
14
15
use ArrayAccess;
16
use think\facade\Lang;
0 ignored issues
show
Bug introduced by
This use statement conflicts with another class in this namespace, think\Lang. Consider defining an alias.

Let?s assume that you have a directory layout like this:

.
|-- OtherDir
|   |-- Bar.php
|   `-- Foo.php
`-- SomeDir
    `-- Foo.php

and let?s assume the following content of Bar.php:

// Bar.php
namespace OtherDir;

use SomeDir\Foo; // This now conflicts the class OtherDir\Foo

If both files OtherDir/Foo.php and SomeDir/Foo.php are loaded in the same runtime, you will see a PHP error such as the following:

PHP Fatal error:  Cannot use SomeDir\Foo as Foo because the name is already in use in OtherDir/Foo.php

However, as OtherDir/Foo.php does not necessarily have to be loaded and the error is only triggered if it is loaded before OtherDir/Bar.php, this problem might go unnoticed for a while. In order to prevent this error from surfacing, you must import the namespace with a different alias:

// Bar.php
namespace OtherDir;

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

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

337
        $request->header = array_change_key_case(/** @scrutinizer ignore-type */ $header);
Loading history...
338 27
        $request->server = $_SERVER;
339 27
        $request->env    = $app->env;
340
341 27
        $inputData = $request->getInputData($request->input);
342
343 27
        $request->get     = $_GET;
344 27
        $request->post    = $_POST ?: $inputData;
345 27
        $request->put     = $inputData;
346 27
        $request->request = $_REQUEST;
347 27
        $request->cookie  = $_COOKIE;
348 27
        $request->file    = $_FILES ?? [];
349
350 27
        return $request;
351
    }
352
353
    /**
354
     * 设置当前包含协议的域名
355
     * @access public
356
     * @param  string $domain 域名
357
     * @return $this
358
     */
359
    public function setDomain(string $domain)
360
    {
361
        $this->domain = $domain;
362
        return $this;
363
    }
364
365
    /**
366
     * 获取当前包含协议的域名
367
     * @access public
368
     * @param  bool $port 是否需要去除端口号
369
     * @return string
370
     */
371
    public function domain(bool $port = false): string
372
    {
373
        return $this->scheme() . '://' . $this->host($port);
374
    }
375
376
    /**
377
     * 设置根域名
378
     * @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
        }
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
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

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

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

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

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

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

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

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

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

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