Completed
Push — 6.0 ( 11f2bc...c0e914 )
by liu
03:26
created

Request::isSsl()   B

Complexity

Conditions 9
Paths 6

Size

Total Lines 15
Code Lines 11

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 90

Importance

Changes 0
Metric Value
cc 9
eloc 11
nc 6
nop 0
dl 0
loc 15
ccs 0
cts 12
cp 0
crap 90
rs 8.0555
c 0
b 0
f 0
1
<?php
2
// +----------------------------------------------------------------------
1 ignored issue
show
Coding Style introduced by
You must use "/**" style comments for a file comment
Loading history...
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\route\Dispatch;
16
17
/**
18
 * 请求管理类
19
 */
5 ignored issues
show
Coding Style introduced by
Missing @category tag in class comment
Loading history...
Coding Style introduced by
Missing @package tag in class comment
Loading history...
Coding Style introduced by
Missing @author tag in class comment
Loading history...
Coding Style introduced by
Missing @license tag in class comment
Loading history...
Coding Style introduced by
Missing @link tag in class comment
Loading history...
20
class Request
21
{
22
    /**
23
     * 兼容PATH_INFO获取
24
     * @var array
25
     */
26
    protected $pathinfoFetch = ['ORIG_PATH_INFO', 'REDIRECT_PATH_INFO', 'REDIRECT_URL'];
27
28
    /**
29
     * PATHINFO变量名 用于兼容模式
30
     * @var string
31
     */
32
    protected $varPathinfo = 's';
33
34
    /**
35
     * 请求类型
36
     * @var string
37
     */
38
    protected $varMethod = '_method';
39
40
    /**
41
     * 表单ajax伪装变量
42
     * @var string
43
     */
44
    protected $varAjax = '_ajax';
45
46
    /**
47
     * 表单pjax伪装变量
48
     * @var string
49
     */
50
    protected $varPjax = '_pjax';
51
52
    /**
53
     * 域名根
54
     * @var string
55
     */
56
    protected $rootDomain = '';
57
58
    /**
59
     * HTTPS代理标识
60
     * @var string
61
     */
62
    protected $httpsAgentName = '';
63
64
    /**
65
     * 前端代理服务器IP
66
     * @var array
67
     */
68
    protected $proxyServerIp = [];
69
70
    /**
71
     * 前端代理服务器真实IP头
72
     * @var array
73
     */
74
    protected $proxyServerIpHeader = ['HTTP_X_REAL_IP', 'HTTP_X_FORWARDED_FOR', 'HTTP_CLIENT_IP', 'HTTP_X_CLIENT_IP', 'HTTP_X_CLUSTER_CLIENT_IP'];
75
76
    /**
77
     * 请求类型
78
     * @var string
79
     */
80
    protected $method;
81
82
    /**
83
     * 域名(含协议及端口)
84
     * @var string
85
     */
86
    protected $domain;
87
88
    /**
89
     * HOST(含端口)
90
     * @var string
91
     */
92
    protected $host;
93
94
    /**
95
     * 子域名
96
     * @var string
97
     */
98
    protected $subDomain;
99
100
    /**
101
     * 泛域名
102
     * @var string
103
     */
104
    protected $panDomain;
105
106
    /**
107
     * 当前URL地址
108
     * @var string
109
     */
110
    protected $url;
111
112
    /**
113
     * 基础URL
114
     * @var string
115
     */
116
    protected $baseUrl;
117
118
    /**
119
     * 当前执行的文件
120
     * @var string
121
     */
122
    protected $baseFile;
123
124
    /**
125
     * 访问的ROOT地址
126
     * @var string
127
     */
128
    protected $root;
129
130
    /**
131
     * pathinfo
0 ignored issues
show
Coding Style introduced by
Doc comment short description must start with a capital letter
Loading history...
132
     * @var string
133
     */
134
    protected $pathinfo;
135
136
    /**
137
     * pathinfo(不含后缀)
0 ignored issues
show
Coding Style introduced by
Doc comment short description must start with a capital letter
Loading history...
138
     * @var string
139
     */
140
    protected $path;
141
142
    /**
143
     * 当前请求的IP地址
144
     * @var string
145
     */
146
    protected $realIP;
147
148
    /**
149
     * 当前调度信息
150
     * @var Dispatch
151
     */
152
    protected $dispatch;
153
154
    /**
155
     * 当前应用名
156
     * @var string
157
     */
158
    protected $app;
159
160
    /**
161
     * 当前控制器名
162
     * @var string
163
     */
164
    protected $controller;
165
166
    /**
167
     * 当前操作名
168
     * @var string
169
     */
170
    protected $action;
171
172
    /**
173
     * 当前请求参数
174
     * @var array
175
     */
176
    protected $param = [];
177
178
    /**
179
     * 当前GET参数
180
     * @var array
181
     */
182
    protected $get = [];
183
184
    /**
185
     * 当前POST参数
186
     * @var array
187
     */
188
    protected $post = [];
189
190
    /**
191
     * 当前REQUEST参数
192
     * @var array
193
     */
194
    protected $request = [];
195
196
    /**
197
     * 当前ROUTE参数
198
     * @var array
199
     */
200
    protected $route = [];
201
202
    /**
203
     * 中间件传递的参数
204
     * @var array
205
     */
206
    protected $middleware = [];
207
208
    /**
209
     * 当前PUT参数
210
     * @var array
211
     */
212
    protected $put;
213
214
    /**
215
     * SESSION对象
216
     * @var Session
217
     */
218
    protected $session;
219
220
    /**
221
     * COOKIE数据
222
     * @var array
223
     */
224
    protected $cookie = [];
225
226
    /**
227
     * ENV对象
228
     * @var Env
229
     */
230
    protected $env;
231
232
    /**
233
     * 当前SERVER参数
234
     * @var array
235
     */
236
    protected $server = [];
237
238
    /**
239
     * 当前FILE参数
240
     * @var array
241
     */
242
    protected $file = [];
243
244
    /**
245
     * 当前HEADER参数
246
     * @var array
247
     */
248
    protected $header = [];
249
250
    /**
251
     * 资源类型定义
252
     * @var array
253
     */
254
    protected $mimeType = [
255
        'xml'   => 'application/xml,text/xml,application/x-xml',
256
        'json'  => 'application/json,text/x-json,application/jsonrequest,text/json',
257
        'js'    => 'text/javascript,application/javascript,application/x-javascript',
258
        'css'   => 'text/css',
259
        'rss'   => 'application/rss+xml',
260
        'yaml'  => 'application/x-yaml,text/yaml',
261
        'atom'  => 'application/atom+xml',
262
        'pdf'   => 'application/pdf',
263
        'text'  => 'text/plain',
264
        'image' => 'image/png,image/jpg,image/jpeg,image/pjpeg,image/gif,image/webp,image/*',
265
        'csv'   => 'text/csv',
266
        'html'  => 'text/html,application/xhtml+xml,*/*',
267
    ];
268
269
    /**
270
     * 当前请求内容
271
     * @var string
272
     */
273
    protected $content;
274
275
    /**
276
     * 全局过滤规则
277
     * @var array
278
     */
279
    protected $filter;
280
281
    /**
282
     * php://input内容
0 ignored issues
show
Coding Style introduced by
Doc comment short description must start with a capital letter
Loading history...
283
     * @var string
284
     */
285
    // php://input
286
    protected $input;
287
288
    /**
289
     * 请求缓存
290
     * @var array
291
     */
292
    protected $cache;
293
294
    /**
295
     * 缓存是否检查
296
     * @var bool
297
     */
298
    protected $isCheckCache;
299
300
    /**
301
     * 请求安全Key
302
     * @var string
303
     */
304
    protected $secureKey;
305
306
    /**
307
     * 是否合并Param
308
     * @var bool
309
     */
310
    protected $mergeParam = false;
311
312
    /**
313
     * 架构函数
314
     * @access public
315
     */
316 8
    public function __construct()
317
    {
318
        // 保存 php://input
319 8
        $this->input = file_get_contents('php://input');
320 8
    }
321
322 8
    public static function __make(App $app)
2 ignored issues
show
Coding Style introduced by
Method name "Request::__make" is invalid; only PHP magic methods should be prefixed with a double underscore
Loading history...
Coding Style introduced by
Public method name "Request::__make" must not be prefixed with an underscore
Loading history...
Coding Style introduced by
Missing doc comment for function __make()
Loading history...
323
    {
324 8
        $request = new static();
325
326 8
        $request->server  = $_SERVER;
327 8
        $request->env     = $app->env;
328 8
        $request->get     = $_GET;
329 8
        $request->post    = $_POST ?: $request->getInputData($request->input);
330 8
        $request->put     = $request->getInputData($request->input);
331 8
        $request->request = $_REQUEST;
332 8
        $request->cookie  = $_COOKIE;
333 8
        $request->file    = $_FILES ?? [];
334
335 8
        if (function_exists('apache_request_headers') && $result = apache_request_headers()) {
336
            $header = $result;
337
        } else {
338 8
            $header = [];
339 8
            $server = $_SERVER;
340 8
            foreach ($server as $key => $val) {
341 8
                if (0 === strpos($key, 'HTTP_')) {
342
                    $key          = str_replace('_', '-', strtolower(substr($key, 5)));
343 8
                    $header[$key] = $val;
344
                }
345
            }
346 8
            if (isset($server['CONTENT_TYPE'])) {
347
                $header['content-type'] = $server['CONTENT_TYPE'];
348
            }
349 8
            if (isset($server['CONTENT_LENGTH'])) {
350
                $header['content-length'] = $server['CONTENT_LENGTH'];
351
            }
352
        }
353
354 8
        $request->header = array_change_key_case($header);
355
356 8
        return $request;
357
    }
358
359
    /**
360
     * 设置当前包含协议的域名
361
     * @access public
362
     * @param  string $domain 域名
363
     * @return $this
364
     */
365
    public function setDomain(string $domain)
366
    {
367
        $this->domain = $domain;
368
        return $this;
369
    }
370
371
    /**
372
     * 获取当前包含协议的域名
373
     * @access public
374
     * @param  bool $port 是否需要去除端口号
375
     * @return string
376
     */
377
    public function domain(bool $port = false): string
378
    {
379
        return $this->scheme() . '://' . $this->host($port);
380
    }
381
382
    /**
383
     * 获取当前根域名
384
     * @access public
385
     * @return string
386
     */
387
    public function rootDomain(): string
388
    {
389
        $root = $this->rootDomain;
390
391
        if (!$root) {
392
            $item  = explode('.', $this->host());
393
            $count = count($item);
394
            $root  = $count > 1 ? $item[$count - 2] . '.' . $item[$count - 1] : $item[0];
395
        }
396
397
        return $root;
398
    }
399
400
    /**
401
     * 设置当前泛域名的值
402
     * @access public
403
     * @param  string $domain 域名
404
     * @return $this
405
     */
406
    public function setSubDomain(string $domain)
407
    {
408
        $this->subDomain = $domain;
409
        return $this;
410
    }
411
412
    /**
413
     * 获取当前子域名
414
     * @access public
415
     * @return string
416
     */
417 3
    public function subDomain(): string
418
    {
419 3
        if (is_null($this->subDomain)) {
0 ignored issues
show
introduced by
The condition is_null($this->subDomain) is always false.
Loading history...
420
            // 获取当前主域名
421 3
            $rootDomain = $this->urlDdomainRoot;
422
423 3
            if ($rootDomain) {
424
                // 配置域名根 例如 thinkphp.cn 163.com.cn 如果是国家级域名 com.cn net.cn 之类的域名需要配置
425
                $domain = explode('.', rtrim(stristr($this->host(), $rootDomain, true), '.'));
426
            } else {
427 3
                $domain = explode('.', $this->host(), -2);
428
            }
429
430 3
            $this->subDomain = implode('.', $domain);
431
        }
432
433 3
        return $this->subDomain;
434
    }
435
436
    /**
437
     * 设置当前泛域名的值
438
     * @access public
439
     * @param  string $domain 域名
440
     * @return $this
441
     */
442
    public function setPanDomain(string $domain)
443
    {
444
        $this->panDomain = $domain;
445
        return $this;
446
    }
447
448
    /**
449
     * 获取当前泛域名的值
450
     * @access public
451
     * @return string
452
     */
453
    public function panDomain(): string
454
    {
455
        return $this->panDomain ?: '';
456
    }
457
458
    /**
459
     * 设置当前完整URL 包括QUERY_STRING
460
     * @access public
461
     * @param  string $url URL地址
462
     * @return $this
463
     */
464
    public function setUrl(string $url)
465
    {
466
        $this->url = $url;
467
        return $this;
468
    }
469
470
    /**
471
     * 获取当前完整URL 包括QUERY_STRING
472
     * @access public
473
     * @param  bool $complete 是否包含完整域名
474
     * @return string
475
     */
476
    public function url(bool $complete = false): string
477
    {
478
        if ($this->url) {
479
            $url = $this->url;
480
        } elseif ($this->server('HTTP_X_REWRITE_URL')) {
481
            $url = $this->server('HTTP_X_REWRITE_URL');
482
        } elseif ($this->server('REQUEST_URI')) {
483
            $url = $this->server('REQUEST_URI');
484
        } elseif ($this->server('ORIG_PATH_INFO')) {
485
            $url = $this->server('ORIG_PATH_INFO') . (!empty($this->server('QUERY_STRING')) ? '?' . $this->server('QUERY_STRING') : '');
486
        } elseif (isset($_SERVER['argv'][1])) {
487
            $url = $_SERVER['argv'][1];
488
        } else {
489
            $url = '';
490
        }
491
492
        return $complete ? $this->domain() . $url : $url;
493
    }
494
495
    /**
496
     * 设置当前URL 不含QUERY_STRING
497
     * @access public
498
     * @param  string $url URL地址
499
     * @return $this
500
     */
501
    public function setBaseUrl(string $url)
502
    {
503
        $this->baseUrl = $url;
504
        return $this;
505
    }
506
507
    /**
508
     * 获取当前URL 不含QUERY_STRING
509
     * @access public
510
     * @param  bool $complete 是否包含完整域名
511
     * @return string
512
     */
513
    public function baseUrl(bool $complete = false): string
514
    {
515
        if (!$this->baseUrl) {
516
            $str           = $this->url();
517
            $this->baseUrl = strpos($str, '?') ? strstr($str, '?', true) : $str;
518
        }
519
520
        return $complete ? $this->domain() . $this->baseUrl : $this->baseUrl;
521
    }
522
523
    /**
524
     * 获取当前执行的文件 SCRIPT_NAME
525
     * @access public
526
     * @param  bool $complete 是否包含完整域名
527
     * @return string
528
     */
529
    public function baseFile(bool $complete = false): string
530
    {
531
        if (!$this->baseFile) {
532
            $url = '';
533
            if (!$this->isCli()) {
534
                $script_name = basename($this->server('SCRIPT_FILENAME'));
535
                if (basename($this->server('SCRIPT_NAME')) === $script_name) {
536
                    $url = $this->server('SCRIPT_NAME');
537
                } elseif (basename($this->server('PHP_SELF')) === $script_name) {
538
                    $url = $this->server('PHP_SELF');
539
                } elseif (basename($this->server('ORIG_SCRIPT_NAME')) === $script_name) {
540
                    $url = $this->server('ORIG_SCRIPT_NAME');
541
                } elseif (($pos = strpos($this->server('PHP_SELF'), '/' . $script_name)) !== false) {
542
                    $url = substr($this->server('SCRIPT_NAME'), 0, $pos) . '/' . $script_name;
543
                } elseif ($this->server('DOCUMENT_ROOT') && strpos($this->server('SCRIPT_FILENAME'), $this->server('DOCUMENT_ROOT')) === 0) {
544
                    $url = str_replace('\\', '/', str_replace($this->server('DOCUMENT_ROOT'), '', $this->server('SCRIPT_FILENAME')));
545
                }
546
            }
547
            $this->baseFile = $url;
548
        }
549
550
        return $complete ? $this->domain() . $this->baseFile : $this->baseFile;
551
    }
552
553
    /**
554
     * 设置URL访问根地址
555
     * @access public
556
     * @param  string $url URL地址
557
     * @return $this
558
     */
559 2
    public function setRoot(string $url)
560
    {
561 2
        $this->root = $url;
562 2
        return $this;
563
    }
564
565
    /**
566
     * 获取URL访问根地址
567
     * @access public
568
     * @param  bool $complete 是否包含完整域名
569
     * @return string
570
     */
571
    public function root(bool $complete = false): string
572
    {
573
        if (!$this->root) {
574
            $file = $this->baseFile();
575
            if ($file && 0 !== strpos($this->url(), $file)) {
576
                $file = str_replace('\\', '/', dirname($file));
577
            }
578
            $this->root = rtrim($file, '/');
579
        }
580
581
        return $complete ? $this->domain() . $this->root : $this->root;
582
    }
583
584
    /**
585
     * 获取URL访问根目录
586
     * @access public
587
     * @return string
588
     */
589
    public function rootUrl(): string
590
    {
591
        $base = $this->root();
592
        $root = strpos($base, '.') ? ltrim(dirname($base), DIRECTORY_SEPARATOR) : $base;
593
594
        if ('' != $root) {
595
            $root = '/' . ltrim($root, '/');
596
        }
597
598
        return $root;
599
    }
600
601
    /**
602
     * 设置当前请求的pathinfo
603
     * @access public
604
     * @param  string $pathinfo
0 ignored issues
show
Coding Style introduced by
Missing parameter comment
Loading history...
605
     * @return $this
606
     */
607 2
    public function setPathinfo(string $pathinfo)
608
    {
609 2
        $this->pathinfo = $pathinfo;
610 2
        return $this;
611
    }
612
613
    /**
614
     * 获取当前请求URL的pathinfo信息(含URL后缀)
615
     * @access public
616
     * @return string
617
     */
618
    public function pathinfo(): string
619
    {
620
        if (is_null($this->pathinfo)) {
0 ignored issues
show
introduced by
The condition is_null($this->pathinfo) is always false.
Loading history...
621
            if (isset($_GET[$this->varPathinfo])) {
622
                // 判断URL里面是否有兼容模式参数
623
                $pathinfo = $_GET[$this->varPathinfo];
624
                unset($_GET[$this->varPathinfo]);
625
            } elseif ($this->server('PATH_INFO')) {
626
                $pathinfo = $this->server('PATH_INFO');
627
            } elseif ('cli-server' == PHP_SAPI) {
628
                $pathinfo = strpos($this->server('REQUEST_URI'), '?') ? strstr($this->server('REQUEST_URI'), '?', true) : $this->server('REQUEST_URI');
629
            }
630
631
            // 分析PATHINFO信息
632
            if (!isset($pathinfo)) {
633
                foreach ($this->pathinfoFetch as $type) {
634
                    if ($this->server($type)) {
635
                        $pathinfo = (0 === strpos($this->server($type), $this->server('SCRIPT_NAME'))) ?
636
                        substr($this->server($type), strlen($this->server('SCRIPT_NAME'))) : $this->server($type);
637
                        break;
638
                    }
639
                }
640
            }
641
            $this->pathinfo = empty($pathinfo) || '/' == $pathinfo ? '' : ltrim($pathinfo, '/');
642
        }
643
644
        return $this->pathinfo;
645
    }
646
647
    /**
648
     * 当前URL的访问后缀
649
     * @access public
650
     * @return string
651
     */
652
    public function ext(): string
653
    {
654
        return pathinfo($this->pathinfo(), PATHINFO_EXTENSION);
655
    }
656
657
    /**
658
     * 获取当前请求的时间
659
     * @access public
660
     * @param  bool $float 是否使用浮点类型
661
     * @return integer|float
662
     */
663
    public function time(bool $float = false)
664
    {
665
        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...
666
    }
667
668
    /**
669
     * 当前请求的资源类型
670
     * @access public
671
     * @return string
672
     */
673 8
    public function type(): string
674
    {
675 8
        $accept = $this->server('HTTP_ACCEPT');
676
677 8
        if (empty($accept)) {
678 8
            return '';
679
        }
680
681
        foreach ($this->mimeType as $key => $val) {
682
            $array = explode(',', $val);
683
            foreach ($array as $k => $v) {
684
                if (stristr($accept, $v)) {
685
                    return $key;
686
                }
687
            }
688
        }
689
690
        return '';
691
    }
692
693
    /**
694
     * 设置资源类型
695
     * @access public
696
     * @param  string|array $type 资源类型名
697
     * @param  string       $val 资源类型
0 ignored issues
show
Coding Style introduced by
Expected 2 spaces after parameter name; 1 found
Loading history...
698
     * @return void
699
     */
700
    public function mimeType($type, $val = ''): void
701
    {
702
        if (is_array($type)) {
703
            $this->mimeType = array_merge($this->mimeType, $type);
704
        } else {
705
            $this->mimeType[$type] = $val;
706
        }
707
    }
708
709
    /**
710
     * 设置请求类型
711
     * @access public
712
     * @param  string $method 请求类型
713
     * @return $this
714
     */
715
    public function setMethod(string $method)
716
    {
717
        $this->method = strtoupper($method);
718
        return $this;
719
    }
720
721
    /**
722
     * 当前的请求类型
723
     * @access public
724
     * @param  bool $origin 是否获取原始请求类型
725
     * @return string
726
     */
727
    public function method(bool $origin = false): string
728
    {
729
        if ($origin) {
730
            // 获取原始请求类型
731
            return $this->server('REQUEST_METHOD') ?: 'GET';
732
        } elseif (!$this->method) {
733
            if (isset($_POST[$this->varMethod])) {
734
                $method = strtolower($_POST[$this->varMethod]);
735
                if (in_array($method, ['get', 'post', 'put', 'patch', 'delete'])) {
736
                    $this->method    = strtoupper($method);
737
                    $this->{$method} = $_POST;
738
                } else {
739
                    $this->method = 'POST';
740
                }
741
                unset($_POST[$this->varMethod]);
742
            } elseif ($this->server('HTTP_X_HTTP_METHOD_OVERRIDE')) {
743
                $this->method = strtoupper($this->server('HTTP_X_HTTP_METHOD_OVERRIDE'));
744
            } else {
745
                $this->method = $this->server('REQUEST_METHOD') ?: 'GET';
746
            }
747
        }
748
749
        return $this->method;
750
    }
751
752
    /**
753
     * 是否为GET请求
754
     * @access public
755
     * @return bool
756
     */
757
    public function isGet(): bool
758
    {
759
        return $this->method() == 'GET';
760
    }
761
762
    /**
763
     * 是否为POST请求
764
     * @access public
765
     * @return bool
766
     */
767
    public function isPost(): bool
768
    {
769
        return $this->method() == 'POST';
770
    }
771
772
    /**
773
     * 是否为PUT请求
774
     * @access public
775
     * @return bool
776
     */
777
    public function isPut(): bool
778
    {
779
        return $this->method() == 'PUT';
780
    }
781
782
    /**
783
     * 是否为DELTE请求
784
     * @access public
785
     * @return bool
786
     */
787
    public function isDelete(): bool
788
    {
789
        return $this->method() == 'DELETE';
790
    }
791
792
    /**
793
     * 是否为HEAD请求
794
     * @access public
795
     * @return bool
796
     */
797
    public function isHead(): bool
798
    {
799
        return $this->method() == 'HEAD';
800
    }
801
802
    /**
803
     * 是否为PATCH请求
804
     * @access public
805
     * @return bool
806
     */
807
    public function isPatch(): bool
808
    {
809
        return $this->method() == 'PATCH';
810
    }
811
812
    /**
813
     * 是否为OPTIONS请求
814
     * @access public
815
     * @return bool
816
     */
817
    public function isOptions(): bool
818
    {
819
        return $this->method() == 'OPTIONS';
820
    }
821
822
    /**
823
     * 是否为cli
824
     * @access public
825
     * @return bool
826
     */
827
    public function isCli(): bool
828
    {
829
        return PHP_SAPI == 'cli';
830
    }
831
832
    /**
833
     * 是否为cgi
834
     * @access public
835
     * @return bool
836
     */
837
    public function isCgi(): bool
838
    {
839
        return strpos(PHP_SAPI, 'cgi') === 0;
840
    }
841
842
    /**
843
     * 获取当前请求的参数
844
     * @access public
845
     * @param  string|array $name 变量名
0 ignored issues
show
Coding Style introduced by
Expected 4 spaces after parameter name; 1 found
Loading history...
846
     * @param  mixed        $default 默认值
847
     * @param  string|array $filter 过滤方法
0 ignored issues
show
Coding Style introduced by
Expected 2 spaces after parameter name; 1 found
Loading history...
848
     * @return mixed
849
     */
850
    public function param($name = '', $default = null, $filter = '')
851
    {
852
        if (empty($this->mergeParam)) {
853
            $method = $this->method(true);
854
855
            // 自动获取请求变量
856
            switch ($method) {
857
                case 'POST':
1 ignored issue
show
Coding Style introduced by
Line indented incorrectly; expected 12 spaces, found 16
Loading history...
858
                    $vars = $this->post(false);
859
                    break;
860
                case 'PUT':
1 ignored issue
show
Coding Style introduced by
Line indented incorrectly; expected 12 spaces, found 16
Loading history...
861
                case 'DELETE':
1 ignored issue
show
Coding Style introduced by
Line indented incorrectly; expected 12 spaces, found 16
Loading history...
862
                case 'PATCH':
1 ignored issue
show
Coding Style introduced by
Line indented incorrectly; expected 12 spaces, found 16
Loading history...
863
                    $vars = $this->put(false);
864
                    break;
865
                default:
1 ignored issue
show
Coding Style introduced by
Line indented incorrectly; expected 12 spaces, found 16
Loading history...
866
                    $vars = [];
867
            }
868
869
            // 当前请求参数和URL地址中的参数合并
870
            $this->param = array_merge($this->param, $this->get(false), $vars, $this->route(false));
871
872
            $this->mergeParam = true;
873
        }
874
875
        if (is_array($name)) {
876
            return $this->only($name, $this->param, $filter);
877
        }
878
879
        return $this->input($this->param, $name, $default, $filter);
880
    }
881
882
    /**
883
     * 设置路由变量
884
     * @access public
885
     * @param  array $route 路由变量
886
     * @return $this
887
     */
888
    public function setRoute(array $route)
889
    {
890
        $this->route = array_merge($this->route, $route);
891
        return $this;
892
    }
893
894
    /**
895
     * 获取路由参数
896
     * @access public
897
     * @param  mixed        $name 变量名
0 ignored issues
show
Coding Style introduced by
Expected 4 spaces after parameter name; 1 found
Loading history...
898
     * @param  mixed        $default 默认值
899
     * @param  string|array $filter 过滤方法
0 ignored issues
show
Coding Style introduced by
Expected 2 spaces after parameter name; 1 found
Loading history...
900
     * @return mixed
901
     */
902
    public function route($name = '', $default = null, $filter = '')
903
    {
904
        if (is_array($name)) {
905
            return $this->only($name, $this->route, $filter);
906
        }
907
908
        return $this->input($this->route, $name, $default, $filter);
909
    }
910
911
    /**
912
     * 获取GET参数
913
     * @access public
914
     * @param  mixed        $name 变量名
0 ignored issues
show
Coding Style introduced by
Expected 4 spaces after parameter name; 1 found
Loading history...
915
     * @param  mixed        $default 默认值
916
     * @param  string|array $filter 过滤方法
0 ignored issues
show
Coding Style introduced by
Expected 2 spaces after parameter name; 1 found
Loading history...
917
     * @return mixed
918
     */
919
    public function get($name = '', $default = null, $filter = '')
920
    {
921
        if (is_array($name)) {
922
            return $this->only($name, $this->get, $filter);
923
        }
924
925
        return $this->input($this->get, $name, $default, $filter);
926
    }
927
928
    /**
929
     * 获取中间件传递的参数
930
     * @access public
931
     * @param  mixed $name 变量名
0 ignored issues
show
Coding Style introduced by
Expected 4 spaces after parameter name; 1 found
Loading history...
932
     * @param  mixed $default 默认值
933
     * @return mixed
934
     */
935 3
    public function middleware($name, $default = null)
936
    {
937 3
        return $this->middleware[$name] ?? $default;
938
    }
939
940
    /**
941
     * 获取POST参数
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
     * @param  string|array $filter 过滤方法
0 ignored issues
show
Coding Style introduced by
Expected 2 spaces after parameter name; 1 found
Loading history...
946
     * @return mixed
947
     */
948
    public function post($name = '', $default = null, $filter = '')
949
    {
950
        if (is_array($name)) {
951
            return $this->only($name, $this->post, $filter);
952
        }
953
954
        return $this->input($this->post, $name, $default, $filter);
955
    }
956
957
    /**
958
     * 获取PUT参数
959
     * @access public
960
     * @param  mixed        $name 变量名
0 ignored issues
show
Coding Style introduced by
Expected 4 spaces after parameter name; 1 found
Loading history...
961
     * @param  mixed        $default 默认值
962
     * @param  string|array $filter 过滤方法
0 ignored issues
show
Coding Style introduced by
Expected 2 spaces after parameter name; 1 found
Loading history...
963
     * @return mixed
964
     */
965
    public function put($name = '', $default = null, $filter = '')
966
    {
967
        if (is_array($name)) {
968
            return $this->only($name, $this->put, $filter);
969
        }
970
971
        return $this->input($this->put, $name, $default, $filter);
972
    }
973
974 8
    protected function getInputData($content)
0 ignored issues
show
Coding Style introduced by
Missing doc comment for function getInputData()
Loading history...
975
    {
976 8
        if ($this->isJson()) {
977
            return (array) json_decode($content, true);
978 8
        } elseif (strpos($content, '=')) {
979
            parse_str($content, $data);
980
            return $data;
981
        }
982
983 8
        return [];
984
    }
985
986
    /**
987
     * 设置获取DELETE参数
988
     * @access public
989
     * @param  mixed        $name 变量名
0 ignored issues
show
Coding Style introduced by
Expected 4 spaces after parameter name; 1 found
Loading history...
990
     * @param  mixed        $default 默认值
991
     * @param  string|array $filter 过滤方法
0 ignored issues
show
Coding Style introduced by
Expected 2 spaces after parameter name; 1 found
Loading history...
992
     * @return mixed
993
     */
994
    public function delete($name = '', $default = null, $filter = '')
995
    {
996
        return $this->put($name, $default, $filter);
997
    }
998
999
    /**
1000
     * 设置获取PATCH参数
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 patch($name = '', $default = null, $filter = '')
1008
    {
1009
        return $this->put($name, $default, $filter);
1010
    }
1011
1012
    /**
1013
     * 获取request变量
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 request($name = '', $default = null, $filter = '')
1021
    {
1022
        if (is_array($name)) {
1023
            return $this->only($name, $this->request, $filter);
1024
        }
1025
1026
        return $this->input($this->request, $name, $default, $filter);
1027
    }
1028
1029
    /**
1030
     * 获取环境变量
1031
     * @access public
1032
     * @param  string $name 数据名称
0 ignored issues
show
Coding Style introduced by
Expected 4 spaces after parameter name; 1 found
Loading history...
1033
     * @param  string $default 默认值
1034
     * @return mixed
1035
     */
1036
    public function env(string $name = '', string $default = null)
1037
    {
1038
        if (empty($name)) {
1039
            return $this->env->get();
1040
        } else {
1041
            $name = strtoupper($name);
1042
        }
1043
1044
        return $this->env->get($name, $default);
1045
    }
1046
1047
    /**
1048
     * 获取session数据
1049
     * @access public
1050
     * @param  string $name 数据名称
0 ignored issues
show
Coding Style introduced by
Expected 4 spaces after parameter name; 1 found
Loading history...
1051
     * @param  string $default 默认值
1052
     * @return mixed
1053
     */
1054
    public function session(string $name = '', $default = null)
1055
    {
1056
        if ('' === $name) {
1057
            return $this->session->get();
1058
        }
1059
1060
        return $this->getData($this->session->get(), $name, $default);
1061
    }
1062
1063
    /**
1064
     * 获取cookie参数
1065
     * @access public
1066
     * @param  mixed        $name 数据名称
0 ignored issues
show
Coding Style introduced by
Expected 4 spaces after parameter name; 1 found
Loading history...
1067
     * @param  string       $default 默认值
1068
     * @param  string|array $filter 过滤方法
0 ignored issues
show
Coding Style introduced by
Expected 2 spaces after parameter name; 1 found
Loading history...
1069
     * @return mixed
1070
     */
1071
    public function cookie(string $name = '', $default = null, $filter = '')
1072
    {
1073
        if (!empty($name)) {
1074
            $data = $this->getData($this->cookie, $name, $default);
1075
        } else {
1076
            $data = $this->cookie;
1077
        }
1078
1079
        // 解析过滤器
1080
        $filter = $this->getFilter($filter, $default);
1081
1082
        if (is_array($data)) {
1083
            array_walk_recursive($data, [$this, 'filterValue'], $filter);
1084
            reset($data);
1085
        } else {
1086
            $this->filterValue($data, $name, $filter);
1087
        }
1088
1089
        return $data;
1090
    }
1091
1092
    /**
1093
     * 获取server参数
1094
     * @access public
1095
     * @param  string $name 数据名称
0 ignored issues
show
Coding Style introduced by
Expected 4 spaces after parameter name; 1 found
Loading history...
1096
     * @param  string $default 默认值
1097
     * @return mixed
1098
     */
1099 8
    public function server(string $name = '', string $default = '')
1100
    {
1101 8
        if (empty($name)) {
1102
            return $this->server;
1103
        } else {
1104 8
            $name = strtoupper($name);
1105
        }
1106
1107 8
        return $this->server[$name] ?? $default;
1108
    }
1109
1110
    /**
1111
     * 获取上传的文件信息
1112
     * @access public
1113
     * @param  string $name 名称
1114
     * @return null|array|\think\File
1115
     */
1116
    public function file(string $name = '')
1117
    {
1118
        $files = $this->file;
1119
        if (!empty($files)) {
1120
1121
            if (strpos($name, '.')) {
1122
                list($name, $sub) = explode('.', $name);
1123
            }
1124
1125
            // 处理上传文件
1126
            $array = $this->dealUploadFile($files, $name);
1127
1128
            if ('' === $name) {
1129
                // 获取全部文件
1130
                return $array;
1131
            } elseif (isset($sub) && isset($array[$name][$sub])) {
1132
                return $array[$name][$sub];
1133
            } elseif (isset($array[$name])) {
1134
                return $array[$name];
1135
            }
1136
        }
1137
1138
        return;
1139
    }
1140
1141
    protected function dealUploadFile($files, $name)
0 ignored issues
show
Coding Style introduced by
Missing doc comment for function dealUploadFile()
Loading history...
1142
    {
1143
        $array = [];
1144
        foreach ($files as $key => $file) {
1145
            if (is_array($file['name'])) {
1146
                $item  = [];
1147
                $keys  = array_keys($file);
1148
                $count = count($file['name']);
1149
1150
                for ($i = 0; $i < $count; $i++) {
1151
                    if ($file['error'][$i] > 0) {
1152
                        if ($name == $key) {
1153
                            $this->throwUploadFileError($file['error'][$i]);
1154
                        } else {
1155
                            continue;
1156
                        }
1157
                    }
1158
1159
                    $temp['key'] = $key;
1160
1161
                    foreach ($keys as $_key) {
1162
                        $temp[$_key] = $file[$_key][$i];
1163
                    }
1164
1165
                    $item[] = (new File($temp['tmp_name']))->setUploadInfo($temp);
1166
                }
1167
1168
                $array[$key] = $item;
1169
            } else {
1170
                if ($file instanceof File) {
1171
                    $array[$key] = $file;
1172
                } else {
1173
                    if ($file['error'] > 0) {
1174
                        if ($key == $name) {
1175
                            $this->throwUploadFileError($file['error']);
1176
                        } else {
1177
                            continue;
1178
                        }
1179
                    }
1180
1181
                    $array[$key] = (new File($file['tmp_name']))->setUploadInfo($file);
1182
                }
1183
            }
1184
        }
1185
1186
        return $array;
1187
    }
1188
1189
    protected function throwUploadFileError($error)
0 ignored issues
show
Coding Style introduced by
Missing doc comment for function throwUploadFileError()
Loading history...
1190
    {
1191
        static $fileUploadErrors = [
1192
            1 => 'upload File size exceeds the maximum value',
1193
            2 => 'upload File size exceeds the maximum value',
1194
            3 => 'only the portion of file is uploaded',
1195
            4 => 'no file to uploaded',
1196
            6 => 'upload temp dir not found',
1197
            7 => 'file write error',
1198
        ];
1199
1200
        $msg = $fileUploadErrors[$error];
1201
        throw new Exception($msg);
1202
    }
1203
1204
    /**
1205
     * 设置或者获取当前的Header
1206
     * @access public
1207
     * @param  string $name header名称
0 ignored issues
show
Coding Style introduced by
Expected 4 spaces after parameter name; 1 found
Loading history...
1208
     * @param  string $default 默认值
1209
     * @return string|array
1210
     */
1211
    public function header(string $name = '', string $default = null)
1212
    {
1213
        if ('' === $name) {
1214
            return $this->header;
1215
        }
1216
1217
        $name = str_replace('_', '-', strtolower($name));
1218
1219
        return $this->header[$name] ?? $default;
1220
    }
1221
1222
    /**
1223
     * 获取变量 支持过滤和默认值
1224
     * @access public
1225
     * @param  array        $data 数据源
0 ignored issues
show
Coding Style introduced by
Expected 4 spaces after parameter name; 1 found
Loading history...
1226
     * @param  string|false $name 字段名
0 ignored issues
show
Coding Style introduced by
Expected 4 spaces after parameter name; 1 found
Loading history...
1227
     * @param  mixed        $default 默认值
1228
     * @param  string|array $filter 过滤函数
0 ignored issues
show
Coding Style introduced by
Expected 2 spaces after parameter name; 1 found
Loading history...
1229
     * @return mixed
1230
     */
1231
    public function input(array $data = [], $name = '', $default = null, $filter = '')
1232
    {
1233
        if (false === $name) {
1234
            // 获取原始数据
1235
            return $data;
1236
        }
1237
1238
        $name = (string) $name;
1239
        if ('' != $name) {
1240
            // 解析name
1241
            if (strpos($name, '/')) {
1242
                list($name, $type) = explode('/', $name);
1243
            }
1244
1245
            $data = $this->getData($data, $name);
1246
1247
            if (is_null($data)) {
1248
                return $default;
1249
            }
1250
1251
            if (is_object($data)) {
1252
                return $data;
1253
            }
1254
        }
1255
1256
        $data = $this->filterData($data, $filter, $name, $default);
1257
1258
        if (isset($type) && $data !== $default) {
1259
            // 强制类型转换
1260
            $this->typeCast($data, $type);
1261
        }
1262
1263
        return $data;
1264
    }
1265
1266
    protected function filterData($data, $filter, $name, $default)
0 ignored issues
show
Coding Style introduced by
Missing doc comment for function filterData()
Loading history...
1267
    {
1268
        // 解析过滤器
1269
        $filter = $this->getFilter($filter, $default);
1270
1271
        if (is_array($data)) {
1272
            array_walk_recursive($data, [$this, 'filterValue'], $filter);
1273
            reset($data);
1274
        } else {
1275
            $this->filterValue($data, $name, $filter);
1276
        }
1277
1278
        return $data;
1279
    }
1280
1281
    /**
1282
     * 强制类型转换
1283
     * @access public
1284
     * @param  string $data
0 ignored issues
show
Coding Style introduced by
Missing parameter comment
Loading history...
1285
     * @param  string $type
0 ignored issues
show
Coding Style introduced by
Missing parameter comment
Loading history...
1286
     * @return mixed
1287
     */
1288
    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...
1289
    {
1290
        switch (strtolower($type)) {
1291
            // 数组
1292
            case 'a':
1 ignored issue
show
Coding Style introduced by
Line indented incorrectly; expected 8 spaces, found 12
Loading history...
1293
                $data = (array) $data;
1294
                break;
1295
            // 数字
1296
            case 'd':
1 ignored issue
show
Coding Style introduced by
Line indented incorrectly; expected 8 spaces, found 12
Loading history...
1297
                $data = (int) $data;
1298
                break;
1299
            // 浮点
1300
            case 'f':
1 ignored issue
show
Coding Style introduced by
Line indented incorrectly; expected 8 spaces, found 12
Loading history...
1301
                $data = (float) $data;
1302
                break;
1303
            // 布尔
1304
            case 'b':
1 ignored issue
show
Coding Style introduced by
Line indented incorrectly; expected 8 spaces, found 12
Loading history...
1305
                $data = (boolean) $data;
1306
                break;
1307
            // 字符串
1308
            case 's':
1 ignored issue
show
Coding Style introduced by
Line indented incorrectly; expected 8 spaces, found 12
Loading history...
1309
                if (is_scalar($data)) {
1 ignored issue
show
introduced by
The condition is_scalar($data) is always true.
Loading history...
Coding Style introduced by
Line indented incorrectly; expected 12 spaces, found 16
Loading history...
1310
                    $data = (string) $data;
1311
                } else {
1 ignored issue
show
Coding Style introduced by
Line indented incorrectly; expected 12 spaces, found 16
Loading history...
1312
                    throw new \InvalidArgumentException('variable type error:' . gettype($data));
1313
                }
1 ignored issue
show
Coding Style introduced by
Line indented incorrectly; expected 12 spaces, found 16
Loading history...
1314
                break;
1315
        }
1316
    }
1317
1318
    /**
1319
     * 获取数据
1320
     * @access public
1321
     * @param  array  $data 数据源
0 ignored issues
show
Coding Style introduced by
Expected 4 spaces after parameter name; 1 found
Loading history...
1322
     * @param  string $name 字段名
0 ignored issues
show
Coding Style introduced by
Expected 4 spaces after parameter name; 1 found
Loading history...
1323
     * @param  mixed  $default 默认值
1324
     * @return mixed
1325
     */
1326
    protected function getData(array $data, string $name, $default = null)
1327
    {
1328
        foreach (explode('.', $name) as $val) {
1329
            if (isset($data[$val])) {
1330
                $data = $data[$val];
1331
            } else {
1332
                return $default;
1333
            }
1334
        }
1335
1336
        return $data;
1337
    }
1338
1339
    /**
1340
     * 设置或获取当前的过滤规则
1341
     * @access public
1342
     * @param  mixed $filter 过滤规则
1343
     * @return mixed
1344
     */
1345
    public function filter($filter = null)
1346
    {
1347
        if (is_null($filter)) {
1348
            return $this->filter;
1349
        }
1350
1351
        $this->filter = $filter;
1352
1353
        return $this;
1354
    }
1355
1356
    protected function getFilter($filter, $default)
0 ignored issues
show
Coding Style introduced by
Missing doc comment for function getFilter()
Loading history...
1357
    {
1358
        if (is_null($filter)) {
1359
            $filter = [];
1360
        } else {
1361
            $filter = $filter ?: $this->filter;
1362
            if (is_string($filter) && false === strpos($filter, '/')) {
1363
                $filter = explode(',', $filter);
1364
            } else {
1365
                $filter = (array) $filter;
1366
            }
1367
        }
1368
1369
        $filter[] = $default;
1370
1371
        return $filter;
1372
    }
1373
1374
    /**
1375
     * 递归过滤给定的值
1376
     * @access public
1377
     * @param  mixed $value 键值
0 ignored issues
show
Coding Style introduced by
Expected 3 spaces after parameter name; 1 found
Loading history...
1378
     * @param  mixed $key 键名
0 ignored issues
show
Coding Style introduced by
Expected 5 spaces after parameter name; 1 found
Loading history...
1379
     * @param  array $filters 过滤方法+默认值
1380
     * @return mixed
1381
     */
1382
    private function filterValue(&$value, $key, $filters)
0 ignored issues
show
Coding Style introduced by
Private method name "Request::filterValue" must be prefixed with an underscore
Loading history...
1383
    {
1384
        $default = array_pop($filters);
1385
1386
        foreach ($filters as $filter) {
1387
            if (is_callable($filter)) {
1388
                // 调用函数或者方法过滤
1389
                $value = call_user_func($filter, $value);
1390
            } elseif (is_scalar($value)) {
1391
                if (false !== strpos($filter, '/')) {
1392
                    // 正则过滤
1393
                    if (!preg_match($filter, $value)) {
1394
                        // 匹配不成功返回默认值
1395
                        $value = $default;
1396
                        break;
1397
                    }
1398
                } elseif (!empty($filter)) {
1399
                    // filter函数不存在时, 则使用filter_var进行过滤
1400
                    // filter为非整形值时, 调用filter_id取得过滤id
1401
                    $value = filter_var($value, is_int($filter) ? $filter : filter_id($filter));
1402
                    if (false === $value) {
1403
                        $value = $default;
1404
                        break;
1405
                    }
1406
                }
1407
            }
1408
        }
1409
1410
        return $value;
1411
    }
1412
1413
    /**
1414
     * 是否存在某个请求参数
1415
     * @access public
1416
     * @param  string $name 变量名
0 ignored issues
show
Coding Style introduced by
Expected 7 spaces after parameter name; 1 found
Loading history...
1417
     * @param  string $type 变量类型
0 ignored issues
show
Coding Style introduced by
Expected 7 spaces after parameter name; 1 found
Loading history...
1418
     * @param  bool   $checkEmpty 是否检测空值
1419
     * @return bool
1420
     */
1421
    public function has(string $name, string $type = 'param', bool $checkEmpty = false): bool
1422
    {
1423
        if (!in_array($type, ['param', 'get', 'post', 'put', 'patch', 'route', 'delete', 'cookie', 'session', 'env', 'request', 'server', 'header', 'file'])) {
1424
            return false;
1425
        }
1426
1427
        $param = empty($this->$type) ? $this->$type() : $this->$type;
1428
1429
        if (is_object($param)) {
1430
            return $param->has($name);
1431
        }
1432
1433
        // 按.拆分成多维数组进行判断
1434
        foreach (explode('.', $name) as $val) {
1435
            if (isset($param[$val])) {
1436
                $param = $param[$val];
1437
            } else {
1438
                return false;
1439
            }
1440
        }
1441
1442
        return ($checkEmpty && '' === $param) ? false : true;
1443
    }
1444
1445
    /**
1446
     * 获取指定的参数
1447
     * @access public
1448
     * @param  array        $name 变量名
0 ignored issues
show
Coding Style introduced by
Expected 3 spaces after parameter name; 1 found
Loading history...
1449
     * @param  mixed        $data 数据或者变量类型
0 ignored issues
show
Coding Style introduced by
Expected 3 spaces after parameter name; 1 found
Loading history...
1450
     * @param  string|array $filter 过滤方法
1451
     * @return array
1452
     */
1453
    public function only(array $name, $data = 'param', $filter = ''): array
1454
    {
1455
        $data = is_array($data) ? $data : $this->$data();
1456
1457
        $item = [];
1458
        foreach ($name as $key => $val) {
1459
1460
            if (is_int($key)) {
1461
                $default = null;
1462
                $key     = $val;
1463
                if (!isset($data[$key])) {
1464
                    continue;
1465
                }
1466
            } else {
1467
                $default = $val;
1468
            }
1469
1470
            $item[$key] = $this->filterData($data[$key] ?? $default, $filter, $key, $default);
1471
        }
1472
1473
        return $item;
1474
    }
1475
1476
    /**
1477
     * 排除指定参数获取
1478
     * @access public
1479
     * @param  array  $name 变量名
1480
     * @param  string $type 变量类型
1481
     * @return mixed
1482
     */
1483
    public function except(array $name, string $type = 'param'): array
1484
    {
1485
        $param = $this->$type();
1486
1487
        foreach ($name as $key) {
1488
            if (isset($param[$key])) {
1489
                unset($param[$key]);
1490
            }
1491
        }
1492
1493
        return $param;
1494
    }
1495
1496
    /**
1497
     * 当前是否ssl
1498
     * @access public
1499
     * @return bool
1500
     */
1501
    public function isSsl(): bool
1502
    {
1503
        if ($this->server('HTTPS') && ('1' == $this->server('HTTPS') || 'on' == strtolower($this->server('HTTPS')))) {
1504
            return true;
1505
        } elseif ('https' == $this->server('REQUEST_SCHEME')) {
1506
            return true;
1507
        } elseif ('443' == $this->server('SERVER_PORT')) {
1508
            return true;
1509
        } elseif ('https' == $this->server('HTTP_X_FORWARDED_PROTO')) {
1510
            return true;
1511
        } elseif ($this->httpsAgentName && $this->server($this->httpsAgentName)) {
1512
            return true;
1513
        }
1514
1515
        return false;
1516
    }
1517
1518
    /**
1519
     * 当前是否JSON请求
1520
     * @access public
1521
     * @return bool
1522
     */
1523 8
    public function isJson(): bool
1524
    {
1525 8
        $contentType = $this->contentType();
1526 8
        $acceptType  = $this->type();
1527
1528 8
        return false !== strpos($contentType, 'json') || false !== strpos($acceptType, 'json');
1529
    }
1530
1531
    /**
1532
     * 当前是否Ajax请求
1533
     * @access public
1534
     * @param  bool $ajax true 获取原始ajax请求
1535
     * @return bool
1536
     */
1537
    public function isAjax(bool $ajax = false): bool
1538
    {
1539
        $value  = $this->server('HTTP_X_REQUESTED_WITH');
1540
        $result = $value && 'xmlhttprequest' == strtolower($value) ? true : false;
1541
1542
        if (true === $ajax) {
1543
            return $result;
1544
        }
1545
1546
        return $this->param($this->varAjax) ? true : $result;
1547
    }
1548
1549
    /**
1550
     * 当前是否Pjax请求
1551
     * @access public
1552
     * @param  bool $pjax true 获取原始pjax请求
1553
     * @return bool
1554
     */
1555
    public function isPjax(bool $pjax = false): bool
1556
    {
1557
        $result = !is_null($this->server('HTTP_X_PJAX')) ? true : false;
1558
1559
        if (true === $pjax) {
1560
            return $result;
1561
        }
1562
1563
        return $this->param($this->varPjax) ? true : $result;
1564
    }
1565
1566
    /**
1567
     * 获取客户端IP地址
1568
     * @access public
1569
     * @return string
1570
     */
1571
    public function ip(): string
1572
    {
1573
        if (!empty($this->realIP)) {
1574
            return $this->realIP;
1575
        }
1576
1577
        $this->realIP = $this->server('REMOTE_ADDR', '');
1578
1579
        // 如果指定了前端代理服务器IP以及其会发送的IP头
1580
        // 则尝试获取前端代理服务器发送过来的真实IP
1581
        $proxyIp       = $this->proxyServerIp;
1582
        $proxyIpHeader = $this->proxyServerIpHeader;
1583
1584
        if (count($proxyIp) > 0 && count($proxyIpHeader) > 0) {
1585
            // 从指定的HTTP头中依次尝试获取IP地址
1586
            // 直到获取到一个合法的IP地址
1587
            foreach ($proxyIpHeader as $header) {
1588
                $tempIP = $this->server($header);
1589
1590
                if (empty($tempIP)) {
1591
                    continue;
1592
                }
1593
1594
                $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

1594
                $tempIP = trim(explode(',', /** @scrutinizer ignore-type */ $tempIP)[0]);
Loading history...
1595
1596
                if (!$this->isValidIP($tempIP)) {
1597
                    $tempIP = null;
1598
                } else {
1599
                    break;
1600
                }
1601
            }
1602
1603
            // tempIP不为空,说明获取到了一个IP地址
1604
            // 这时我们检查 REMOTE_ADDR 是不是指定的前端代理服务器之一
1605
            // 如果是的话说明该 IP头 是由前端代理服务器设置的
1606
            // 否则则是伪装的
1607
            if ($tempIP) {
0 ignored issues
show
Comprehensibility Best Practice introduced by
The variable $tempIP seems to be defined by a foreach iteration on line 1587. Are you sure the iterator is never empty, otherwise this variable is not defined?
Loading history...
1608
                $realIPBin = $this->ip2bin($this->realIP);
1609
1610
                foreach ($proxyIp as $ip) {
1611
                    $serverIPElements = explode('/', $ip);
1612
                    $serverIP         = $serverIPElements[0];
1613
                    $serverIPPrefix   = $serverIPElements[1] ?? 128;
1614
                    $serverIPBin      = $this->ip2bin($serverIP);
1615
1616
                    // IP类型不符
1617
                    if (strlen($realIPBin) !== strlen($serverIPBin)) {
1618
                        continue;
1619
                    }
1620
1621
                    if (strncmp($realIPBin, $serverIPBin, (int) $serverIPPrefix) === 0) {
1622
                        $this->realIP = $tempIP;
1623
                        break;
1624
                    }
1625
                }
1626
            }
1627
        }
1628
1629
        if (!$this->isValidIP($this->realIP)) {
1630
            $this->realIP = '0.0.0.0';
1631
        }
1632
1633
        return $this->realIP;
1634
    }
1635
1636
    /**
1637
     * 检测是否是合法的IP地址
1638
     *
1639
     * @param string $ip   IP地址
1640
     * @param string $type IP地址类型 (ipv4, ipv6)
1641
     *
1642
     * @return boolean
1643
     */
1644
    public function isValidIP(string $ip, string $type = ''): bool
1645
    {
1646
        switch (strtolower($type)) {
1647
            case 'ipv4':
1 ignored issue
show
Coding Style introduced by
Line indented incorrectly; expected 8 spaces, found 12
Loading history...
1648
                $flag = FILTER_FLAG_IPV4;
1649
                break;
1650
            case 'ipv6':
1 ignored issue
show
Coding Style introduced by
Line indented incorrectly; expected 8 spaces, found 12
Loading history...
1651
                $flag = FILTER_FLAG_IPV6;
1652
                break;
1653
            default:
1 ignored issue
show
Coding Style introduced by
Line indented incorrectly; expected 8 spaces, found 12
Loading history...
1654
                $flag = null;
1655
                break;
1656
        }
1657
1658
        return boolval(filter_var($ip, FILTER_VALIDATE_IP, $flag));
1659
    }
1660
1661
    /**
1662
     * 将IP地址转换为二进制字符串
1663
     *
1664
     * @param string $ip
0 ignored issues
show
Coding Style introduced by
Missing parameter comment
Loading history...
1665
     *
1666
     * @return string
1667
     */
1668
    public function ip2bin(string $ip): string
1669
    {
1670
        if ($this->isValidIP($ip, 'ipv6')) {
1671
            $IPHex = str_split(bin2hex(inet_pton($ip)), 4);
1672
            foreach ($IPHex as $key => $value) {
1673
                $IPHex[$key] = intval($value, 16);
1674
            }
1675
            $IPBin = vsprintf('%016b%016b%016b%016b%016b%016b%016b%016b', $IPHex);
1676
        } else {
1677
            $IPHex = str_split(bin2hex(inet_pton($ip)), 2);
1678
            foreach ($IPHex as $key => $value) {
1679
                $IPHex[$key] = intval($value, 16);
1680
            }
1681
            $IPBin = vsprintf('%08b%08b%08b%08b', $IPHex);
1682
        }
1683
1684
        return $IPBin;
1685
    }
1686
1687
    /**
1688
     * 检测是否使用手机访问
1689
     * @access public
1690
     * @return bool
1691
     */
1692
    public function isMobile(): bool
1693
    {
1694
        if ($this->server('HTTP_VIA') && stristr($this->server('HTTP_VIA'), "wap")) {
1695
            return true;
1696
        } elseif ($this->server('HTTP_ACCEPT') && strpos(strtoupper($this->server('HTTP_ACCEPT')), "VND.WAP.WML")) {
1697
            return true;
1698
        } elseif ($this->server('HTTP_X_WAP_PROFILE') || $this->server('HTTP_PROFILE')) {
1699
            return true;
1700
        } 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'))) {
1701
            return true;
1702
        }
1703
1704
        return false;
1705
    }
