Completed
Push — 6.0 ( 5e9bb0...631ba1 )
by liu
03:40
created

Request::route()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 7
Code Lines 3

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 6

Importance

Changes 0
Metric Value
cc 2
eloc 3
nc 2
nop 3
dl 0
loc 7
ccs 0
cts 4
cp 0
crap 6
rs 10
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 ($this->server('REQUEST_URI')) {
628
                $pathinfo = strpos($this->server('REQUEST_URI'), '?') ? strstr($this->server('REQUEST_URI'), '?', true) : $this->server('REQUEST_URI');
629
                if (0 === strpos($pathinfo, $this->server('SCRIPT_NAME'))) {
630
                    $pathinfo = substr($pathinfo, strlen($this->server('SCRIPT_NAME')));
631
                }
632
            } elseif (isset($_SERVER['argv'][1])) {
633
                // CLI模式下 index.php controller/action/params/...
634
                $pathinfo = $_SERVER['argv'][1];
635
            }
636
637
            // 分析PATHINFO信息
638
            if (!isset($pathinfo)) {
639
                foreach ($this->pathinfoFetch as $type) {
640
                    if ($this->server($type)) {
641
                        $pathinfo = (0 === strpos($this->server($type), $this->server('SCRIPT_NAME'))) ?
642
                        substr($this->server($type), strlen($this->server('SCRIPT_NAME'))) : $this->server($type);
643
                        break;
644
                    }
645
                }
646
            }
647
            $this->pathinfo = empty($pathinfo) || '/' == $pathinfo ? '' : ltrim($pathinfo, '/');
648
        }
649
650
        return $this->pathinfo;
651
    }
652
653
    /**
654
     * 当前URL的访问后缀
655
     * @access public
656
     * @return string
657
     */
658
    public function ext(): string
659
    {
660
        return pathinfo($this->pathinfo(), PATHINFO_EXTENSION);
661
    }
662
663
    /**
664
     * 获取当前请求的时间
665
     * @access public
666
     * @param  bool $float 是否使用浮点类型
667
     * @return integer|float
668
     */
669
    public function time(bool $float = false)
670
    {
671
        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...
672
    }
673
674
    /**
675
     * 当前请求的资源类型
676
     * @access public
677
     * @return string
678
     */
679 8
    public function type(): string
680
    {
681 8
        $accept = $this->server('HTTP_ACCEPT');
682
683 8
        if (empty($accept)) {
684 8
            return '';
685
        }
686
687
        foreach ($this->mimeType as $key => $val) {
688
            $array = explode(',', $val);
689
            foreach ($array as $k => $v) {
690
                if (stristr($accept, $v)) {
691
                    return $key;
692
                }
693
            }
694
        }
695
696
        return '';
697
    }
698
699
    /**
700
     * 设置资源类型
701
     * @access public
702
     * @param  string|array $type 资源类型名
703
     * @param  string       $val 资源类型
0 ignored issues
show
Coding Style introduced by
Expected 2 spaces after parameter name; 1 found
Loading history...
704
     * @return void
705
     */
706
    public function mimeType($type, $val = ''): void
707
    {
708
        if (is_array($type)) {
709
            $this->mimeType = array_merge($this->mimeType, $type);
710
        } else {
711
            $this->mimeType[$type] = $val;
712
        }
713
    }
714
715
    /**
716
     * 设置请求类型
717
     * @access public
718
     * @param  string $method 请求类型
719
     * @return $this
720
     */
721
    public function setMethod(string $method)
722
    {
723
        $this->method = strtoupper($method);
724
        return $this;
725
    }
726
727
    /**
728
     * 当前的请求类型
729
     * @access public
730
     * @param  bool $origin 是否获取原始请求类型
731
     * @return string
732
     */
733
    public function method(bool $origin = false): string
734
    {
735
        if ($origin) {
736
            // 获取原始请求类型
737
            return $this->server('REQUEST_METHOD') ?: 'GET';
738
        } elseif (!$this->method) {
739
            if (isset($_POST[$this->varMethod])) {
740
                $method = strtolower($_POST[$this->varMethod]);
741
                if (in_array($method, ['get', 'post', 'put', 'patch', 'delete'])) {
742
                    $this->method    = strtoupper($method);
743
                    $this->{$method} = $_POST;
744
                } else {
745
                    $this->method = 'POST';
746
                }
747
                unset($_POST[$this->varMethod]);
748
            } elseif ($this->server('HTTP_X_HTTP_METHOD_OVERRIDE')) {
749
                $this->method = strtoupper($this->server('HTTP_X_HTTP_METHOD_OVERRIDE'));
750
            } else {
751
                $this->method = $this->server('REQUEST_METHOD') ?: 'GET';
752
            }
753
        }
754
755
        return $this->method;
756
    }
