Completed
Push — 6.0 ( 278c39...a74adb )
by liu
03:27
created

Request::isCli()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 3
Code Lines 1

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 2

Importance

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

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