1706
1707
    /**
1708
     * 当前URL地址中的scheme参数
1709
     * @access public
1710
     * @return string
1711
     */
1712
    public function scheme(): string
1713
    {
1714
        return $this->isSsl() ? 'https' : 'http';
1715
    }
1716
1717
    /**
1718
     * 当前请求URL地址中的query参数
1719
     * @access public
1720
     * @return string
1721
     */
1722
    public function query(): string
1723
    {
1724
        return $this->server('QUERY_STRING', '');
1725
    }
1726
1727
    /**
1728
     * 设置当前请求的host(包含端口)
1729
     * @access public
1730
     * @param  string $host 主机名(含端口)
1731
     * @return $this
1732
     */
1733
    public function setHost(string $host)
1734
    {
1735
        $this->host = $host;
1736
1737
        return $this;
1738
    }
1739
1740
    /**
1741
     * 当前请求的host
1742
     * @access public
1743
     * @param bool $strict  true 仅仅获取HOST
1 ignored issue
show
Coding Style introduced by
Expected 1 spaces after parameter name; 2 found
Loading history...
Coding Style introduced by
Tag value for @param tag indented incorrectly; expected 2 spaces but found 1
Loading history...
1744
     * @return string
1745
     */
1746 3
    public function host(bool $strict = false): string