757
758
    /**
759
     * 是否为GET请求
760
     * @access public
761
     * @return bool
762
     */
763
    public function isGet(): bool
764
    {
765
        return $this->method() == 'GET';
766
    }
767
768
    /**
769
     * 是否为POST请求
770
     * @access public
771
     * @return bool
772
     */
773
    public function isPost(): bool
774
    {
775
        return $this->method() == 'POST';
776
    }
777
778
    /**
779
     * 是否为PUT请求
780
     * @access public
781
     * @return bool
782
     */
783
    public function isPut(): bool
784
    {
785
        return $this->method() == 'PUT';
786
    }
787
788
    /**
789
     * 是否为DELTE请求
790
     * @access public
791
     * @return bool
792
     */
793
    public function isDelete(): bool
794
    {
795
        return $this->method() == 'DELETE';
796
    }
797
798
    /**
799
     * 是否为HEAD请求
800
     * @access public
801
     * @return bool
802
     */
803
    public function isHead(): bool
804
    {
805
        return $this->method() == 'HEAD';
806
    }
807
808
    /**
809
     * 是否为PATCH请求
810
     * @access public
811
     * @return bool
812
     */
813
    public function isPatch(): bool
814
    {
815
        return $this->method() == 'PATCH';
816
    }
817
818
    /**
819
     * 是否为OPTIONS请求
820
     * @access public
821
     * @return bool
822
     */
823
    public function isOptions(): bool
824
    {
825
        return $this->method() == 'OPTIONS';
826
    }
827
828
    /**
829
     * 是否为cli
830
     * @access public
831
     * @return bool
832
     */
833
    public function isCli(): bool
834
    {
835
        return PHP_SAPI == 'cli';
836
    }
837
838
    /**
839
     * 是否为cgi
840
     * @access public
841
     * @return bool
842
     */
843
    public function isCgi(): bool
844
    {
845
        return strpos(PHP_SAPI, 'cgi') === 0;
846
    }
847
848
    /**
849
     * 获取当前请求的参数
850
     * @access public
851
     * @param  string|array $name 变量名
0 ignored issues
show
Coding Style introduced by
Expected 4 spaces after parameter name; 1 found
Loading history...
852
     * @param  mixed        $default 默认值
853
     * @param  string|array $filter 过滤方法
0 ignored issues
show
Coding Style introduced by
Expected 2 spaces after parameter name; 1 found
Loading history...
854
     * @return mixed
855
     */
856
    public function param($name = '', $default = null, $filter = '')
857
    {
858
        if (empty($this->mergeParam)) {
859
            $method = $this->method(true);
860
861
            // 自动获取请求变量
862
            switch ($method) {
863
                case 'POST':
1 ignored issue
show
Coding Style introduced by
Line indented incorrectly; expected 12 spaces, found 16
Loading history...
864
                    $vars = $this->post(false);
865
                    break;
866
                case 'PUT':
1 ignored issue
show
Coding Style introduced by
Line indented incorrectly; expected 12 spaces, found 16
Loading history...
867
                case 'DELETE':
1 ignored issue
show
Coding Style introduced by
Line indented incorrectly; expected 12 spaces, found 16
Loading history...
868
                case 'PATCH':
1 ignored issue
show
Coding Style introduced by
Line indented incorrectly; expected 12 spaces, found 16
Loading history...
869
                    $vars = $this->put(false);
870
                    break;
871
                default:
1 ignored issue
show
Coding Style introduced by
Line indented incorrectly; expected 12 spaces, found 16
Loading history...
872
                    $vars = [];
873
            }
874
875
            // 当前请求参数和URL地址中的参数合并
876
            $this->param = array_merge($this->param, $this->get(false), $vars, $this->route(false));
877
878
            $this->mergeParam = true;
879
        }
880
881
        if (is_array($name)) {
882
            return $this->only($name, $this->param, $filter);
883
        }
884
885
        return $this->input($this->param, $name, $default, $filter);
886
    }
887
888
    /**
889
     * 设置路由变量
890
     * @access public
891
     * @param  array $route 路由变量
892
     * @return $this
893
     */
894
    public function setRoute(array $route)
