Completed
Push — 6.0 ( d34a69...e97afa )
by liu
08:04
created

Request::offsetGet()   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 1
Bugs 0 Features 0
Metric Value
cc 1
eloc 1
c 1
b 0
f 0
nc 1
nop 1
dl 0
loc 3
ccs 0
cts 2
cp 0
crap 2
rs 10
1
<?php
2
// +----------------------------------------------------------------------
3
// | ThinkPHP [ WE CAN DO IT JUST THINK ]
4
// +----------------------------------------------------------------------
5
// | Copyright (c) 2006~2019 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\file\UploadedFile;
17
use think\route\Rule;
18
19
/**
20
 * 请求管理类
21
 * @package think
0 ignored issues
show
Coding Style introduced by
Package name "think" is not valid; consider "Think" instead
Loading history...
22
 */
23
class Request implements ArrayAccess
24
{
25
    /**
26
     * 兼容PATH_INFO获取
27
     * @var array
28
     */
29
    protected $pathinfoFetch = ['ORIG_PATH_INFO', 'REDIRECT_PATH_INFO', 'REDIRECT_URL'];
30
31
    /**
32
     * PATHINFO变量名 用于兼容模式
33
     * @var string
34
     */
35
    protected $varPathinfo = 's';
36
37
    /**
38
     * 请求类型
39
     * @var string
40
     */
41
    protected $varMethod = '_method';
42
43
    /**
44
     * 表单ajax伪装变量
45
     * @var string
46
     */
47
    protected $varAjax = '_ajax';
48
49
    /**
50
     * 表单pjax伪装变量
51
     * @var string
52
     */
53
    protected $varPjax = '_pjax';
54
55
    /**
56
     * 域名根
57
     * @var string
58
     */
59
    protected $rootDomain = '';
60
61
    /**
62
     * HTTPS代理标识
63
     * @var string
64
     */
65
    protected $httpsAgentName = '';
66
67
    /**
68
     * 前端代理服务器IP
69
     * @var array
70
     */
71
    protected $proxyServerIp = [];
72
73
    /**
74
     * 前端代理服务器真实IP头
75
     * @var array
76
     */
77
    protected $proxyServerIpHeader = ['HTTP_X_REAL_IP', 'HTTP_X_FORWARDED_FOR', 'HTTP_CLIENT_IP', 'HTTP_X_CLIENT_IP', 'HTTP_X_CLUSTER_CLIENT_IP'];
78
79
    /**
80
     * 请求类型
81
     * @var string
82
     */
83
    protected $method;
84
85
    /**
86
     * 域名(含协议及端口)
87
     * @var string
88
     */
89
    protected $domain;
90
91
    /**
92
     * HOST(含端口)
93
     * @var string
94
     */
95
    protected $host;
96
97
    /**
98
     * 子域名
99
     * @var string
100
     */
101
    protected $subDomain;
102
103
    /**
104
     * 泛域名
105
     * @var string
106
     */
107
    protected $panDomain;
108
109
    /**
110
     * 当前URL地址
111
     * @var string
112
     */
113
    protected $url;
114
115
    /**
116
     * 基础URL
117
     * @var string
118
     */
119
    protected $baseUrl;
120
121
    /**
122
     * 当前执行的文件
123
     * @var string
124
     */
125
    protected $baseFile;
126
127
    /**
128
     * 访问的ROOT地址
129
     * @var string
130
     */
131
    protected $root;
132
133
    /**
134
     * pathinfo
0 ignored issues
show
Coding Style introduced by
Doc comment short description must start with a capital letter
Loading history...
135
     * @var string
136
     */
137
    protected $pathinfo;
138
139
    /**
140
     * pathinfo(不含后缀)
0 ignored issues
show
Coding Style introduced by
Doc comment short description must start with a capital letter
Loading history...
141
     * @var string
142
     */
143
    protected $path;
144
145
    /**
146
     * 当前请求的IP地址
147
     * @var string
148
     */
149
    protected $realIP;
150
151
    /**
152
     * 当前控制器名
153
     * @var string
154
     */
155
    protected $controller;
156
157
    /**
158
     * 当前操作名
159
     * @var string
160
     */
161
    protected $action;
162
163
    /**
164
     * 当前请求参数
165
     * @var array
166
     */
167
    protected $param = [];
168
169
    /**
170
     * 当前GET参数
171
     * @var array
172
     */
173
    protected $get = [];
174
175
    /**
176
     * 当前POST参数
177
     * @var array
178
     */
179
    protected $post = [];
180
181
    /**
182
     * 当前REQUEST参数
183
     * @var array
184
     */
185
    protected $request = [];
186
187
    /**
188
     * 当前路由对象
189
     * @var Rule
190
     */
191
    protected $rule;
192
193
    /**
194
     * 当前ROUTE参数
195
     * @var array
196
     */
197
    protected $route = [];
198
199
    /**
200
     * 中间件传递的参数
201
     * @var array
202
     */
203
    protected $middleware = [];
204
205
    /**
206
     * 当前PUT参数
207
     * @var array
208
     */
209
    protected $put;
210
211
    /**
212
     * SESSION对象
213
     * @var Session
214
     */
215
    protected $session;
216
217
    /**
218
     * COOKIE数据
219
     * @var array
220
     */
221
    protected $cookie = [];
222
223
    /**
224
     * ENV对象
225
     * @var Env
226
     */
227
    protected $env;
228
229
    /**
230
     * 当前SERVER参数
231
     * @var array
232
     */
233
    protected $server = [];
234
235
    /**
236
     * 当前FILE参数
237
     * @var array
238
     */
239
    protected $file = [];
240
241
    /**
242
     * 当前HEADER参数
243
     * @var array
244
     */
245
    protected $header = [];
246
247
    /**
248
     * 资源类型定义
249
     * @var array
250
     */
251
    protected $mimeType = [
252
        'xml'   => 'application/xml,text/xml,application/x-xml',
253
        'json'  => 'application/json,text/x-json,application/jsonrequest,text/json',
254
        'js'    => 'text/javascript,application/javascript,application/x-javascript',
255
        'css'   => 'text/css',
256
        'rss'   => 'application/rss+xml',
257
        'yaml'  => 'application/x-yaml,text/yaml',
258
        'atom'  => 'application/atom+xml',
259
        'pdf'   => 'application/pdf',
260
        'text'  => 'text/plain',
261
        'image' => 'image/png,image/jpg,image/jpeg,image/pjpeg,image/gif,image/webp,image/*',
262
        'csv'   => 'text/csv',
263
        'html'  => 'text/html,application/xhtml+xml,*/*',
264
    ];
265
266
    /**
267
     * 当前请求内容
268
     * @var string
269
     */
270
    protected $content;
271
272
    /**
273
     * 全局过滤规则
274
     * @var array
275
     */
276
    protected $filter;
277
278
    /**
279
     * php://input内容
0 ignored issues
show
Coding Style introduced by
Doc comment short description must start with a capital letter
Loading history...
280
     * @var string
281
     */
282
    // php://input
283
    protected $input;
284
285
    /**
286
     * 请求安全Key
287
     * @var string
288
     */
289
    protected $secureKey;
290
291
    /**
292
     * 是否合并Param
293
     * @var bool
294
     */
295
    protected $mergeParam = false;
296
297
    /**
298
     * 架构函数
299
     * @access public
300
     */
301
    public function __construct()
302
    {
303
        // 保存 php://input
304
        $this->input = file_get_contents('php://input');
305
    }
306
307
    public static function __make(App $app)
0 ignored issues
show
Coding Style introduced by
Missing doc comment for function __make()
Loading history...
308
    {
309
        $request = new static();
310
311
        if (function_exists('apache_request_headers') && $result = apache_request_headers()) {
312
            $header = $result;
313
        } else {
314
            $header = [];
315
            $server = $_SERVER;
316
            foreach ($server as $key => $val) {
317
                if (0 === strpos($key, 'HTTP_')) {
318
                    $key          = str_replace('_', '-', strtolower(substr($key, 5)));
319
                    $header[$key] = $val;
320
                }
321
            }
322
            if (isset($server['CONTENT_TYPE'])) {
323
                $header['content-type'] = $server['CONTENT_TYPE'];
324
            }
325
            if (isset($server['CONTENT_LENGTH'])) {
326
                $header['content-length'] = $server['CONTENT_LENGTH'];
327
            }
328
        }
329
330
        $request->header = array_change_key_case($header);
331
        $request->server = $_SERVER;
332
        $request->env    = $app->env;
333
334
        $inputData = $request->getInputData($request->input);
335
336
        $request->get     = $_GET;
337
        $request->post    = $_POST ?: $inputData;
338
        $request->put     = $inputData;
339
        $request->request = $_REQUEST;
340
        $request->cookie  = $_COOKIE;
341
        $request->file    = $_FILES ?? [];
342
343
        return $request;
344
    }
345
346
    /**
347
     * 设置当前包含协议的域名
348
     * @access public
349
     * @param  string $domain 域名
350
     * @return $this
351
     */
352
    public function setDomain(string $domain)
353
    {
354
        $this->domain = $domain;
355
        return $this;
356
    }
357
358
    /**
359
     * 获取当前包含协议的域名
360
     * @access public
361
     * @param  bool $port 是否需要去除端口号
362
     * @return string
363
     */
364
    public function domain(bool $port = false): string
365
    {
366
        return $this->scheme() . '://' . $this->host($port);
367
    }
368
369
    /**
370
     * 获取当前根域名
371
     * @access public
372
     * @return string
373
     */
374
    public function rootDomain(): string
375
    {
376
        $root = $this->rootDomain;
377
378
        if (!$root) {
379
            $item  = explode('.', $this->host());
380
            $count = count($item);
381
            $root  = $count > 1 ? $item[$count - 2] . '.' . $item[$count - 1] : $item[0];
382
        }
383
384
        return $root;
385
    }
386
387
    /**
388
     * 设置当前泛域名的值
389
     * @access public
390
     * @param  string $domain 域名
391
     * @return $this
392
     */
393
    public function setSubDomain(string $domain)
394
    {
395
        $this->subDomain = $domain;
396
        return $this;
397
    }
398
399
    /**
400
     * 获取当前子域名
401
     * @access public
402
     * @return string
403
     */
404
    public function subDomain(): string
405
    {
406
        if (is_null($this->subDomain)) {
0 ignored issues
show
introduced by
The condition is_null($this->subDomain) is always false.
Loading history...
407
            // 获取当前主域名
408
            $rootDomain = $this->rootDomain();
409
410
            if ($rootDomain) {
411
                $this->subDomain = rtrim(stristr($this->host(), $rootDomain, true), '.');
412
            } else {
413
                $this->subDomain = '';
414
            }
415
        }
416
417
        return $this->subDomain;
418
    }
419
420
    /**
421
     * 设置当前泛域名的值
422
     * @access public
423
     * @param  string $domain 域名
424
     * @return $this
425
     */
426
    public function setPanDomain(string $domain)
427
    {
428
        $this->panDomain = $domain;
429
        return $this;
430
    }
431
432
    /**
433
     * 获取当前泛域名的值
434
     * @access public
435
     * @return string
436
     */
437
    public function panDomain(): string
438
    {
439
        return $this->panDomain ?: '';
440
    }
441
442
    /**
443
     * 设置当前完整URL 包括QUERY_STRING
444
     * @access public
445
     * @param  string $url URL地址
446
     * @return $this
447
     */
448
    public function setUrl(string $url)
449
    {
450
        $this->url = $url;
451
        return $this;
452
    }
453
454
    /**
455
     * 获取当前完整URL 包括QUERY_STRING
456
     * @access public
457
     * @param  bool $complete 是否包含完整域名
458
     * @return string
459
     */
460
    public function url(bool $complete = false): string
461
    {
462
        if ($this->url) {
463
            $url = $this->url;
464
        } elseif ($this->server('HTTP_X_REWRITE_URL')) {
465
            $url = $this->server('HTTP_X_REWRITE_URL');
466
        } elseif ($this->server('REQUEST_URI')) {
467
            $url = $this->server('REQUEST_URI');
468
        } elseif ($this->server('ORIG_PATH_INFO')) {
469
            $url = $this->server('ORIG_PATH_INFO') . (!empty($this->server('QUERY_STRING')) ? '?' . $this->server('QUERY_STRING') : '');
470
        } elseif (isset($_SERVER['argv'][1])) {
471
            $url = $_SERVER['argv'][1];
472
        } else {
473
            $url = '';
474
        }
475
476
        return $complete ? $this->domain() . $url : $url;
477
    }
478
479
    /**
480
     * 设置当前URL 不含QUERY_STRING
481
     * @access public
482
     * @param  string $url URL地址
483
     * @return $this
484
     */
485
    public function setBaseUrl(string $url)
486
    {
487
        $this->baseUrl = $url;
488
        return $this;
489
    }
490
491
    /**
492
     * 获取当前URL 不含QUERY_STRING
493
     * @access public
494
     * @param  bool $complete 是否包含完整域名
495
     * @return string
496
     */
497
    public function baseUrl(bool $complete = false): string
498
    {
499
        if (!$this->baseUrl) {
500
            $str           = $this->url();
501
            $this->baseUrl = strpos($str, '?') ? strstr($str, '?', true) : $str;
502
        }
503
504
        return $complete ? $this->domain() . $this->baseUrl : $this->baseUrl;
505
    }
506
507
    /**
508
     * 获取当前执行的文件 SCRIPT_NAME
509
     * @access public
510
     * @param  bool $complete 是否包含完整域名
511
     * @return string
512
     */
513
    public function baseFile(bool $complete = false): string
514
    {
515
        if (!$this->baseFile) {
516
            $url = '';
517
            if (!$this->isCli()) {
518
                $script_name = basename($this->server('SCRIPT_FILENAME'));
519
                if (basename($this->server('SCRIPT_NAME')) === $script_name) {
520
                    $url = $this->server('SCRIPT_NAME');
521
                } elseif (basename($this->server('PHP_SELF')) === $script_name) {
522
                    $url = $this->server('PHP_SELF');
523
                } elseif (basename($this->server('ORIG_SCRIPT_NAME')) === $script_name) {
524
                    $url = $this->server('ORIG_SCRIPT_NAME');
525
                } elseif (($pos = strpos($this->server('PHP_SELF'), '/' . $script_name)) !== false) {
526
                    $url = substr($this->server('SCRIPT_NAME'), 0, $pos) . '/' . $script_name;
527
                } elseif ($this->server('DOCUMENT_ROOT') && strpos($this->server('SCRIPT_FILENAME'), $this->server('DOCUMENT_ROOT')) === 0) {
528
                    $url = str_replace('\\', '/', str_replace($this->server('DOCUMENT_ROOT'), '', $this->server('SCRIPT_FILENAME')));
529
                }
530
            }
531
            $this->baseFile = $url;
532
        }
533
534
        return $complete ? $this->domain() . $this->baseFile : $this->baseFile;
535
    }
536
537
    /**
538
     * 设置URL访问根地址
539
     * @access public
540
     * @param  string $url URL地址
541
     * @return $this
542
     */
543
    public function setRoot(string $url)
544
    {
545
        $this->root = $url;
546
        return $this;
547
    }
548
549
    /**
550
     * 获取URL访问根地址
551
     * @access public
552
     * @param  bool $complete 是否包含完整域名
553
     * @return string
554
     */
555
    public function root(bool $complete = false): string
556
    {
557
        if (!$this->root) {
558
            $file = $this->baseFile();
559
            if ($file && 0 !== strpos($this->url(), $file)) {
560
                $file = str_replace('\\', '/', dirname($file));
561
            }
562
            $this->root = rtrim($file, '/');
563
        }
564
565
        return $complete ? $this->domain() . $this->root : $this->root;
566
    }
567
568
    /**
569
     * 获取URL访问根目录
570
     * @access public
571
     * @return string
572
     */
573
    public function rootUrl(): string
574
    {
575
        $base = $this->root();
576
        $root = strpos($base, '.') ? ltrim(dirname($base), DIRECTORY_SEPARATOR) : $base;
577
578
        if ('' != $root) {
579
            $root = '/' . ltrim($root, '/');
580
        }
581
582
        return $root;
583
    }
584
585
    /**
586
     * 设置当前请求的pathinfo
587
     * @access public
588
     * @param  string $pathinfo
0 ignored issues
show
Coding Style introduced by
Missing parameter comment
Loading history...
589
     * @return $this
590
     */
591
    public function setPathinfo(string $pathinfo)
592
    {
593
        $this->pathinfo = $pathinfo;
594
        return $this;
595
    }
596
597
    /**
598
     * 获取当前请求URL的pathinfo信息(含URL后缀)
599
     * @access public
600
     * @return string
601
     */
602
    public function pathinfo(): string
603
    {
604
        if (is_null($this->pathinfo)) {
0 ignored issues
show
introduced by
The condition is_null($this->pathinfo) is always false.
Loading history...
605
            if (isset($_GET[$this->varPathinfo])) {
606
                // 判断URL里面是否有兼容模式参数
607
                $pathinfo = $_GET[$this->varPathinfo];
608
                unset($_GET[$this->varPathinfo]);
609
                unset($this->get[$this->varPathinfo]);
610
            } elseif ($this->server('PATH_INFO')) {
611
                $pathinfo = $this->server('PATH_INFO');
612
            } elseif (false !== strpos(PHP_SAPI, 'cli')) {
613
                $pathinfo = strpos($this->server('REQUEST_URI'), '?') ? strstr($this->server('REQUEST_URI'), '?', true) : $this->server('REQUEST_URI');
614
            }
615
616
            // 分析PATHINFO信息
617
            if (!isset($pathinfo)) {
618
                foreach ($this->pathinfoFetch as $type) {
619
                    if ($this->server($type)) {
620
                        $pathinfo = (0 === strpos($this->server($type), $this->server('SCRIPT_NAME'))) ?
621
                        substr($this->server($type), strlen($this->server('SCRIPT_NAME'))) : $this->server($type);
622
                        break;
623
                    }
624
                }
625
            }
626
627
            if (!empty($pathinfo)) {
628
                unset($this->get[$pathinfo], $this->request[$pathinfo]);
629
            }
630
631
            $this->pathinfo = empty($pathinfo) || '/' == $pathinfo ? '' : ltrim($pathinfo, '/');
632
        }
633
634
        return $this->pathinfo;
635
    }
636
637
    /**
638
     * 当前URL的访问后缀
639
     * @access public
640
     * @return string
641
     */
642
    public function ext(): string
643
    {
644
        return pathinfo($this->pathinfo(), PATHINFO_EXTENSION);
645
    }
646
647
    /**
648
     * 获取当前请求的时间
649
     * @access public
650
     * @param  bool $float 是否使用浮点类型
651
     * @return integer|float
652
     */
653
    public function time(bool $float = false)
654
    {
655
        return $float ? $this->server('REQUEST_TIME_FLOAT') : $this->server('REQUEST_TIME');
0 ignored issues
show
Bug Best Practice introduced by
The expression return $float ? $this->s...>server('REQUEST_TIME') also could return the type string which is incompatible with the documented return type double|integer.
Loading history...
656
    }
657
658
    /**
659
     * 当前请求的资源类型
660
     * @access public
661
     * @return string
662
     */
663
    public function type(): string
664
    {
665
        $accept = $this->server('HTTP_ACCEPT');
666
667
        if (empty($accept)) {
668
            return '';
669
        }
670
671
        foreach ($this->mimeType as $key => $val) {
672
            $array = explode(',', $val);
673
            foreach ($array as $k => $v) {
674
                if (stristr($accept, $v)) {
675
                    return $key;
676
                }
677
            }
678
        }
679
680
        return '';
681
    }
682
683
    /**
684
     * 设置资源类型
685
     * @access public
686
     * @param  string|array $type 资源类型名
687
     * @param  string       $val 资源类型
0 ignored issues
show
Coding Style introduced by
Expected 2 spaces after parameter name; 1 found
Loading history...
688
     * @return void
689
     */
690
    public function mimeType($type, $val = ''): void
691
    {
692
        if (is_array($type)) {
693
            $this->mimeType = array_merge($this->mimeType, $type);
694
        } else {
695
            $this->mimeType[$type] = $val;
696
        }
697
    }
698
699
    /**
700
     * 设置请求类型
701
     * @access public
702
     * @param  string $method 请求类型
703
     * @return $this
704
     */
705
    public function setMethod(string $method)
706
    {
707
        $this->method = strtoupper($method);
708
        return $this;
709
    }
710
711
    /**
712
     * 当前的请求类型
713
     * @access public
714
     * @param  bool $origin 是否获取原始请求类型
715
     * @return string
716
     */
717
    public function method(bool $origin = false): string
718
    {
719
        if ($origin) {
720
            // 获取原始请求类型
721
            return $this->server('REQUEST_METHOD') ?: 'GET';
722
        } elseif (!$this->method) {
723
            if (isset($this->post[$this->varMethod])) {
724
                $method = strtolower($this->post[$this->varMethod]);
725
                if (in_array($method, ['get', 'post', 'put', 'patch', 'delete'])) {
726
                    $this->method    = strtoupper($method);
727
                    $this->{$method} = $this->post;
728
                } else {
729
                    $this->method = 'POST';
730
                }
731
                unset($this->post[$this->varMethod]);
732
            } elseif ($this->server('HTTP_X_HTTP_METHOD_OVERRIDE')) {
733
                $this->method = strtoupper($this->server('HTTP_X_HTTP_METHOD_OVERRIDE'));
734
            } else {
735
                $this->method = $this->server('REQUEST_METHOD') ?: 'GET';
736
            }
737
        }
738
739
        return $this->method;
740
    }
741
742
    /**
743
     * 是否为GET请求
744
     * @access public
745
     * @return bool
746
     */
747
    public function isGet(): bool
748
    {
749
        return $this->method() == 'GET';
750
    }
751
752
    /**
753
     * 是否为POST请求
754
     * @access public
755
     * @return bool
756
     */
757
    public function isPost(): bool
758
    {
759
        return $this->method() == 'POST';
760
    }
761
762
    /**
763
     * 是否为PUT请求
764
     * @access public
765
     * @return bool
766
     */
767
    public function isPut(): bool
768
    {
769
        return $this->method() == 'PUT';
770
    }
771
772
    /**
773
     * 是否为DELTE请求
774
     * @access public
775
     * @return bool
776
     */
777
    public function isDelete(): bool
778
    {
779
        return $this->method() == 'DELETE';
780
    }
781
782
    /**
783
     * 是否为HEAD请求
784
     * @access public
785
     * @return bool
786
     */
787
    public function isHead(): bool
788
    {
789
        return $this->method() == 'HEAD';
790
    }
791
792
    /**
793
     * 是否为PATCH请求
794
     * @access public
795
     * @return bool
796
     */
797
    public function isPatch(): bool
798
    {
799
        return $this->method() == 'PATCH';
800
    }
801
802
    /**
803
     * 是否为OPTIONS请求
804
     * @access public
805
     * @return bool
806
     */
807
    public function isOptions(): bool
808
    {
809
        return $this->method() == 'OPTIONS';
810
    }
811
812
    /**
813
     * 是否为cli
814
     * @access public
815
     * @return bool
816
     */
817
    public function isCli(): bool
818
    {
819
        return PHP_SAPI == 'cli';
820
    }
821
822
    /**
823
     * 是否为cgi
824
     * @access public
825
     * @return bool
826
     */
827
    public function isCgi(): bool
828
    {
829
        return strpos(PHP_SAPI, 'cgi') === 0;
830
    }
831
832
    /**
833
     * 获取当前请求的参数
834
     * @access public
835
     * @param  string|array $name 变量名
0 ignored issues
show
Coding Style introduced by
Expected 4 spaces after parameter name; 1 found
Loading history...
836
     * @param  mixed        $default 默认值
837
     * @param  string|array $filter 过滤方法
0 ignored issues
show
Coding Style introduced by
Expected 2 spaces after parameter name; 1 found
Loading history...
838
     * @return mixed
839
     */
840
    public function param($name = '', $default = null, $filter = '')
841
    {
842
        if (empty($this->mergeParam)) {
843
            $method = $this->method(true);
844
845
            // 自动获取请求变量
846
            switch ($method) {
847
                case 'POST':
848
                    $vars = $this->post(false);
0 ignored issues
show
Bug introduced by
false of type false is incompatible with the type array|string expected by parameter $name of think\Request::post(). ( Ignorable by Annotation )

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

848
                    $vars = $this->post(/** @scrutinizer ignore-type */ false);
Loading history...
849
                    break;
850
                case 'PUT':
851
                case 'DELETE':
852
                case 'PATCH':
853
                    $vars = $this->put(false);
0 ignored issues
show
Bug introduced by
false of type false is incompatible with the type array|string expected by parameter $name of think\Request::put(). ( Ignorable by Annotation )

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

853
                    $vars = $this->put(/** @scrutinizer ignore-type */ false);
Loading history...
854
                    break;
855
                default:
856
                    $vars = [];
857
            }
858
859
            // 当前请求参数和URL地址中的参数合并
860
            $this->param = array_merge($this->param, $this->get(false), $vars, $this->route(false));
0 ignored issues
show
Bug introduced by
false of type false is incompatible with the type array|string expected by parameter $name of think\Request::get(). ( Ignorable by Annotation )

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

860
            $this->param = array_merge($this->param, $this->get(/** @scrutinizer ignore-type */ false), $vars, $this->route(false));
Loading history...
Bug introduced by
false of type false is incompatible with the type array|string expected by parameter $name of think\Request::route(). ( Ignorable by Annotation )

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

860
            $this->param = array_merge($this->param, $this->get(false), $vars, $this->route(/** @scrutinizer ignore-type */ false));
Loading history...
861
862
            $this->mergeParam = true;
863
        }
864
865
        if (is_array($name)) {
866
            return $this->only($name, $this->param, $filter);
867
        }
868
869
        return $this->input($this->param, $name, $default, $filter);
870
    }
871
872
    /**
873
     * 设置路由变量
874
     * @access public
875
     * @param  Rule $rule 路由对象
876
     * @return $this
877
     */
878
    public function setRule(Rule $rule)
879
    {
880
        $this->rule = $rule;
881
        return $this;
882
    }
883
884
    /**
885
     * 获取当前路由对象
886
     * @access public
887
     * @return Rule|null
888
     */
889
    public function rule()
890
    {
891
        return $this->rule;
892
    }
893
894
    /**
895
     * 设置路由变量
896
     * @access public
897
     * @param  array $route 路由变量
898
     * @return $this
899
     */
900
    public function setRoute(array $route)
901
    {
902
        $this->route = array_merge($this->route, $route);
903
        return $this;
904
    }
905
906
    /**
907
     * 获取路由参数
908
     * @access public
909
     * @param  string|array $name 变量名
0 ignored issues
show
Coding Style introduced by
Expected 4 spaces after parameter name; 1 found
Loading history...
910
     * @param  mixed        $default 默认值
911
     * @param  string|array $filter 过滤方法
0 ignored issues
show
Coding Style introduced by
Expected 2 spaces after parameter name; 1 found
Loading history...
912
     * @return mixed
913
     */
914
    public function route($name = '', $default = null, $filter = '')
915
    {
916
        if (is_array($name)) {
917
            return $this->only($name, $this->route, $filter);
918
        }
919
920
        return $this->input($this->route, $name, $default, $filter);
921
    }
922
923
    /**
924
     * 获取GET参数
925
     * @access public
926
     * @param  string|array $name 变量名
0 ignored issues
show
Coding Style introduced by
Expected 4 spaces after parameter name; 1 found
Loading history...
927
     * @param  mixed        $default 默认值
928
     * @param  string|array $filter 过滤方法
0 ignored issues
show
Coding Style introduced by
Expected 2 spaces after parameter name; 1 found
Loading history...
929
     * @return mixed
930
     */
931
    public function get($name = '', $default = null, $filter = '')
932
    {
933
        if (is_array($name)) {
934
            return $this->only($name, $this->get, $filter);
935
        }
936
937
        return $this->input($this->get, $name, $default, $filter);
938
    }
939
940
    /**
941
     * 获取中间件传递的参数
942
     * @access public
943
     * @param  mixed $name 变量名
0 ignored issues
show
Coding Style introduced by
Expected 4 spaces after parameter name; 1 found
Loading history...
944
     * @param  mixed $default 默认值
945
     * @return mixed
946
     */
947
    public function middleware($name, $default = null)
948
    {
949
        return $this->middleware[$name] ?? $default;
950
    }
951
952
    /**
953
     * 获取POST参数
954
     * @access public
955
     * @param  string|array $name 变量名
0 ignored issues
show
Coding Style introduced by
Expected 4 spaces after parameter name; 1 found
Loading history...
956
     * @param  mixed        $default 默认值
957
     * @param  string|array $filter 过滤方法
0 ignored issues
show
Coding Style introduced by
Expected 2 spaces after parameter name; 1 found
Loading history...
958
     * @return mixed
959
     */
960
    public function post($name = '', $default = null, $filter = '')
961
    {
962
        if (is_array($name)) {
963
            return $this->only($name, $this->post, $filter);
964
        }
965
966
        return $this->input($this->post, $name, $default, $filter);
967
    }
968
969
    /**
970
     * 获取PUT参数
971
     * @access public
972
     * @param  string|array $name 变量名
0 ignored issues
show
Coding Style introduced by
Expected 4 spaces after parameter name; 1 found
Loading history...
973
     * @param  mixed        $default 默认值
974
     * @param  string|array $filter 过滤方法
0 ignored issues
show
Coding Style introduced by
Expected 2 spaces after parameter name; 1 found
Loading history...
975
     * @return mixed
976
     */
977
    public function put($name = '', $default = null, $filter = '')
978
    {
979
        if (is_array($name)) {
980
            return $this->only($name, $this->put, $filter);
981
        }
982
983
        return $this->input($this->put, $name, $default, $filter);
984
    }
985
986
    protected function getInputData($content): array
0 ignored issues
show
Coding Style introduced by
Missing doc comment for function getInputData()
Loading history...
987
    {
988
        $contentType = $this->contentType();
989
        if ('application/x-www-form-urlencoded' == $contentType) {
990
            parse_str($content, $data);
991
            return $data;
992
        } elseif (false !== strpos($contentType, 'json')) {
993
            return (array) json_decode($content, true);
994
        }
995
996
        return [];
997
    }
998
999
    /**
1000
     * 设置获取DELETE参数
1001
     * @access public
1002
     * @param  mixed        $name 变量名
0 ignored issues
show
Coding Style introduced by
Expected 4 spaces after parameter name; 1 found
Loading history...
1003
     * @param  mixed        $default 默认值
1004
     * @param  string|array $filter 过滤方法
0 ignored issues
show
Coding Style introduced by
Expected 2 spaces after parameter name; 1 found
Loading history...
1005
     * @return mixed
1006
     */
1007
    public function delete($name = '', $default = null, $filter = '')
1008
    {
1009
        return $this->put($name, $default, $filter);
1010
    }
1011
1012
    /**
1013
     * 设置获取PATCH参数
1014
     * @access public
1015
     * @param  mixed        $name 变量名
0 ignored issues
show
Coding Style introduced by
Expected 4 spaces after parameter name; 1 found
Loading history...
1016
     * @param  mixed        $default 默认值
1017
     * @param  string|array $filter 过滤方法
0 ignored issues
show
Coding Style introduced by
Expected 2 spaces after parameter name; 1 found
Loading history...
1018
     * @return mixed
1019
     */
1020
    public function patch($name = '', $default = null, $filter = '')
1021
    {
1022
        return $this->put($name, $default, $filter);
1023
    }
1024
1025
    /**
1026
     * 获取request变量
1027
     * @access public
1028
     * @param  string|array $name 数据名称
0 ignored issues
show
Coding Style introduced by
Expected 4 spaces after parameter name; 1 found
Loading history...
1029
     * @param  mixed        $default 默认值
1030
     * @param  string|array $filter 过滤方法
0 ignored issues
show
Coding Style introduced by
Expected 2 spaces after parameter name; 1 found
Loading history...
1031
     * @return mixed
1032
     */
1033
    public function request($name = '', $default = null, $filter = '')
1034
    {
1035
        if (is_array($name)) {
1036
            return $this->only($name, $this->request, $filter);
1037
        }
1038
1039
        return $this->input($this->request, $name, $default, $filter);
1040
    }
1041
1042
    /**
1043
     * 获取环境变量
1044
     * @access public
1045
     * @param  string $name 数据名称
0 ignored issues
show
Coding Style introduced by
Expected 4 spaces after parameter name; 1 found
Loading history...
1046
     * @param  string $default 默认值
1047
     * @return mixed
1048
     */
1049
    public function env(string $name = '', string $default = null)
1050
    {
1051
        if (empty($name)) {
1052
            return $this->env->get();
1053
        } else {
1054
            $name = strtoupper($name);
1055
        }
1056
1057
        return $this->env->get($name, $default);
1058
    }
1059
1060
    /**
1061
     * 获取session数据
1062
     * @access public
1063
     * @param  string $name 数据名称
0 ignored issues
show
Coding Style introduced by
Expected 4 spaces after parameter name; 1 found
Loading history...
1064
     * @param  string $default 默认值
1065
     * @return mixed
1066
     */
1067
    public function session(string $name = '', $default = null)
1068
    {
1069
        if ('' === $name) {
1070
            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

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

1072
        return $this->session->/** @scrutinizer ignore-call */ get($name, $default);
Loading history...
1073
    }
1074
1075
    /**
1076
     * 获取cookie参数
1077
     * @access public
1078
     * @param  mixed        $name 数据名称
0 ignored issues
show
Coding Style introduced by
Expected 4 spaces after parameter name; 1 found
Loading history...
1079
     * @param  string       $default 默认值
1080
     * @param  string|array $filter 过滤方法
0 ignored issues
show
Coding Style introduced by
Expected 2 spaces after parameter name; 1 found
Loading history...
1081
     * @return mixed
1082
     */
1083
    public function cookie(string $name = '', $default = null, $filter = '')
1084
    {
1085
        if (!empty($name)) {
1086
            $data = $this->getData($this->cookie, $name, $default);
1087
        } else {
1088
            $data = $this->cookie;
1089
        }
1090
1091
        // 解析过滤器
1092
        $filter = $this->getFilter($filter, $default);
1093
1094
        if (is_array($data)) {
1095
            array_walk_recursive($data, [$this, 'filterValue'], $filter);
1096
        } else {
1097
            $this->filterValue($data, $name, $filter);
1098
        }
1099
1100
        return $data;
1101
    }
1102
1103
    /**
1104
     * 获取server参数
1105
     * @access public
1106
     * @param  string $name 数据名称
0 ignored issues
show
Coding Style introduced by
Expected 4 spaces after parameter name; 1 found
Loading history...
1107
     * @param  string $default 默认值
1108
     * @return mixed
1109
     */
1110
    public function server(string $name = '', string $default = '')
1111
    {
1112
        if (empty($name)) {
1113
            return $this->server;
1114
        } else {
1115
            $name = strtoupper($name);
1116
        }
1117
1118
        return $this->server[$name] ?? $default;
1119
    }
1120
1121
    /**
1122
     * 获取上传的文件信息
1123
     * @access public
1124
     * @param  string $name 名称
1125
     * @return null|array|UploadedFile
1126
     */
1127
    public function file(string $name = '')
1128
    {
1129
        $files = $this->file;
1130
        if (!empty($files)) {
1131
1132
            if (strpos($name, '.')) {
1133
                [$name, $sub] = explode('.', $name);
1134
            }
1135
1136
            // 处理上传文件
1137
            $array = $this->dealUploadFile($files, $name);
1138
1139
            if ('' === $name) {
1140
                // 获取全部文件
1141
                return $array;
1142
            } elseif (isset($sub) && isset($array[$name][$sub])) {
1143
                return $array[$name][$sub];
1144
            } elseif (isset($array[$name])) {
1145
                return $array[$name];
1146
            }
1147
        }
1148
    }
1149
1150
    protected function dealUploadFile(array $files, string $name): array
0 ignored issues
show
Coding Style introduced by
Missing doc comment for function dealUploadFile()
Loading history...
1151
    {
1152
        $array = [];
1153
        foreach ($files as $key => $file) {
1154
            if (is_array($file['name'])) {
1155
                $item  = [];
1156
                $keys  = array_keys($file);
1157
                $count = count($file['name']);
1158
1159
                for ($i = 0; $i < $count; $i++) {
1160
                    if ($file['error'][$i] > 0) {
1161
                        if ($name == $key) {
1162
                            $this->throwUploadFileError($file['error'][$i]);
1163
                        } else {
1164
                            continue;
1165
                        }
1166
                    }
1167
1168
                    $temp['key'] = $key;
1169
1170
                    foreach ($keys as $_key) {
1171
                        $temp[$_key] = $file[$_key][$i];
1172
                    }
1173
1174
                    $item[] = new UploadedFile($temp['tmp_name'], $temp['name'], $temp['type'], $temp['error']);
1175
                }
1176
1177
                $array[$key] = $item;
1178
            } else {
1179
                if ($file instanceof File) {
1180
                    $array[$key] = $file;
1181
                } else {
1182
                    if ($file['error'] > 0) {
1183
                        if ($key == $name) {
1184
                            $this->throwUploadFileError($file['error']);
1185
                        } else {
1186
                            continue;
1187
                        }
1188
                    }
1189
1190
                    $array[$key] = new UploadedFile($file['tmp_name'], $file['name'], $file['type'], $file['error']);
1191
                }
1192
            }
1193
        }
1194
1195
        return $array;
1196
    }
1197
1198
    protected function throwUploadFileError($error)
0 ignored issues
show
Coding Style introduced by
Missing doc comment for function throwUploadFileError()
Loading history...
1199
    {
1200
        static $fileUploadErrors = [
1201
            1 => 'upload File size exceeds the maximum value',
1202
            2 => 'upload File size exceeds the maximum value',
1203
            3 => 'only the portion of file is uploaded',
1204
            4 => 'no file to uploaded',
1205
            6 => 'upload temp dir not found',
1206
            7 => 'file write error',
1207
        ];
1208
1209
        $msg = $fileUploadErrors[$error];
1210
        throw new Exception($msg, $error);
1211
    }
1212
1213
    /**
1214
     * 设置或者获取当前的Header
1215
     * @access public
1216
     * @param  string $name header名称
0 ignored issues
show
Coding Style introduced by
Expected 4 spaces after parameter name; 1 found
Loading history...
1217
     * @param  string $default 默认值
1218
     * @return string|array
1219
     */
1220
    public function header(string $name = '', string $default = null)
1221
    {
1222
        if ('' === $name) {
1223
            return $this->header;
1224
        }
1225
1226
        $name = str_replace('_', '-', strtolower($name));
1227
1228
        return $this->header[$name] ?? $default;
1229
    }
1230
1231
    /**
1232
     * 获取变量 支持过滤和默认值
1233
     * @access public
1234
     * @param  array        $data 数据源
0 ignored issues
show
Coding Style introduced by
Expected 4 spaces after parameter name; 1 found
Loading history...
1235
     * @param  string|false $name 字段名
0 ignored issues
show
Coding Style introduced by
Expected 4 spaces after parameter name; 1 found
Loading history...
1236
     * @param  mixed        $default 默认值
1237
     * @param  string|array $filter 过滤函数
0 ignored issues
show
Coding Style introduced by
Expected 2 spaces after parameter name; 1 found
Loading history...
1238
     * @return mixed
1239
     */
1240
    public function input(array $data = [], $name = '', $default = null, $filter = '')
1241
    {
1242
        if (false === $name) {
1243
            // 获取原始数据
1244
            return $data;
1245
        }
1246
1247
        $name = (string) $name;
1248
        if ('' != $name) {
1249
            // 解析name
1250
            if (strpos($name, '/')) {
1251
                [$name, $type] = explode('/', $name);
1252
            }
1253
1254
            $data = $this->getData($data, $name);
1255
1256
            if (is_null($data)) {
1257
                return $default;
1258
            }
1259
1260
            if (is_object($data)) {
1261
                return $data;
1262
            }
1263
        }
1264
1265
        $data = $this->filterData($data, $filter, $name, $default);
1266
1267
        if (isset($type) && $data !== $default) {
1268
            // 强制类型转换
1269
            $this->typeCast($data, $type);
1270
        }
1271
1272
        return $data;
1273
    }
1274
1275
    protected function filterData($data, $filter, $name, $default)
0 ignored issues
show
Coding Style introduced by
Missing doc comment for function filterData()
Loading history...
1276
    {
1277
        // 解析过滤器
1278
        $filter = $this->getFilter($filter, $default);
1279
1280
        if (is_array($data)) {
1281
            array_walk_recursive($data, [$this, 'filterValue'], $filter);
1282
        } else {
1283
            $this->filterValue($data, $name, $filter);
1284
        }
1285
1286
        return $data;
1287
    }
1288
1289
    /**
1290
     * 强制类型转换
1291
     * @access public
1292
     * @param  mixed  $data
0 ignored issues
show
Coding Style introduced by
Missing parameter comment
Loading history...
1293
     * @param  string $type
0 ignored issues
show
Coding Style introduced by
Missing parameter comment
Loading history...
1294
     * @return mixed
1295
     */
1296
    private function typeCast(&$data, string $type)
0 ignored issues
show
Coding Style introduced by
Private method name "Request::typeCast" must be prefixed with an underscore
Loading history...
1297
    {
1298
        switch (strtolower($type)) {
1299
            // 数组
1300
            case 'a':
1301
                $data = (array) $data;
1302
                break;
1303
            // 数字
1304
            case 'd':
1305
                $data = (int) $data;
1306
                break;
1307
            // 浮点
1308
            case 'f':
1309
                $data = (float) $data;
1310
                break;
1311
            // 布尔
1312
            case 'b':
1313
                $data = (boolean) $data;
1314
                break;
1315
            // 字符串
1316
            case 's':
1317
                if (is_scalar($data)) {
1318
                    $data = (string) $data;
1319
                } else {
1320
                    throw new \InvalidArgumentException('variable type error:' . gettype($data));
1321
                }
1322
                break;
1323
        }
1324
    }
1325
1326
    /**
1327
     * 获取数据
1328
     * @access public
1329
     * @param  array  $data 数据源
0 ignored issues
show
Coding Style introduced by
Expected 4 spaces after parameter name; 1 found
Loading history...
1330
     * @param  string $name 字段名
0 ignored issues
show
Coding Style introduced by
Expected 4 spaces after parameter name; 1 found
Loading history...
1331
     * @param  mixed  $default 默认值
1332
     * @return mixed
1333
     */
1334
    protected function getData(array $data, string $name, $default = null)
1335
    {
1336
        foreach (explode('.', $name) as $val) {
1337
            if (isset($data[$val])) {
1338
                $data = $data[$val];
1339
            } else {
1340
                return $default;
1341
            }
1342
        }
1343
1344
        return $data;
1345
    }
1346
1347
    /**
1348
     * 设置或获取当前的过滤规则
1349
     * @access public
1350
     * @param  mixed $filter 过滤规则
1351
     * @return mixed
1352
     */
1353
    public function filter($filter = null)
1354
    {
1355
        if (is_null($filter)) {
1356
            return $this->filter;
1357
        }
1358
1359
        $this->filter = $filter;
1360
1361
        return $this;
1362
    }
1363
1364
    protected function getFilter($filter, $default): array
0 ignored issues
show
Coding Style introduced by
Missing doc comment for function getFilter()
Loading history...
1365
    {
1366
        if (is_null($filter)) {
1367
            $filter = [];
1368
        } else {
1369
            $filter = $filter ?: $this->filter;
1370
            if (is_string($filter) && false === strpos($filter, '/')) {
1371
                $filter = explode(',', $filter);
1372
            } else {
1373
                $filter = (array) $filter;
1374
            }
1375
        }
1376
1377
        $filter[] = $default;
1378
1379
        return $filter;
1380
    }
1381
1382
    /**
1383
     * 递归过滤给定的值
1384
     * @access public
1385
     * @param  mixed $value 键值
0 ignored issues
show
Coding Style introduced by
Expected 3 spaces after parameter name; 1 found
Loading history...
1386
     * @param  mixed $key 键名
0 ignored issues
show
Coding Style introduced by
Expected 5 spaces after parameter name; 1 found
Loading history...
1387
     * @param  array $filters 过滤方法+默认值
1388
     * @return mixed
1389
     */
1390
    public function filterValue(&$value, $key, $filters)
1391
    {
1392
        $default = array_pop($filters);
1393
1394
        foreach ($filters as $filter) {
1395
            if (is_callable($filter)) {
1396
                // 调用函数或者方法过滤
1397
                $value = call_user_func($filter, $value);
1398
            } elseif (is_scalar($value)) {
1399
                if (is_string($filter) && false !== strpos($filter, '/')) {
1400
                    // 正则过滤
1401
                    if (!preg_match($filter, $value)) {
1402
                        // 匹配不成功返回默认值
1403
                        $value = $default;
1404
                        break;
1405
                    }
1406
                } elseif (!empty($filter)) {
1407
                    // filter函数不存在时, 则使用filter_var进行过滤
1408
                    // filter为非整形值时, 调用filter_id取得过滤id
1409
                    $value = filter_var($value, is_int($filter) ? $filter : filter_id($filter));
1410
                    if (false === $value) {
1411
                        $value = $default;
1412
                        break;
1413
                    }
1414
                }
1415
            }
1416
        }
1417
1418
        return $value;
1419
    }
1420
1421
    /**
1422
     * 是否存在某个请求参数
1423
     * @access public
1424
     * @param  string $name 变量名
0 ignored issues
show
Coding Style introduced by
Expected 7 spaces after parameter name; 1 found
Loading history...
1425
     * @param  string $type 变量类型
0 ignored issues
show
Coding Style introduced by
Expected 7 spaces after parameter name; 1 found
Loading history...
1426
     * @param  bool   $checkEmpty 是否检测空值
1427
     * @return bool
1428
     */
1429
    public function has(string $name, string $type = 'param', bool $checkEmpty = false): bool
1430
    {
1431
        if (!in_array($type, ['param', 'get', 'post', 'put', 'patch', 'route', 'delete', 'cookie', 'session', 'env', 'request', 'server', 'header', 'file'])) {
1432
            return false;
1433
        }
1434
1435
        $param = empty($this->$type) ? $this->$type() : $this->$type;
1436
1437
        if (is_object($param)) {
1438
            return $param->has($name);
1439
        }
1440
1441
        // 按.拆分成多维数组进行判断
1442
        foreach (explode('.', $name) as $val) {
1443
            if (isset($param[$val])) {
1444
                $param = $param[$val];
1445
            } else {
1446
                return false;
1447
            }
1448
        }
1449
1450
        return ($checkEmpty && '' === $param) ? false : true;
1451
    }
1452
1453
    /**
1454
     * 获取指定的参数
1455
     * @access public
1456
     * @param  array        $name 变量名
0 ignored issues
show
Coding Style introduced by
Expected 3 spaces after parameter name; 1 found
Loading history...
1457
     * @param  mixed        $data 数据或者变量类型
0 ignored issues
show
Coding Style introduced by
Expected 3 spaces after parameter name; 1 found
Loading history...
1458
     * @param  string|array $filter 过滤方法
1459
     * @return array
1460
     */
1461
    public function only(array $name, $data = 'param', $filter = ''): array
1462
    {
1463
        $data = is_array($data) ? $data : $this->$data();
1464
1465
        $item = [];
1466
        foreach ($name as $key => $val) {
1467
1468
            if (is_int($key)) {
1469
                $default = null;
1470
                $key     = $val;
1471
                if (!isset($data[$key])) {
1472
                    continue;
1473
                }
1474
            } else {
1475
                $default = $val;
1476
            }
1477
1478
            $item[$key] = $this->filterData($data[$key] ?? $default, $filter, $key, $default);
1479
        }
1480
1481
        return $item;
1482
    }
1483
1484
    /**
1485
     * 排除指定参数获取
1486
     * @access public
1487
     * @param  array  $name 变量名
1488
     * @param  string $type 变量类型
1489
     * @return mixed
1490
     */
1491
    public function except(array $name, string $type = 'param'): array
1492
    {
1493
        $param = $this->$type();
1494
1495
        foreach ($name as $key) {
1496
            if (isset($param[$key])) {
1497
                unset($param[$key]);
1498
            }
1499
        }
1500
1501
        return $param;
1502
    }
1503
1504
    /**
1505
     * 当前是否ssl
1506
     * @access public
1507
     * @return bool
1508
     */
1509
    public function isSsl(): bool
1510
    {
1511
        if ($this->server('HTTPS') && ('1' == $this->server('HTTPS') || 'on' == strtolower($this->server('HTTPS')))) {
1512
            return true;
1513
        } elseif ('https' == $this->server('REQUEST_SCHEME')) {
1514
            return true;
1515
        } elseif ('443' == $this->server('SERVER_PORT')) {
1516
            return true;
1517
        } elseif ('https' == $this->server('HTTP_X_FORWARDED_PROTO')) {
1518
            return true;
1519
        } elseif ($this->httpsAgentName && $this->server($this->httpsAgentName)) {
1520
            return true;
1521
        }
1522
1523
        return false;
1524
    }
1525
1526
    /**
1527
     * 当前是否JSON请求
1528
     * @access public
1529
     * @return bool
1530
     */
1531
    public function isJson(): bool
1532
    {
1533
        $acceptType = $this->type();
1534
1535
        return false !== strpos($acceptType, 'json');
1536
    }
1537
1538
    /**
1539
     * 当前是否Ajax请求
1540
     * @access public
1541
     * @param  bool $ajax true 获取原始ajax请求
1542
     * @return bool
1543
     */
1544
    public function isAjax(bool $ajax = false): bool
1545
    {
1546
        $value  = $this->server('HTTP_X_REQUESTED_WITH');
1547
        $result = $value && 'xmlhttprequest' == strtolower($value) ? true : false;
1548
1549
        if (true === $ajax) {
1550
            return $result;
1551
        }
1552
1553
        return $this->param($this->varAjax) ? true : $result;
1554
    }
1555
1556
    /**
1557
     * 当前是否Pjax请求
1558
     * @access public
1559
     * @param  bool $pjax true 获取原始pjax请求
1560
     * @return bool
1561
     */
1562
    public function isPjax(bool $pjax = false): bool
1563
    {
1564
        $result = !empty($this->server('HTTP_X_PJAX')) ? true : false;
1565
1566
        if (true === $pjax) {
1567
            return $result;
1568
        }
1569
1570
        return $this->param($this->varPjax) ? true : $result;
1571
    }
1572
1573
    /**
1574
     * 获取客户端IP地址
1575
     * @access public
1576
     * @return string
1577
     */
1578
    public function ip(): string
1579
    {
1580
        if (!empty($this->realIP)) {
1581
            return $this->realIP;
1582
        }
1583
1584
        $this->realIP = $this->server('REMOTE_ADDR', '');
1585
1586
        // 如果指定了前端代理服务器IP以及其会发送的IP头
1587
        // 则尝试获取前端代理服务器发送过来的真实IP
1588
        $proxyIp       = $this->proxyServerIp;
1589
        $proxyIpHeader = $this->proxyServerIpHeader;
1590
1591
        if (count($proxyIp) > 0 && count($proxyIpHeader) > 0) {
1592
            // 从指定的HTTP头中依次尝试获取IP地址
1593
            // 直到获取到一个合法的IP地址
1594
            foreach ($proxyIpHeader as $header) {
1595
                $tempIP = $this->server($header);
1596
1597
                if (empty($tempIP)) {
1598
                    continue;
1599
                }
1600
1601
                $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

1601
                $tempIP = trim(explode(',', /** @scrutinizer ignore-type */ $tempIP)[0]);
Loading history...
1602
1603
                if (!$this->isValidIP($tempIP)) {
1604
                    $tempIP = null;
1605
                } else {
1606
                    break;
1607
                }
1608
            }
1609
1610
            // tempIP不为空,说明获取到了一个IP地址
1611
            // 这时我们检查 REMOTE_ADDR 是不是指定的前端代理服务器之一
1612
            // 如果是的话说明该 IP头 是由前端代理服务器设置的
1613
            // 否则则是伪装的
1614
            if (!empty($tempIP)) {
1615
                $realIPBin = $this->ip2bin($this->realIP);
1616
1617
                foreach ($proxyIp as $ip) {
1618
                    $serverIPElements = explode('/', $ip);
1619
                    $serverIP         = $serverIPElements[0];
1620
                    $serverIPPrefix   = $serverIPElements[1] ?? 128;
1621
                    $serverIPBin      = $this->ip2bin($serverIP);
1622
1623
                    // IP类型不符
1624
                    if (strlen($realIPBin) !== strlen($serverIPBin)) {
1625
                        continue;
1626
                    }
1627
1628
                    if (strncmp($realIPBin, $serverIPBin, (int) $serverIPPrefix) === 0) {
1629
                        $this->realIP = $tempIP;
1630
                        break;
1631
                    }
1632
                }
1633
            }
1634
        }
1635
1636
        if (!$this->isValidIP($this->realIP)) {
1637
            $this->realIP = '0.0.0.0';
1638
        }
1639
1640
        return $this->realIP;
1641
    }
1642
1643
    /**
1644
     * 检测是否是合法的IP地址
1645
     *
1646
     * @param string $ip   IP地址
1647
     * @param string $type IP地址类型 (ipv4, ipv6)
1648
     *
1649
     * @return boolean
1650
     */
1651
    public function isValidIP(string $ip, string $type = ''): bool
1652
    {
1653
        switch (strtolower($type)) {
1654
            case 'ipv4':
1655
                $flag = FILTER_FLAG_IPV4;
1656
                break;
1657
            case 'ipv6':
1658
                $flag = FILTER_FLAG_IPV6;
1659
                break;
1660
            default:
1661
                $flag = null;
1662
                break;
1663
        }
1664
1665
        return boolval(filter_var($ip, FILTER_VALIDATE_IP, $flag));
1666
    }
1667
1668
    /**
1669
     * 将IP地址转换为二进制字符串
1670
     *
1671
     * @param string $ip
0 ignored issues
show
Coding Style introduced by
Missing parameter comment
Loading history...
1672
     *
1673
     * @return string
1674
     */
1675
    public function ip2bin(string $ip): string
1676
    {
1677
        if ($this->isValidIP($ip, 'ipv6')) {
1678
            $IPHex = str_split(bin2hex(inet_pton($ip)), 4);
1679
            foreach ($IPHex as $key => $value) {
1680
                $IPHex[$key] = intval($value, 16);
1681
            }
1682
            $IPBin = vsprintf('%016b%016b%016b%016b%016b%016b%016b%016b', $IPHex);
1683
        } else {
1684
            $IPHex = str_split(bin2hex(inet_pton($ip)), 2);
1685
            foreach ($IPHex as $key => $value) {
1686
                $IPHex[$key] = intval($value, 16);
1687
            }
1688
            $IPBin = vsprintf('%08b%08b%08b%08b', $IPHex);
1689
        }
1690
1691
        return $IPBin;
1692
    }
1693
1694
    /**
1695
     * 检测是否使用手机访问
1696
     * @access public
1697
     * @return bool
1698
     */
1699
    public function isMobile(): bool
1700
    {
1701
        if ($this->server('HTTP_VIA') && stristr($this->server('HTTP_VIA'), "wap")) {
1702
            return true;
1703
        } elseif ($this->server('HTTP_ACCEPT') && strpos(strtoupper($this->server('HTTP_ACCEPT')), "VND.WAP.WML")) {
1704
            return true;
1705
        } elseif ($this->server('HTTP_X_WAP_PROFILE') || $this->server('HTTP_PROFILE')) {
1706
            return true;
1707
        } 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'))) {
1708
            return true;
1709
        }
1710
1711
        return false;
1712
    }
1713
1714
    /**
1715
     * 当前URL地址中的scheme参数
1716
     * @access public
1717
     * @return string
1718
     */
1719
    public function scheme(): string
1720
    {
1721
        return $this->isSsl() ? 'https' : 'http';
1722
    }
1723
1724
    /**
1725
     * 当前请求URL地址中的query参数
1726
     * @access public
1727
     * @return string
1728
     */
1729
    public function query(): string
1730
    {
1731
        return $this->server('QUERY_STRING', '');
1732
    }
1733
1734
    /**
1735
     * 设置当前请求的host(包含端口)
1736
     * @access public
1737
     * @param  string $host 主机名(含端口)
1738
     * @return $this
1739
     */
1740
    public function setHost(string $host)
1741
    {
1742
        $this->host = $host;
1743
1744
        return $this;
1745
    }
1746
1747
    /**
1748
     * 当前请求的host
1749
     * @access public
1750
     * @param bool $strict  true 仅仅获取HOST
0 ignored issues
show
Coding Style introduced by
Expected 1 spaces after parameter name; 2 found
Loading history...
1751
     * @return string
1752
     */
1753
    public function host(bool $strict = false): string
1754
    {
1755
        if ($this->host) {
1756
            $host = $this->host;
1757
        } else {
1758
            $host = strval($this->server('HTTP_X_REAL_HOST') ?: $this->server('HTTP_HOST'));
1759
        }
1760
1761
        return true === $strict && strpos($host, ':') ? strstr($host, ':', true) : $host;
1762
    }
1763
1764
    /**
1765
     * 当前请求URL地址中的port参数
1766
     * @access public
1767
     * @return int
1768
     */
1769
    public function port(): int
1770
    {
1771
        return (int) $this->server('SERVER_PORT', '');
1772
    }
1773
1774
    /**
1775
     * 当前请求 SERVER_PROTOCOL
1776
     * @access public
1777
     * @return string
1778
     */
1779
    public function protocol(): string
1780
    {
1781
        return $this->server('SERVER_PROTOCOL', '');
1782
    }
1783
1784
    /**
1785
     * 当前请求 REMOTE_PORT
1786
     * @access public
1787
     * @return int
1788
     */
1789
    public function remotePort(): int
1790
    {
1791
        return (int) $this->server('REMOTE_PORT', '');
1792
    }
1793
1794
    /**
1795
     * 当前请求 HTTP_CONTENT_TYPE
1796
     * @access public
1797
     * @return string
1798
     */
1799
    public function contentType(): string
1800
    {
1801
        $contentType = $this->header('Content-Type');
1802
1803
        if ($contentType) {
1804
            if (strpos($contentType, ';')) {
0 ignored issues
show
Bug introduced by
It seems like $contentType can also be of type array; however, parameter $haystack of strpos() 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

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

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

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

1913
        $this->session->/** @scrutinizer ignore-call */ 
1914
                        set($name, $token);
Loading history...
1914
1915
        return $token;
1916
    }
1917
1918
    /**
1919
     * 检查请求令牌
1920
     * @access public
1921
     * @param  string $token 令牌名称
1922
     * @param  array  $data  表单数据
1923
     * @return bool
1924
     */
1925
    public function checkToken(string $token = '__token__', array $data = []): bool
1926
    {
1927
        if (in_array($this->method(), ['GET', 'HEAD', 'OPTIONS'], true)) {
1928
            return true;
1929
        }
1930
1931
        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

1931
        if (!$this->session->/** @scrutinizer ignore-call */ has($token)) {
Loading history...
1932
            // 令牌数据无效
1933
            return false;
1934
        }
1935
1936
        // Header验证
1937
        if ($this->header('X-CSRF-TOKEN') && $this->session->get($token) === $this->header('X-CSRF-TOKEN')) {
1938
            // 防止重复提交
1939
            $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

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