1747
    {
1748 3
        if ($this->host) {
1749
            $host = $this->host;
1750
        } else {
1751 3
            $host = strval($this->server('HTTP_X_REAL_HOST') ?: $this->server('HTTP_HOST'));
1752
        }
1753
1754 3
        return true === $strict && strpos($host, ':') ? strstr($host, ':', true) : $host;
1755
    }
1756
1757
    /**
1758
     * 当前请求URL地址中的port参数
1759
     * @access public
1760
     * @return string
1761
     */
1762
    public function port(): string
1763
    {
1764
        return $this->server('SERVER_PORT', '');
1765
    }
1766
1767
    /**
1768
     * 当前请求 SERVER_PROTOCOL
1769
     * @access public
1770
     * @return string
1771
     */
1772
    public function protocol(): string
1773
    {
1774
        return $this->server('SERVER_PROTOCOL', '');
1775
    }
1776
1777
    /**
1778
     * 当前请求 REMOTE_PORT
1779
     * @access public
1780
     * @return string
1781
     */
1782
    public function remotePort(): string
1783
    {
1784
        return $this->server('REMOTE_PORT', '');
1785
    }
1786
1787
    /**
1788
     * 当前请求 HTTP_CONTENT_TYPE
1789
     * @access public
1790
     * @return string
1791
     */