895
    {
896
        $this->route = array_merge($this->route, $route);
897
        return $this;
898
    }
899
900
    /**
901
     * 获取路由参数
902
     * @access public
903
     * @param  mixed        $name 变量名
0 ignored issues
show
Coding Style introduced by
Expected 4 spaces after parameter name; 1 found
Loading history...
904
     * @param  mixed        $default 默认值
905
     * @param  string|array $filter 过滤方法
0 ignored issues
show
Coding Style introduced by
Expected 2 spaces after parameter name; 1 found
Loading history...
906
     * @return mixed
907
     */
908
    public function route($name = '', $default = null, $filter = '')
909
    {
910
        if (is_array($name)) {
911
            return $this->only($name, $this->route, $filter);
912
        }
913
914
        return $this->input($this->route, $name, $default, $filter);
915
    }
916
917
    /**
918
     * 获取GET参数
919
     * @access public
920
     * @param  mixed        $name 变量名
0 ignored issues
show
Coding Style introduced by
Expected 4 spaces after parameter name; 1 found
Loading history...
921
     * @param  mixed        $default 默认值
922
     * @param  string|array $filter 过滤方法
0 ignored issues
show
Coding Style introduced by
Expected 2 spaces after parameter name; 1 found
Loading history...
923
     * @return mixed
924
     */
925
    public function get($name = '', $default = null, $filter = '')
926
    {
927
        if (is_array($name)) {
928
            return $this->only($name, $this->get, $filter);
929
        }
930
931
        return $this->input($this->get, $name, $default, $filter);
932
    }
933
934
    /**
935
     * 获取中间件传递的参数
936
     * @access public
937
     * @param  mixed $name 变量名
0 ignored issues
show
Coding Style introduced by
Expected 4 spaces after parameter name; 1 found
Loading history...
938
     * @param  mixed $default 默认值
939
     * @return mixed
940
     */
941 3
    public function middleware($name, $default = null)
942
    {
943 3
        return $this->middleware[$name] ?? $default;
944
    }
945
946
    /**
947
     * 获取POST参数
948
     * @access public
949
     * @param  mixed        $name 变量名
0 ignored issues
show
Coding Style introduced by
Expected 4 spaces after parameter name; 1 found
Loading history...
950
     * @param  mixed        $default 默认值
951
     * @param  string|array $filter 过滤方法
0 ignored issues
show
Coding Style introduced by
Expected 2 spaces after parameter name; 1 found
Loading history...
952
     * @return mixed
953
     */
954
    public function post($name = '', $default = null, $filter = '')
955
    {
956
        if (is_array($name)) {
957
            return $this->only($name, $this->post, $filter);
958
        }
959
960
        return $this->input($this->post, $name, $default, $filter);
961
    }
962
963
    /**
964
     * 获取PUT参数
965
     * @access public
966
     * @param  mixed        $name 变量名
0 ignored issues
show
Coding Style introduced by
Expected 4 spaces after parameter name; 1 found
Loading history...
967
     * @param  mixed        $default 默认值
968
     * @param  string|array $filter 过滤方法
0 ignored issues
show
Coding Style introduced by
Expected 2 spaces after parameter name; 1 found
Loading history...
969
     * @return mixed
970
     */
971
    public function put($name = '', $default = null, $filter = '')
972
    {
973
        if (is_array($name)) {
974
            return $this->only($name, $this->put, $filter);
975
        }
976
977
        return $this->input($this->put, $name, $default, $filter);
978
    }
979
980 8
    protected function getInputData($content)
0 ignored issues
show
Coding Style introduced by
Missing doc comment for function getInputData()
Loading history...
981
    {
982 8
        if ($this->isJson()) {
983
            return (array) json_decode($content, true);
984 8
        } elseif (strpos($content, '=')) {
985
            parse_str($content, $data);
986
            return $data;
987
        }
988
989 8
        return [];
990
    }
991
992
    /**
993
     * 设置获取DELETE参数
994
     * @access public
995
     * @param  mixed        $name 变量名
0 ignored issues
show
Coding Style introduced by
Expected 4 spaces after parameter name; 1 found
Loading history...
996
     * @param  mixed        $default 默认值
997
     * @param  string|array $filter 过滤方法
0 ignored issues
show
Coding Style introduced by
Expected 2 spaces after parameter name; 1 found
Loading history...
998
     * @return mixed
999
     */
1000
    public function delete($name = '', $default = null, $filter = '')
