Completed
Push — 6.0 ( 58dbb9...e2b752 )
by yun
05:55
created

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

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

1084
            return $this->session->/** @scrutinizer ignore-call */ all();
Loading history...
1085
        }
1086
        return $this->session->get($name, $default);
0 ignored issues
show
Bug introduced by
The method get() does not exist on think\Session. Since you implemented __call, consider adding a @method annotation. ( Ignorable by Annotation )

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

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

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

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

1951
        $this->session->/** @scrutinizer ignore-call */ 
1952
                        set($name, $token);
Loading history...
1952
1953
        return $token;
1954
    }
1955
1956
    /**
1957
     * 检查请求令牌
1958
     * @access public
1959
     * @param  string $token 令牌名称
1960
     * @param  array  $data  表单数据
1961
     * @return bool
1962
     */
1963
    public function checkToken(string $token = '__token__', array $data = []): bool
1964
    {
1965
        if (in_array($this->method(), ['GET', 'HEAD', 'OPTIONS'], true)) {
1966
            return true;
1967
        }
1968
1969
        if (!$this->session->has($token)) {
0 ignored issues
show
Bug introduced by
The method has() does not exist on think\Session. Since you implemented __call, consider adding a @method annotation. ( Ignorable by Annotation )

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

1969
        if (!$this->session->/** @scrutinizer ignore-call */ has($token)) {
Loading history...
1970
            // 令牌数据无效
1971
            return false;
1972
        }
1973
1974
        // Header验证
1975
        if ($this->header('X-CSRF-TOKEN') && $this->session->get($token) === $this->header('X-CSRF-TOKEN')) {
1976
            // 防止重复提交
1977
            $this->session->delete($token); // 验证完成销毁session
0 ignored issues
show
Bug introduced by
The method delete() does not exist on think\Session. Since you implemented __call, consider adding a @method annotation. ( Ignorable by Annotation )

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

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