1792 8
    public function contentType(): string
1793
    {
1794 8
        $contentType = $this->server('CONTENT_TYPE');
1795
1796 8
        if ($contentType) {
1797
            if (strpos($contentType, ';')) {
1798
                list($type) = explode(';', $contentType);
1799
            } else {
1800
                $type = $contentType;
1801
            }
1802
            return trim($type);
1803
        }
1804
1805 8
        return '';
1806
    }
1807
1808
    /**
1809
     * 设置或者获取当前请求的调度信息
1810
     * @access public
1811
     * @param  Dispatch  $dispatch 调度信息
1812
     * @return Dispatch
1813
     */
1814
    public function dispatch(Dispatch $dispatch = null)
1815
    {
1816
        if (!is_null($dispatch)) {
1817
            $this->dispatch = $dispatch;
1818
        }
1819
1820
        return $this->dispatch;
1821
    }
1822
1823
    /**
1824
     * 获取当前请求的安全Key
1825
     * @access public
1826
     * @return string
1827
     */
1828
    public function secureKey(): string
1829
    {
1830
        if (is_null($this->secureKey)) {
0 ignored issues
show
introduced by
The condition is_null($this->secureKey) is always false.
Loading history...
1831
            $this->secureKey = uniqid('', true);
1832
        }
1833
1834
        return $this->secureKey;
1835
    }