1001
    {
1002
        return $this->put($name, $default, $filter);
1003
    }
1004
1005
    /**
1006
     * 设置获取PATCH参数
1007
     * @access public
1008
     * @param  mixed        $name 变量名
0 ignored issues
show
Coding Style introduced by
Expected 4 spaces after parameter name; 1 found
Loading history...
1009
     * @param  mixed        $default 默认值
1010
     * @param  string|array $filter 过滤方法
0 ignored issues
show
Coding Style introduced by
Expected 2 spaces after parameter name; 1 found
Loading history...
1011
     * @return mixed
1012
     */
1013
    public function patch($name = '', $default = null, $filter = '')
1014
    {
1015
        return $this->put($name, $default, $filter);
1016
    }
1017
1018
    /**
1019
     * 获取request变量
1020
     * @access public
1021
     * @param  mixed        $name 数据名称
0 ignored issues
show
Coding Style introduced by
Expected 4 spaces after parameter name; 1 found
Loading history...
1022
     * @param  mixed        $default 默认值
1023
     * @param  string|array $filter 过滤方法
0 ignored issues
show
Coding Style introduced by
Expected 2 spaces after parameter name; 1 found
Loading history...
1024
     * @return mixed
1025
     */
1026
    public function request($name = '', $default = null, $filter = '')
1027
    {
1028
        if (is_array($name)) {
1029
            return $this->only($name, $this->request, $filter);
1030
        }
1031
1032
        return $this->input($this->request, $name, $default, $filter);
1033
    }
1034
1035
    /**
1036
     * 获取环境变量
1037
     * @access public
1038
     * @param  string $name 数据名称
0 ignored issues
show
Coding Style introduced by
Expected 4 spaces after parameter name; 1 found
Loading history...
1039
     * @param  string $default 默认值
1040
     * @return mixed
1041
     */
1042
    public function env(string $name = '', string $default = null)
1043
    {
1044
        if (empty($name)) {
1045
            return $this->env->get();
1046
        } else {
1047
            $name = strtoupper($name);
1048
        }
1049
1050
        return $this->env->get($name, $default);
1051
    }
1052
1053
    /**
1054
     * 获取session数据
1055
     * @access public
1056
     * @param  string $name 数据名称
0 ignored issues
show
Coding Style introduced by
Expected 4 spaces after parameter name; 1 found
Loading history...
1057
     * @param  string $default 默认值
1058
     * @return mixed
1059
     */
1060
    public function session(string $name = '', $default = null)
1061
    {
1062
        if ('' === $name) {
1063
            return $this->session->get();
1064
        }
1065
1066
        return $this->getData($this->session->get(), $name, $default);
1067
    }
1068
1069
    /**
1070
     * 获取cookie参数
1071
     * @access public
1072
     * @param  mixed        $name 数据名称
0 ignored issues
show
Coding Style introduced by
Expected 4 spaces after parameter name; 1 found
Loading history...
1073
     * @param  string       $default 默认值
1074
     * @param  string|array $filter 过滤方法
0 ignored issues
show
Coding Style introduced by
Expected 2 spaces after parameter name; 1 found
Loading history...
1075
     * @return mixed
1076
     */
1077
    public function cookie(string $name = '', $default = null, $filter = '')
1078
    {
1079
        if (!empty($name)) {
1080
            $data = $this->getData($this->cookie, $name, $default);
1081
        } else {
1082
            $data = $this->cookie;
1083
        }
1084
1085
        // 解析过滤器
1086
        $filter = $this->getFilter($filter, $default);
1087
1088
        if (is_array($data)) {
1089
            array_walk_recursive($data, [$this, 'filterValue'], $filter);
1090
            reset($data);
1091
        } else {
1092
            $this->filterValue($data, $name, $filter);
1093
        }
1094
1095
        return $data;
1096
    }
1097
1098
    /**
1099
     * 获取server参数
1100
     * @access public
1101
     * @param  string $name 数据名称
0 ignored issues
show
Coding Style introduced by
Expected 4 spaces after parameter name; 1 found
Loading history...
1102
     * @param  string $default 默认值
1103
     * @return mixed
1104
     */
1105 8
    public function server(string $name = '', string $default = '')
1106
    {
1107 8
        if (empty($name)) {
1108
            return $this->server;
1109
        } else {
1110 8
            $name = strtoupper($name);
1111
        }
1112
1113 8
        return $this->server[$name] ?? $default;
1114
    }
