Completed
Pull Request — 6.0 (#2058)
by nhzex
05:48
created

Request::withHeader()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 4
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 2

Importance

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

857
                    $vars = $this->post(/** @scrutinizer ignore-type */ false);
Loading history...
858
                    break;
859
                case 'PUT':
860
                case 'DELETE':
861
                case 'PATCH':
862
                    $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

862
                    $vars = $this->put(/** @scrutinizer ignore-type */ false);
Loading history...
863
                    break;
864
                default:
865
                    $vars = [];
866
            }
867
868
            // 当前请求参数和URL地址中的参数合并
869
            $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::route(). ( Ignorable by Annotation )

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

869
            $this->param = array_merge($this->param, $this->get(false), $vars, $this->route(/** @scrutinizer ignore-type */ false));
Loading history...
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

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

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

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

1611
                $tempIP = trim(explode(',', /** @scrutinizer ignore-type */ $tempIP)[0]);
Loading history...
1612
1613
                if (!$this->isValidIP($tempIP)) {
1614
                    $tempIP = null;
1615
                } else {
1616
                    break;
1617
                }
1618
            }
1619
1620
            // tempIP不为空,说明获取到了一个IP地址
1621
            // 这时我们检查 REMOTE_ADDR 是不是指定的前端代理服务器之一
1622
            // 如果是的话说明该 IP头 是由前端代理服务器设置的
1623
            // 否则则是伪装的
1624
            if (!empty($tempIP)) {
1625
                $realIPBin = $this->ip2bin($this->realIP);
1626
1627
                foreach ($proxyIp as $ip) {
1628
                    $serverIPElements = explode('/', $ip);
1629
                    $serverIP         = $serverIPElements[0];
1630
                    $serverIPPrefix   = $serverIPElements[1] ?? 128;
1631
                    $serverIPBin      = $this->ip2bin($serverIP);
1632
1633
                    // IP类型不符
1634
                    if (strlen($realIPBin) !== strlen($serverIPBin)) {
1635
                        continue;
1636
                    }
1637
1638
                    if (strncmp($realIPBin, $serverIPBin, (int) $serverIPPrefix) === 0) {
1639
                        $this->realIP = $tempIP;
1640
                        break;
1641
                    }
1642
                }
1643
            }
1644
        }
1645
1646
        if (!$this->isValidIP($this->realIP)) {
1647
            $this->realIP = '0.0.0.0';
1648
        }
1649
1650
        return $this->realIP;
1651
    }
1652
1653
    /**
1654
     * 检测是否是合法的IP地址
1655
     *
1656
     * @param string $ip   IP地址
1657
     * @param string $type IP地址类型 (ipv4, ipv6)
1658
     *
1659
     * @return boolean
1660
     */
1661
    public function isValidIP(string $ip, string $type = ''): bool
1662
    {
1663
        switch (strtolower($type)) {
1664
            case 'ipv4':
1665
                $flag = FILTER_FLAG_IPV4;
1666
                break;
1667
            case 'ipv6':
1668
                $flag = FILTER_FLAG_IPV6;
1669
                break;
1670
            default:
1671
                $flag = null;
1672
                break;
1673
        }
1674
1675
        return boolval(filter_var($ip, FILTER_VALIDATE_IP, $flag));
1676
    }
1677
1678
    /**
1679
     * 将IP地址转换为二进制字符串
1680
     *
1681
     * @param string $ip
0 ignored issues
show
Coding Style introduced by
Missing parameter comment
Loading history...
1682
     *
1683
     * @return string
1684
     */
1685
    public function ip2bin(string $ip): string
1686
    {
1687
        if ($this->isValidIP($ip, 'ipv6')) {
1688
            $IPHex = str_split(bin2hex(inet_pton($ip)), 4);
1689
            foreach ($IPHex as $key => $value) {
1690
                $IPHex[$key] = intval($value, 16);
1691
            }
1692
            $IPBin = vsprintf('%016b%016b%016b%016b%016b%016b%016b%016b', $IPHex);
1693
        } else {
1694
            $IPHex = str_split(bin2hex(inet_pton($ip)), 2);
1695
            foreach ($IPHex as $key => $value) {
1696
                $IPHex[$key] = intval($value, 16);
1697
            }
1698
            $IPBin = vsprintf('%08b%08b%08b%08b', $IPHex);
1699
        }
1700
1701
        return $IPBin;
1702
    }