1836
1837
    /**
1838
     * 设置当前的应用名
1839
     * @access public
1840
     * @param  string $app 应用名
1841
     * @return $this
1842
     */
1843 5
    public function setApp(string $app)
1844
    {
1845 5
        $this->app = $app;
1846 5
        return $this;
1847
    }
1848
1849
    /**
1850
     * 设置当前的控制器名
1851
     * @access public
1852
     * @param  string $controller 控制器名
1853
     * @return $this
1854
     */
1855
    public function setController(string $controller)
1856
    {
1857
        $this->controller = $controller;
1858
        return $this;
1859
    }
1860
1861
    /**
1862
     * 设置当前的操作名
1863
     * @access public
1864
     * @param  string $action 操作名
1865
     * @return $this
1866
     */
1867
    public function setAction(string $action)
1868
    {
1869
        $this->action = $action;
1870
        return $this;
1871
    }
1872
1873
    /**
1874
     * 获取当前的应用名
1875
     * @access public
1876
     * @return string
1877
     */
1878
    public function app(): string
1879
    {
1880
        return $this->app ?: '';
1881
    }
1882
1883
    /**
1884
     * 获取当前的控制器名
1885
     * @access public
1886
     * @param  bool $convert 转换为小写
1887
     * @return string
1888
     */