1115
1116
    /**
1117
     * 获取上传的文件信息
1118
     * @access public
1119
     * @param  string $name 名称
1120
     * @return null|array|\think\File
1121
     */
1122
    public function file(string $name = '')
1123
    {
1124
        $files = $this->file;
1125
        if (!empty($files)) {
1126
1127
            if (strpos($name, '.')) {
1128
                list($name, $sub) = explode('.', $name);
1129
            }
1130
1131
            // 处理上传文件
1132
            $array = $this->dealUploadFile($files, $name);
1133
1134
            if ('' === $name) {
1135
                // 获取全部文件
1136
                return $array;
1137
            } elseif (isset($sub) && isset($array[$name][$sub])) {
1138
                return $array[$name][$sub];
1139
            } elseif (isset($array[$name])) {
1140
                return $array[$name];
1141
            }
1142
        }
1143
1144
        return;
1145
    }
1146
1147
    protected function dealUploadFile($files, $name)
0 ignored issues
show
Coding Style introduced by
Missing doc comment for function dealUploadFile()
Loading history...
1148
    {
1149
        $array = [];
1150
        foreach ($files as $key => $file) {
1151
            if (is_array($file['name'])) {
1152
                $item  = [];
1153
                $keys  = array_keys($file);
1154
                $count = count($file['name']);
1155
1156
                for ($i = 0; $i < $count; $i++) {
1157
                    if ($file['error'][$i] > 0) {
1158
                        if ($name == $key) {
1159
                            $this->throwUploadFileError($file['error'][$i]);
1160
                        } else {
1161
                            continue;
1162
                        }
1163
                    }
1164
1165
                    $temp['key'] = $key;
1166
1167
                    foreach ($keys as $_key) {
1168
                        $temp[$_key] = $file[$_key][$i];
1169
                    }
1170
1171
                    $item[] = (new File($temp['tmp_name']))->setUploadInfo($temp);
1172
                }
1173
1174
                $array[$key] = $item;
1175
            } else {
1176
                if ($file instanceof File) {
1177
                    $array[$key] = $file;
1178
                } else {
1179
                    if ($file['error'] > 0) {
1180
                        if ($key == $name) {
1181
                            $this->throwUploadFileError($file['error']);
1182
                        } else {
1183
                            continue;
1184
                        }
1185
                    }
1186
1187
                    $array[$key] = (new File($file['tmp_name']))->setUploadInfo($file);
1188
                }
1189
            }
1190
        }
1191
1192
        return $array;
1193
    }
1194
1195
    protected function throwUploadFileError($error)
0 ignored issues
show
Coding Style introduced by
Missing doc comment for function throwUploadFileError()
Loading history...
1196
    {
1197
        static $fileUploadErrors = [
1198
            1 => 'upload File size exceeds the maximum value',
1199
            2 => 'upload File size exceeds the maximum value',
1200
            3 => 'only the portion of file is uploaded',
1201
            4 => 'no file to uploaded',
1202
            6 => 'upload temp dir not found',
1203
            7 => 'file write error',
1204
        ];
1205
1206
        $msg = $fileUploadErrors[$error];
1207
        throw new Exception($msg);
1208
    }
1209
1210
    /**
1211
     * 设置或者获取当前的Header
1212
     * @access public
1213
     * @param  string $name header名称
0 ignored issues
show
Coding Style introduced by
Expected 4 spaces after parameter name; 1 found
Loading history...
1214
     * @param  string $default 默认值
1215
     * @return string|array
1216
     */
1217
    public function header(string $name = '', string $default = null)
1218
    {
1219
        if ('' === $name) {
1220
            return $this->header;
1221
        }
1222
1223
        $name = str_replace('_', '-', strtolower($name));
1224
1225
        return $this->header[$name] ?? $default;
1226
    }
1227
1228
    /**
1229
     * 获取变量 支持过滤和默认值
1230
     * @access public
1231
     * @param  array        $data 数据源
0 ignored issues
show
Coding Style introduced by
Expected 4 spaces after parameter name; 1 found
Loading history...
1232
     * @param  string|false $name 字段名
0 ignored issues
show
Coding Style introduced by
Expected 4 spaces after parameter name; 1 found
Loading history...
1233
     * @param  mixed        $default 默认值
1234
     * @param  string|array $filter 过滤函数
0 ignored issues
show
Coding Style introduced by
Expected 2 spaces after parameter name; 1 found
Loading history...
1235
     * @return mixed
1236
     */