1703
1704
    /**
1705
     * 检测是否使用手机访问
1706
     * @access public
1707
     * @return bool
1708
     */
1709
    public function isMobile(): bool
1710
    {
1711
        if ($this->server('HTTP_VIA') && stristr($this->server('HTTP_VIA'), "wap")) {
1712
            return true;
1713
        } elseif ($this->server('HTTP_ACCEPT') && strpos(strtoupper($this->server('HTTP_ACCEPT')), "VND.WAP.WML")) {
1714
            return true;
1715
        } elseif ($this->server('HTTP_X_WAP_PROFILE') || $this->server('HTTP_PROFILE')) {
1716
            return true;
1717
        } 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'))) {
1718
            return true;
1719
        }
1720
1721
        return false;
1722
    }
1723
1724
    /**
1725
     * 当前URL地址中的scheme参数
1726
     * @access public
1727
     * @return string
1728
     */
1729
    public function scheme(): string
1730
    {
1731
        return $this->isSsl() ? 'https' : 'http';
1732
    }
1733
1734
    /**
1735
     * 当前请求URL地址中的query参数
1736
     * @access public
1737
     * @return string
1738
     */
1739
    public function query(): string
1740
    {
1741
        return $this->server('QUERY_STRING', '');
1742
    }
1743
1744
    /**
1745
     * 设置当前请求的host(包含端口)
1746
     * @access public
1747
     * @param  string $host 主机名(含端口)
1748
     * @return $this
1749
     */
1750
    public function setHost(string $host)
1751
    {
1752
        $this->host = $host;
1753
1754
        return $this;
1755
    }
1756
1757
    /**
1758
     * 当前请求的host
1759
     * @access public
1760
     * @param bool $strict  true 仅仅获取HOST
0 ignored issues
show
Coding Style introduced by
Expected 1 spaces after parameter name; 2 found
Loading history...
1761
     * @return string
1762
     */
1763
    public function host(bool $strict = false): string
1764
    {
1765
        if ($this->host) {
1766
            $host = $this->host;
1767
        } else {
1768
            $host = strval($this->server('HTTP_X_REAL_HOST') ?: $this->server('HTTP_HOST'));
1769
        }
1770
1771
        return true === $strict && strpos($host, ':') ? strstr($host, ':', true) : $host;
1772
    }
1773
1774
    /**
1775
     * 当前请求URL地址中的port参数
1776
     * @access public
1777
     * @return int
1778
     */
1779
    public function port(): int
1780
    {
1781
        return (int) $this->server('SERVER_PORT', '');
1782
    }
1783
1784
    /**
1785
     * 当前请求 SERVER_PROTOCOL
1786
     * @access public
1787
     * @return string
1788
     */
1789
    public function protocol(): string
1790
    {
1791
        return $this->server('SERVER_PROTOCOL', '');
1792
    }
1793
1794
    /**
1795
     * 当前请求 REMOTE_PORT
1796
     * @access public
1797
     * @return int
1798
     */
1799
    public function remotePort(): int
1800
    {
1801
        return (int) $this->server('REMOTE_PORT', '');
1802
    }
1803
1804
    /**
1805
     * 当前请求 HTTP_CONTENT_TYPE
1806
     * @access public
1807
     * @return string
1808
     */
1809 2
    public function contentType(): string
1810
    {
1811 2
        $contentType = $this->server('CONTENT_TYPE');
1812
1813 2
        if ($contentType) {
1814
            if (strpos($contentType, ';')) {
1815
                list($type) = explode(';', $contentType);
1816
            } else {
1817
                $type = $contentType;
1818
            }
1819
            return trim($type);
1820
        }
1821
1822 2
        return '';
1823
    }