1889
    public function controller(bool $convert = false): string
1890
    {
1891
        $name = $this->controller ?: '';
1892
        return $convert ? strtolower($name) : $name;
1893
    }
1894
1895
    /**
1896
     * 获取当前的操作名
1897
     * @access public
1898
     * @param  bool $convert 转换为小写
1899
     * @return string
1900
     */
1901
    public function action(bool $convert = false): string
1902
    {
1903
        $name = $this->action ?: '';
1904
        return $convert ? strtolower($name) : $name;
1905
    }
1906
1907
    /**
1908
     * 设置或者获取当前请求的content
1909
     * @access public
1910
     * @return string
1911
     */
1912
    public function getContent(): string
1913
    {
1914
        if (is_null($this->content)) {
0 ignored issues
show
introduced by
The condition is_null($this->content) is always false.
Loading history...
1915
            $this->content = $this->input;
1916
        }
1917
1918
        return $this->content;
1919
    }
1920
1921
    /**
1922
     * 获取当前请求的php://input
1923
     * @access public
1924
     * @return string
1925
     */
1926
    public function getInput(): string
1927
    {
1928
        return $this->input;
1929
    }
1930
1931
    /**
1932
     * 生成请求令牌
1933
     * @access public
1934
     * @param  string $name 令牌名称
1935
     * @param  mixed  $type 令牌生成方法
1936
     * @return string
1937
     */
