Completed
Push — 6.0 ( 71e4e1...4c6109 )
by liu
02:49
created

Request::__make()   B

Complexity

Conditions 8
Paths 5

Size

Total Lines 35
Code Lines 24

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 19
CRAP Score 8.5784

Importance

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

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