1237
    public function input(array $data = [], $name = '', $default = null, $filter = '')
1238
    {
1239
        if (false === $name) {
1240
            // 获取原始数据
1241
            return $data;
1242
        }
1243
1244
        $name = (string) $name;
1245
        if ('' != $name) {
1246
            // 解析name
1247
            if (strpos($name, '/')) {
1248
                list($name, $type) = explode('/', $name);
1249
            }
1250
1251
            $data = $this->getData($data, $name);
1252
1253
            if (is_null($data)) {
1254
                return $default;
1255
            }
1256
1257
            if (is_object($data)) {
1258
                return $data;
1259
            }
1260
        }
1261
1262
        $data = $this->filterData($data, $filter, $name, $default);
1263
1264
        if (isset($type) && $data !== $default) {
1265
            // 强制类型转换
1266
            $this->typeCast($data, $type);
1267
        }
1268
1269
        return $data;
1270
    }
1271
1272
    protected function filterData($data, $filter, $name, $default)
0 ignored issues
show
Coding Style introduced by
Missing doc comment for function filterData()
Loading history...
1273
    {
1274
        // 解析过滤器
1275
        $filter = $this->getFilter($filter, $default);
1276
1277
        if (is_array($data)) {
1278
            array_walk_recursive($data, [$this, 'filterValue'], $filter);
1279
            reset($data);
1280
        } else {
1281
            $this->filterValue($data, $name, $filter);
1282
        }
1283
1284
        return $data;
1285
    }
1286
1287
    /**
1288
     * 强制类型转换
1289
     * @access public
1290
     * @param  string $data
0 ignored issues
show
Coding Style introduced by
Missing parameter comment
Loading history...
1291
     * @param  string $type
0 ignored issues
show
Coding Style introduced by
Missing parameter comment
Loading history...
1292
     * @return mixed
1293
     */
1294
    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...
1295
    {
1296
        switch (strtolower($type)) {
1297
            // 数组
1298
            case 'a':
1 ignored issue
show
Coding Style introduced by
Line indented incorrectly; expected 8 spaces, found 12
Loading history...
1299
                $data = (array) $data;
1300
                break;
1301
            // 数字
1302
            case 'd':
1 ignored issue
show
Coding Style introduced by
Line indented incorrectly; expected 8 spaces, found 12
Loading history...
1303
                $data = (int) $data;
1304
                break;
1305
            // 浮点
1306
            case 'f':
1 ignored issue
show
Coding Style introduced by
Line indented incorrectly; expected 8 spaces, found 12
Loading history...
1307
                $data = (float) $data;
1308
                break;
1309
            // 布尔
1310
            case 'b':
1 ignored issue
show
Coding Style introduced by
Line indented incorrectly; expected 8 spaces, found 12
Loading history...
1311
                $data = (boolean) $data;
1312
                break;
1313
            // 字符串
1314
            case 's':
1 ignored issue
show
Coding Style introduced by
Line indented incorrectly; expected 8 spaces, found 12
Loading history...
1315
                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...
1316
                    $data = (string) $data;
1317
                } else {
1 ignored issue
show
Coding Style introduced by
Line indented incorrectly; expected 12 spaces, found 16
Loading history...
1318
                    throw new \InvalidArgumentException('variable type error:' . gettype($data));
1319
                }
1 ignored issue
show
Coding Style introduced by
Line indented incorrectly; expected 12 spaces, found 16
Loading history...
1320
                break;
1321
        }
1322
    }
1323
1324
    /**
1325
     * 获取数据
1326
     * @access public
1327
     * @param  array  $data 数据源
0 ignored issues
show
Coding Style introduced by
Expected 4 spaces after parameter name; 1 found
Loading history...
1328
     * @param  string $name 字段名
0 ignored issues
show
Coding Style introduced by
Expected 4 spaces after parameter name; 1 found
Loading history...
1329
     * @param  mixed  $default 默认值
1330
     * @return mixed
1331
     */
1332
    protected function getData(array $data, string $name, $default = null)
1333
    {
1334
        foreach (explode('.', $name) as $val) {
1335
            if (isset($data[$val])) {
1336
                $data = $data[$val];
1337
            } else {
1338
                return $default;
1339
            }
1340
        }
1341
1342
        return $data;
1343
    }
1344
1345
    /**
1346
     * 设置或获取当前的过滤规则
1347
     * @access public
1348
     * @param  mixed $filter 过滤规则
1349
     * @return mixed
1350
     */