1938
    public function buildToken(string $name = '__token__', $type = 'md5'): string
1939
    {
1940
        $type  = is_callable($type) ? $type : 'md5';
1941
        $token = call_user_func($type, $this->server('REQUEST_TIME_FLOAT'));
1942
1943
        $this->session->set($name, $token);
1944
1945
        return $token;
1946
    }
1947
1948
    /**
0 ignored issues
show
Coding Style introduced by
Parameter $token should have a doc-comment as per coding-style.
Loading history...
1949
     * 检查请求令牌
1950
     * @access public
1951
     * @param  string $name 令牌名称
0 ignored issues
show
Coding Style introduced by
Doc comment for parameter $name does not match actual variable name $token
Loading history...
1952
     * @param  array  $data 表单数据
1953
     * @return bool
1954
     */
1955
    public function checkToken(string $token = '__token__', array $data = []): bool
1956
    {
1957
        if (in_array($this->method(), ['GET', 'HEAD', 'OPTIONS'], true)) {
1958
            return true;
1959
        }
1960
1961
        if (!$this->session->has($token)) {
1962
            // 令牌数据无效
1963
            return false;
1964
        }
1965
1966
        // Header验证
1967
        if ($this->header('X-CSRF-TOKEN') && $this->session->get($token) === $this->header('X-CSRF-TOKEN')) {
1968
            // 防止重复提交
1969
            $this->session->delete($token); // 验证完成销毁session
1970
            return true;
1971
        }
1972
1973
        if (empty($data)) {
1974
            $data = $this->post();
1975
        }
1976
1977
        // 令牌验证
1978
        if (isset($data[$token]) && $this->session->get($token) === $data[$token]) {
1979
            // 防止重复提交
1980
            $this->session->delete($token); // 验证完成销毁session
1981
            return true;
1982
        }
1983
1984
        // 开启TOKEN重置
1985
        $this->session->delete($token);
1986
        return false;
1987
    }