1824
1825
    /**
1826
     * 获取当前请求的安全Key
1827
     * @access public
1828
     * @return string
1829
     */
1830
    public function secureKey(): string
1831
    {
1832
        if (is_null($this->secureKey)) {
0 ignored issues
show
introduced by
The condition is_null($this->secureKey) is always false.
Loading history...
1833
            $this->secureKey = uniqid('', true);
1834
        }
1835
1836
        return $this->secureKey;
1837
    }
1838
1839
    /**
1840
     * 设置当前的控制器名
1841
     * @access public
1842
     * @param  string $controller 控制器名
1843
     * @return $this
1844
     */
1845
    public function setController(string $controller)
1846
    {
1847
        $this->controller = $controller;
1848
        return $this;
1849
    }
1850
1851
    /**
1852
     * 设置当前的操作名
1853
     * @access public
1854
     * @param  string $action 操作名
1855
     * @return $this
1856
     */
1857
    public function setAction(string $action)
1858
    {
1859
        $this->action = $action;
1860
        return $this;
1861
    }
1862
1863
    /**
1864
     * 获取当前的控制器名
1865
     * @access public
1866
     * @param  bool $convert 转换为小写
1867
     * @return string
1868
     */
1869
    public function controller(bool $convert = false): string
1870
    {
1871
        $name = $this->controller ?: '';
1872
        return $convert ? strtolower($name) : $name;
1873
    }
1874
1875
    /**
1876
     * 获取当前的操作名
1877
     * @access public
1878
     * @param  bool $convert 转换为小写
1879
     * @return string
1880
     */
1881
    public function action(bool $convert = false): string
1882
    {
1883
        $name = $this->action ?: '';
1884
        return $convert ? strtolower($name) : $name;
1885
    }
1886
1887
    /**
1888
     * 设置或者获取当前请求的content
1889
     * @access public
1890
     * @return string
1891
     */
1892
    public function getContent(): string
1893
    {
1894
        if (is_null($this->content)) {
0 ignored issues
show
introduced by
The condition is_null($this->content) is always false.
Loading history...
1895
            $this->content = $this->input;
1896
        }
1897
1898
        return $this->content;
1899
    }
1900
1901
    /**
1902
     * 获取当前请求的php://input
1903
     * @access public
1904
     * @return string
1905
     */
1906
    public function getInput(): string
1907
    {
1908
        return $this->input;
1909
    }
1910
1911
    /**
1912
     * 生成请求令牌
1913
     * @access public
1914
     * @param  string $name 令牌名称
1915
     * @param  mixed  $type 令牌生成方法
1916
     * @return string
1917
     */
1918
    public function buildToken(string $name = '__token__', $type = 'md5'): string
1919
    {
1920
        $type  = is_callable($type) ? $type : 'md5';
1921
        $token = call_user_func($type, $this->server('REQUEST_TIME_FLOAT'));
1922
1923
        $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

1923
        $this->session->/** @scrutinizer ignore-call */ 
1924
                        set($name, $token);
Loading history...
1924
1925
        return $token;
1926
    }
1927
1928
    /**
1929
     * 检查请求令牌
1930
     * @access public
1931
     * @param  string $token 令牌名称
1932
     * @param  array  $data  表单数据
1933
     * @return bool
1934
     */
1935
    public function checkToken(string $token = '__token__', array $data = []): bool
1936
    {
1937
        if (in_array($this->method(), ['GET', 'HEAD', 'OPTIONS'], true)) {
1938
            return true;
1939
        }
1940
1941
        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

1941
        if (!$this->session->/** @scrutinizer ignore-call */ has($token)) {
Loading history...
1942
            // 令牌数据无效
1943
            return false;
1944
        }
1945
1946
        // Header验证
1947
        if ($this->header('X-CSRF-TOKEN') && $this->session->get($token) === $this->header('X-CSRF-TOKEN')) {
1948
            // 防止重复提交
1949
            $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

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