1351
    public function filter($filter = null)
1352
    {
1353
        if (is_null($filter)) {
1354
            return $this->filter;
1355
        }
1356
1357
        $this->filter = $filter;
1358
1359
        return $this;
1360
    }
1361
1362
    protected function getFilter($filter, $default)
0 ignored issues
show
Coding Style introduced by
Missing doc comment for function getFilter()
Loading history...
1363
    {
1364
        if (is_null($filter)) {
1365
            $filter = [];
1366
        } else {
1367
            $filter = $filter ?: $this->filter;
1368
            if (is_string($filter) && false === strpos($filter, '/')) {
1369
                $filter = explode(',', $filter);
1370
            } else {
1371
                $filter = (array) $filter;
1372
            }
1373
        }
1374
1375
        $filter[] = $default;
1376
1377
        return $filter;
1378
    }
1379
1380
    /**
1381
     * 递归过滤给定的值
1382
     * @access public
1383
     * @param  mixed $value 键值
0 ignored issues
show
Coding Style introduced by
Expected 3 spaces after parameter name; 1 found
Loading history...
1384
     * @param  mixed $key 键名
0 ignored issues
show
Coding Style introduced by
Expected 5 spaces after parameter name; 1 found
Loading history...
1385
     * @param  array $filters 过滤方法+默认值
1386
     * @return mixed
1387
     */
1388
    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...
1389
    {
1390
        $default = array_pop($filters);
1391
1392
        foreach ($filters as $filter) {
1393
            if (is_callable($filter)) {
1394
                // 调用函数或者方法过滤
1395
                $value = call_user_func($filter, $value);
1396
            } elseif (is_scalar($value)) {
1397
                if (false !== strpos($filter, '/')) {
1398
                    // 正则过滤
1399
                    if (!preg_match($filter, $value)) {
1400
                        // 匹配不成功返回默认值
1401
                        $value = $default;
1402
                        break;
1403
                    }
1404
                } elseif (!empty($filter)) {
1405
                    // filter函数不存在时, 则使用filter_var进行过滤
1406
                    // filter为非整形值时, 调用filter_id取得过滤id
1407
                    $value = filter_var($value, is_int($filter) ? $filter : filter_id($filter));
1408
                    if (false === $value) {
1409
                        $value = $default;
1410
                        break;
1411
                    }
1412
                }
1413
            }
1414
        }
1415
1416
        return $value;
1417
    }
1418
1419
    /**
1420
     * 是否存在某个请求参数
1421
     * @access public
1422
     * @param  string $name 变量名
0 ignored issues
show
Coding Style introduced by
Expected 7 spaces after parameter name; 1 found
Loading history...
1423
     * @param  string $type 变量类型
0 ignored issues
show
Coding Style introduced by
Expected 7 spaces after parameter name; 1 found
Loading history...
1424
     * @param  bool   $checkEmpty 是否检测空值
1425
     * @return bool
1426
     */
1427
    public function has(string $name, string $type = 'param', bool $checkEmpty = false): bool
1428
    {
1429
        if (!in_array($type, ['param', 'get', 'post', 'put', 'patch', 'route', 'delete', 'cookie', 'session', 'env', 'request', 'server', 'header', 'file'])) {
1430
            return false;
1431
        }
1432
1433
        $param = empty($this->$type) ? $this->$type() : $this->$type;
1434
1435
        if (is_object($param)) {
1436
            return $param->has($name);
1437
        }
1438
1439
        // 按.拆分成多维数组进行判断
1440
        foreach (explode('.', $name) as $val) {
1441
            if (isset($param[$val])) {
1442
                $param = $param[$val];
1443
            } else {
1444
                return false;
1445
            }
1446
        }
1447
1448
        return ($checkEmpty && '' === $param) ? false : true;
1449
    }
1450
1451
    /**
1452
     * 获取指定的参数
1453
     * @access public
1454
     * @param  array        $name 变量名
0 ignored issues
show
Coding Style introduced by
Expected 3 spaces after parameter name; 1 found
Loading history...
1455
     * @param  mixed        $data 数据或者变量类型
0 ignored issues
show
Coding Style introduced by
Expected 3 spaces after parameter name; 1 found
Loading history...
1456
     * @param  string|array $filter 过滤方法
1457
     * @return array
1458
     */
1459
    public function only(array $name, $data = 'param', $filter = ''): array