1988
1989
    /**
1990
     * 设置在中间件传递的数据
1991
     * @access public
1992
     * @param  array $middleware 数据
1993
     * @return $this
1994
     */
1995
    public function withMiddleware(array $middleware)
1996
    {
1997
        $this->middleware = array_merge($this->middleware, $middleware);
1998
        return $this;
1999
    }
2000
2001
    /**
2002
     * 设置GET数据
2003
     * @access public
2004
     * @param  array $get 数据
2005
     * @return $this
2006
     */
2007
    public function withGet(array $get)
2008
    {
2009
        $this->get = $get;
2010
        return $this;
2011
    }
2012
2013
    /**
2014
     * 设置POST数据
2015
     * @access public
2016
     * @param  array $post 数据
2017
     * @return $this
2018
     */
2019
    public function withPost(array $post)
2020
    {
2021
        $this->post = $post;
2022
        return $this;
2023
    }
2024
2025
    /**
2026
     * 设置COOKIE数据
2027
     * @access public
2028
     * @param array $cookie 数据
1 ignored issue
show
Coding Style introduced by
Tag value for @param tag indented incorrectly; expected 2 spaces but found 1
Loading history...
2029
     * @return $this
2030
     */
2031
    public function withCookie(array $cookie)
2032
    {
2033
        $this->cookie = $cookie;
2034
        return $this;
2035
    }
2036
2037
    /**
2038
     * 设置SESSION数据
2039
     * @access public
2040
     * @param Session $session 数据
1 ignored issue
show
Coding Style introduced by
Tag value for @param tag indented incorrectly; expected 2 spaces but found 1
Loading history...
2041
     * @return $this
2042
     */
2043
    public function withSession(Session $session)
2044
    {
2045
        $this->session = $session;
2046
        return $this;
2047
    }
2048
2049
    /**
2050
     * 设置SERVER数据
2051
     * @access public
2052
     * @param  array $server 数据
2053
     * @return $this
2054
     */
2055
    public function withServer(array $server)
2056
    {
2057
        $this->server = array_change_key_case($server, CASE_UPPER);
2058
        return $this;
2059
    }
2060
2061
    /**
2062
     * 设置HEADER数据
2063
     * @access public
2064
     * @param  array $header 数据
2065
     * @return $this
2066
     */
2067
    public function withHeader(array $header)
2068
    {
2069
        $this->header = array_change_key_case($header);
2070
        return $this;
2071
    }
2072
2073
    /**
2074
     * 设置ENV数据
2075
     * @access public
2076
     * @param Env $env 数据
1 ignored issue
show
Coding Style introduced by
Tag value for @param tag indented incorrectly; expected 2 spaces but found 1
Loading history...
2077
     * @return $this
2078
     */
2079
    public function withEnv(Env $env)
2080
    {
2081
        $this->env = $env;
2082
        return $this;
2083
    }
2084
2085
    /**
2086
     * 设置php://input数据
2087
     * @access public
2088
     * @param  string $input RAW数据
2089
     * @return $this
2090
     */
2091
    public function withInput(string $input)
2092
    {
2093
        $this->input = $input;
2094
        return $this;
2095
    }
2096
2097
    /**
2098
     * 设置文件上传数据
2099
     * @access public
2100
     * @param  array $files 上传信息
2101
     * @return $this
2102
     */
2103
    public function withFiles(array $files)
2104
    {
2105
        $this->file = $files;
2106
        return $this;
2107
    }
2108
2109
    /**
2110
     * 设置ROUTE变量
2111
     * @access public
2112
     * @param  array $route 数据
2113
     * @return $this
2114
     */
2115
    public function withRoute(array $route)
2116
    {
2117
        $this->route = $route;
2118
        return $this;
2119
    }
2120
2121
    /**
2122
     * 设置中间传递数据
2123
     * @access public
2124
     * @param  string    $name  参数名
2125
     * @param  mixed     $value 值
2126
     */
0 ignored issues
show
Coding Style introduced by
Missing @return tag in function comment
Loading history...
2127
    public function __set(string $name, $value)
2128
    {
2129
        $this->middleware[$name] = $value;
2130
    }
2131
2132
    /**
2133
     * 获取中间传递数据的值
2134
     * @access public
2135
     * @param  string $name 名称
2136
     * @return mixed
2137
     */
2138 3
    public function __get(string $name)
2139
    {
2140 3
        return $this->middleware($name);
2141
    }
2142
2143
    /**
2144
     * 检测请求数据的值
2145
     * @access public
2146
     * @param  string $name 名称
2147
     * @return boolean
2148
     */
2149
    public function __isset(string $name): bool
2150
    {
2151
        return isset($this->param[$name]);
2152
    }
2153
}
2154