1460
    {
1461
        $data = is_array($data) ? $data : $this->$data();
1462
1463
        $item = [];
1464
        foreach ($name as $key => $val) {
1465
1466
            if (is_int($key)) {
1467
                $default = null;
1468
                $key     = $val;
1469
                if (!isset($data[$key])) {
1470
                    continue;
1471
                }
1472
            } else {
1473
                $default = $val;
1474
            }
1475
1476
            $item[$key] = $this->filterData($data[$key] ?? $default, $filter, $key, $default);
1477
        }
1478
1479
        return $item;
1480
    }
1481
1482
    /**
1483
     * 排除指定参数获取
1484
     * @access public
1485
     * @param  array  $name 变量名
1486
     * @param  string $type 变量类型
1487
     * @return mixed
1488
     */
1489
    public function except(array $name, string $type = 'param'): array
1490
    {
1491
        $param = $this->$type();
1492
1493
        foreach ($name as $key) {
1494
            if (isset($param[$key])) {
1495
                unset($param[$key]);
1496
            }
1497
        }
1498
1499
        return $param;
1500
    }
1501
1502
    /**
1503
     * 当前是否ssl
1504
     * @access public
1505
     * @return bool
1506
     */
1507
    public function isSsl(): bool
1508
    {
1509
        if ($this->server('HTTPS') && ('1' == $this->server('HTTPS') || 'on' == strtolower($this->server('HTTPS')))) {
1510
            return true;
1511
        } elseif ('https' == $this->server('REQUEST_SCHEME')) {
1512
            return true;
1513
        } elseif ('443' == $this->server('SERVER_PORT')) {
1514
            return true;
1515
        } elseif ('https' == $this->server('HTTP_X_FORWARDED_PROTO')) {
1516
            return true;
1517
        } elseif ($this->httpsAgentName && $this->server($this->httpsAgentName)) {
1518
            return true;
1519
        }
1520
1521
        return false;
1522
    }
1523
1524
    /**
1525
     * 当前是否JSON请求
1526
     * @access public
1527
     * @return bool
1528
     */
1529 8
    public function isJson(): bool
1530
    {
1531 8
        $contentType = $this->contentType();
1532 8
        $acceptType  = $this->type();
1533
1534 8
        return false !== strpos($contentType, 'json') || false !== strpos($acceptType, 'json');
1535
    }
1536
1537
    /**
1538
     * 当前是否Ajax请求
1539
     * @access public
1540
     * @param  bool $ajax true 获取原始ajax请求
1541
     * @return bool
1542
     */
1543
    public function isAjax(bool $ajax = false): bool
1544
    {
1545
        $value  = $this->server('HTTP_X_REQUESTED_WITH');
1546
        $result = $value && 'xmlhttprequest' == strtolower($value) ? true : false;
1547
1548
        if (true === $ajax) {
1549
            return $result;
1550
        }
1551
1552
        return $this->param($this->varAjax) ? true : $result;
1553
    }
1554
1555
    /**
1556
     * 当前是否Pjax请求
1557
     * @access public
1558
     * @param  bool $pjax true 获取原始pjax请求
1559
     * @return bool
1560
     */
1561
    public function isPjax(bool $pjax = false): bool
1562
    {
1563
        $result = !is_null($this->server('HTTP_X_PJAX')) ? true : false;
1564
1565
        if (true === $pjax) {
1566
            return $result;
1567
        }
1568
1569
        return $this->param($this->varPjax) ? true : $result;
1570
    }
1571
1572
    /**
1573
     * 获取客户端IP地址
1574
     * @access public
1575
     * @return string
1576
     */
1577
    public function ip(): string
1578
    {
1579
        if (!empty($this->realIP)) {
1580
            return $this->realIP;
1581
        }
1582
1583
        $this->realIP = $this->server('REMOTE_ADDR', '');
1584
1585
        // 如果指定了前端代理服务器IP以及其会发送的IP头
1586
        // 则尝试获取前端代理服务器发送过来的真实IP
1587
        $proxyIp       = $this->proxyServerIp;
1588
        $proxyIpHeader = $this->proxyServerIpHeader;
1589
1590
        if (count($proxyIp) > 0 && count($proxyIpHeader) > 0) {
1591
            // 从指定的HTTP头中依次尝试获取IP地址
1592
            // 直到获取到一个合法的IP地址
1593
            foreach ($proxyIpHeader as $header) {
1594
                $tempIP = $this->server($header);
1595
1596
                if (empty($tempIP)) {
1597
                    continue;
1598
                }
1599
1600
                $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

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