Completed
Push — 6.0 ( 4de6f5...a6720b )
by liu
03:17
created

Request::setRule()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 4
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 3
CRAP Score 1

Importance

Changes 0
Metric Value
cc 1
eloc 2
nc 1
nop 1
dl 0
loc 4
ccs 3
cts 3
cp 1
crap 1
rs 10
c 0
b 0
f 0
1
<?php
2
// +----------------------------------------------------------------------
3
// | ThinkPHP [ WE CAN DO IT JUST THINK ]
4
// +----------------------------------------------------------------------
5
// | Copyright (c) 2006~2021 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 ArrayAccess;
16
use think\file\UploadedFile;
17
use think\route\Rule;
18
19
/**
20
 * 请求管理类
21
 * @package think
22
 */
23
class Request implements ArrayAccess
24
{
25
    /**
26
     * 兼容PATH_INFO获取
27
     * @var array
28
     */
29
    protected $pathinfoFetch = ['ORIG_PATH_INFO', 'REDIRECT_PATH_INFO', 'REDIRECT_URL'];
30
31
    /**
32
     * PATHINFO变量名 用于兼容模式
33
     * @var string
34
     */
35
    protected $varPathinfo = 's';
36
37
    /**
38
     * 请求类型
39
     * @var string
40
     */
41
    protected $varMethod = '_method';
42
43
    /**
44
     * 表单ajax伪装变量
45
     * @var string
46
     */
47
    protected $varAjax = '_ajax';
48
49
    /**
50
     * 表单pjax伪装变量
51
     * @var string
52
     */
53
    protected $varPjax = '_pjax';
54
55
    /**
56
     * 域名根
57
     * @var string
58
     */
59
    protected $rootDomain = '';
60
61
    /**
62
     * HTTPS代理标识
63
     * @var string
64
     */
65
    protected $httpsAgentName = '';
66
67
    /**
68
     * 前端代理服务器IP
69
     * @var array
70
     */
71
    protected $proxyServerIp = [];
72
73
    /**
74
     * 前端代理服务器真实IP头
75
     * @var array
76
     */
77
    protected $proxyServerIpHeader = ['HTTP_X_REAL_IP', 'HTTP_X_FORWARDED_FOR', 'HTTP_CLIENT_IP', 'HTTP_X_CLIENT_IP', 'HTTP_X_CLUSTER_CLIENT_IP'];
78
79
    /**
80
     * 请求类型
81
     * @var string
82
     */
83
    protected $method;
84
85
    /**
86
     * 域名(含协议及端口)
87
     * @var string
88
     */
89
    protected $domain;
90
91
    /**
92
     * HOST(含端口)
93
     * @var string
94
     */
95
    protected $host;
96
97
    /**
98
     * 子域名
99
     * @var string
100
     */
101
    protected $subDomain;
102
103
    /**
104
     * 泛域名
105
     * @var string
106
     */
107
    protected $panDomain;
108
109
    /**
110
     * 当前URL地址
111
     * @var string
112
     */
113
    protected $url;
114
115
    /**
116
     * 基础URL
117
     * @var string
118
     */
119
    protected $baseUrl;
120
121
    /**
122
     * 当前执行的文件
123
     * @var string
124
     */
125
    protected $baseFile;
126
127
    /**
128
     * 访问的ROOT地址
129
     * @var string
130
     */
131
    protected $root;
132
133
    /**
134
     * pathinfo
135
     * @var string
136
     */
137
    protected $pathinfo;
138
139
    /**
140
     * pathinfo(不含后缀)
141
     * @var string
142
     */
143
    protected $path;
144
145
    /**
146
     * 当前请求的IP地址
147
     * @var string
148
     */
149
    protected $realIP;
150
151
    /**
152
     * 当前控制器名
153
     * @var string
154
     */
155
    protected $controller;
156
157
    /**
158
     * 当前操作名
159
     * @var string
160
     */
161
    protected $action;
162
163
    /**
164
     * 当前请求参数
165
     * @var array
166
     */
167
    protected $param = [];
168
169
    /**
170
     * 当前GET参数
171
     * @var array
172
     */
173
    protected $get = [];
174
175
    /**
176
     * 当前POST参数
177
     * @var array
178
     */
179
    protected $post = [];
180
181
    /**
182
     * 当前REQUEST参数
183
     * @var array
184
     */
185
    protected $request = [];
186
187
    /**
188
     * 当前路由对象
189
     * @var Rule
190
     */
191
    protected $rule;
192
193
    /**
194
     * 当前ROUTE参数
195
     * @var array
196
     */
197
    protected $route = [];
198
199
    /**
200
     * 中间件传递的参数
201
     * @var array
202
     */
203
    protected $middleware = [];
204
205
    /**
206
     * 当前PUT参数
207
     * @var array
208
     */
209
    protected $put;
210
211
    /**
212
     * SESSION对象
213
     * @var Session
214
     */
215
    protected $session;
216
217
    /**
218
     * COOKIE数据
219
     * @var array
220
     */
221
    protected $cookie = [];
222
223
    /**
224
     * ENV对象
225
     * @var Env
226
     */
227
    protected $env;
228
229
    /**
230
     * 当前SERVER参数
231
     * @var array
232
     */
233
    protected $server = [];
234
235
    /**
236
     * 当前FILE参数
237
     * @var array
238
     */
239
    protected $file = [];
240
241
    /**
242
     * 当前HEADER参数
243
     * @var array
244
     */
245
    protected $header = [];
246
247
    /**
248
     * 资源类型定义
249
     * @var array
250
     */
251
    protected $mimeType = [
252
        'xml'   => 'application/xml,text/xml,application/x-xml',
253
        'json'  => 'application/json,text/x-json,application/jsonrequest,text/json',
254
        'js'    => 'text/javascript,application/javascript,application/x-javascript',
255
        'css'   => 'text/css',
256
        'rss'   => 'application/rss+xml',
257
        'yaml'  => 'application/x-yaml,text/yaml',
258
        'atom'  => 'application/atom+xml',
259
        'pdf'   => 'application/pdf',
260
        'text'  => 'text/plain',
261
        'image' => 'image/png,image/jpg,image/jpeg,image/pjpeg,image/gif,image/webp,image/*',
262
        'csv'   => 'text/csv',
263
        'html'  => 'text/html,application/xhtml+xml,*/*',
264
    ];
265
266
    /**
267
     * 当前请求内容
268
     * @var string
269
     */
270
    protected $content;
271
272
    /**
273
     * 全局过滤规则
274
     * @var array
275
     */
276
    protected $filter;
277
278
    /**
279
     * php://input内容
280
     * @var string
281
     */
282
    // php://input
283
    protected $input;
284
285
    /**
286
     * 请求安全Key
287
     * @var string
288
     */
289
    protected $secureKey;
290
291
    /**
292
     * 是否合并Param
293
     * @var bool
294
     */
295
    protected $mergeParam = false;
296
297
    /**
298
     * 架构函数
299
     * @access public
300
     */
301 30
    public function __construct()
302
    {
303
        // 保存 php://input
304 30
        $this->input = file_get_contents('php://input');
305 30
    }
306
307 30
    public static function __make(App $app)
308
    {
309 30
        $request = new static();
310
311 30
        if (function_exists('apache_request_headers') && $result = apache_request_headers()) {
312
            $header = $result;
313
        } else {
314 30
            $header = [];
315 30
            $server = $_SERVER;
316 30
            foreach ($server as $key => $val) {
317 30
                if (0 === strpos($key, 'HTTP_')) {
318
                    $key          = str_replace('_', '-', strtolower(substr($key, 5)));
319 10
                    $header[$key] = $val;
320
                }
321
            }
322 30
            if (isset($server['CONTENT_TYPE'])) {
323
                $header['content-type'] = $server['CONTENT_TYPE'];
324
            }
325 30
            if (isset($server['CONTENT_LENGTH'])) {
326
                $header['content-length'] = $server['CONTENT_LENGTH'];
327
            }
328
        }
329
330 30
        $request->header = array_change_key_case($header);
0 ignored issues
show
Bug introduced by
It seems like $header can also be of type true; however, parameter $array of array_change_key_case() does only seem to accept array, 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

330
        $request->header = array_change_key_case(/** @scrutinizer ignore-type */ $header);
Loading history...
331 30
        $request->server = $_SERVER;
332 30
        $request->env    = $app->env;
333
334 30
        $inputData = $request->getInputData($request->input);
335
336 30
        $request->get     = $_GET;
337 30
        $request->post    = $_POST ?: $inputData;
338 30
        $request->put     = $inputData;
339 30
        $request->request = $_REQUEST;
340 30
        $request->cookie  = $_COOKIE;
341 30
        $request->file    = $_FILES ?? [];
342
343 30
        return $request;
344
    }
345
346
    /**
347
     * 设置当前包含协议的域名
348
     * @access public
349
     * @param  string $domain 域名
350
     * @return $this
351
     */
352
    public function setDomain(string $domain)
353
    {
354
        $this->domain = $domain;
355
        return $this;
356
    }
357
358
    /**
359
     * 获取当前包含协议的域名
360
     * @access public
361
     * @param  bool $port 是否需要去除端口号
362
     * @return string
363
     */
364
    public function domain(bool $port = false): string
365
    {
366
        return $this->scheme() . '://' . $this->host($port);
367
    }
368
369
    /**
370
     * 获取当前根域名
371
     * @access public
372
     * @return string
373
     */
374 33
    public function rootDomain(): string
375
    {
376 33
        $root = $this->rootDomain;
377
378 33
        if (!$root) {
379 33
            $item  = explode('.', $this->host());
380 33
            $count = count($item);
381 33
            $root  = $count > 1 ? $item[$count - 2] . '.' . $item[$count - 1] : $item[0];
382
        }
383
384 33
        return $root;
385
    }
386
387
    /**
388
     * 设置当前泛域名的值
389
     * @access public
390
     * @param  string $domain 域名
391
     * @return $this
392
     */
393
    public function setSubDomain(string $domain)
394
    {
395
        $this->subDomain = $domain;
396
        return $this;
397
    }
398
399
    /**
400
     * 获取当前子域名
401
     * @access public
402
     * @return string
403
     */
404 33
    public function subDomain(): string
405
    {
406 33
        if (is_null($this->subDomain)) {
0 ignored issues
show
introduced by
The condition is_null($this->subDomain) is always false.
Loading history...
407
            // 获取当前主域名
408 33
            $rootDomain = $this->rootDomain();
409
410 33
            if ($rootDomain) {
411 33
                $this->subDomain = rtrim(stristr($this->host(), $rootDomain, true), '.');
412
            } else {
413
                $this->subDomain = '';
414
            }
415
        }
416
417 33
        return $this->subDomain;
418
    }
419
420
    /**
421
     * 设置当前泛域名的值
422
     * @access public
423
     * @param  string $domain 域名
424
     * @return $this
425
     */
426
    public function setPanDomain(string $domain)
427
    {
428
        $this->panDomain = $domain;
429
        return $this;
430
    }
431
432
    /**
433
     * 获取当前泛域名的值
434
     * @access public
435
     * @return string
436
     */
437 3
    public function panDomain(): string
438
    {
439 3
        return $this->panDomain ?: '';
440
    }
441
442
    /**
443
     * 设置当前完整URL 包括QUERY_STRING
444
     * @access public
445
     * @param  string $url URL地址
446
     * @return $this
447
     */
448
    public function setUrl(string $url)
449
    {
450
        $this->url = $url;
451
        return $this;
452
    }
453
454
    /**
455
     * 获取当前完整URL 包括QUERY_STRING
456
     * @access public
457
     * @param  bool $complete 是否包含完整域名
458
     * @return string
459
     */
460
    public function url(bool $complete = false): string
461
    {
462
        if ($this->url) {
463
            $url = $this->url;
464
        } elseif ($this->server('HTTP_X_REWRITE_URL')) {
465
            $url = $this->server('HTTP_X_REWRITE_URL');
466
        } elseif ($this->server('REQUEST_URI')) {
467
            $url = $this->server('REQUEST_URI');
468
        } elseif ($this->server('ORIG_PATH_INFO')) {
469
            $url = $this->server('ORIG_PATH_INFO') . (!empty($this->server('QUERY_STRING')) ? '?' . $this->server('QUERY_STRING') : '');
470
        } elseif (isset($_SERVER['argv'][1])) {
471
            $url = $_SERVER['argv'][1];
472
        } else {
473
            $url = '';
474
        }
475
476
        return $complete ? $this->domain() . $url : $url;
477
    }
478
479
    /**
480
     * 设置当前URL 不含QUERY_STRING
481
     * @access public
482
     * @param  string $url URL地址
483
     * @return $this
484
     */
485
    public function setBaseUrl(string $url)
486
    {
487
        $this->baseUrl = $url;
488
        return $this;
489
    }
490
491
    /**
492
     * 获取当前URL 不含QUERY_STRING
493
     * @access public
494
     * @param  bool $complete 是否包含完整域名
495
     * @return string
496
     */
497
    public function baseUrl(bool $complete = false): string
498
    {
499
        if (!$this->baseUrl) {
500
            $str           = $this->url();
501
            $this->baseUrl = strpos($str, '?') ? strstr($str, '?', true) : $str;
502
        }
503
504
        return $complete ? $this->domain() . $this->baseUrl : $this->baseUrl;
505
    }
506
507
    /**
508
     * 获取当前执行的文件 SCRIPT_NAME
509
     * @access public
510
     * @param  bool $complete 是否包含完整域名
511
     * @return string
512
     */
513
    public function baseFile(bool $complete = false): string
514
    {
515
        if (!$this->baseFile) {
516
            $url = '';
517
            if (!$this->isCli()) {
518
                $script_name = basename($this->server('SCRIPT_FILENAME'));
519
                if (basename($this->server('SCRIPT_NAME')) === $script_name) {
520
                    $url = $this->server('SCRIPT_NAME');
521
                } elseif (basename($this->server('PHP_SELF')) === $script_name) {
522
                    $url = $this->server('PHP_SELF');
523
                } elseif (basename($this->server('ORIG_SCRIPT_NAME')) === $script_name) {
524
                    $url = $this->server('ORIG_SCRIPT_NAME');
525
                } elseif (($pos = strpos($this->server('PHP_SELF'), '/' . $script_name)) !== false) {
526
                    $url = substr($this->server('SCRIPT_NAME'), 0, $pos) . '/' . $script_name;
527
                } elseif ($this->server('DOCUMENT_ROOT') && strpos($this->server('SCRIPT_FILENAME'), $this->server('DOCUMENT_ROOT')) === 0) {
528
                    $url = str_replace('\\', '/', str_replace($this->server('DOCUMENT_ROOT'), '', $this->server('SCRIPT_FILENAME')));
529
                }
530
            }
531
            $this->baseFile = $url;
532
        }
533
534
        return $complete ? $this->domain() . $this->baseFile : $this->baseFile;
535
    }
536
537
    /**
538
     * 设置URL访问根地址
539
     * @access public
540
     * @param  string $url URL地址
541
     * @return $this
542
     */
543
    public function setRoot(string $url)
544
    {
545
        $this->root = $url;
546
        return $this;
547
    }
548
549
    /**
550
     * 获取URL访问根地址
551
     * @access public
552
     * @param  bool $complete 是否包含完整域名
553
     * @return string
554
     */
555
    public function root(bool $complete = false): string
556
    {
557
        if (!$this->root) {
558
            $file = $this->baseFile();
559
            if ($file && 0 !== strpos($this->url(), $file)) {
560
                $file = str_replace('\\', '/', dirname($file));
561
            }
562
            $this->root = rtrim($file, '/');
563
        }
564
565
        return $complete ? $this->domain() . $this->root : $this->root;
566
    }
567
568
    /**
569
     * 获取URL访问根目录
570
     * @access public
571
     * @return string
572
     */
573
    public function rootUrl(): string
574
    {
575
        $base = $this->root();
576
        $root = strpos($base, '.') ? ltrim(dirname($base), DIRECTORY_SEPARATOR) : $base;
577
578
        if ('' != $root) {
579
            $root = '/' . ltrim($root, '/');
580
        }
581
582
        return $root;
583
    }
584
585
    /**
586
     * 设置当前请求的pathinfo
587
     * @access public
588
     * @param  string $pathinfo
589
     * @return $this
590
     */
591
    public function setPathinfo(string $pathinfo)
592
    {
593
        $this->pathinfo = $pathinfo;
594
        return $this;
595
    }
596
597
    /**
598
     * 获取当前请求URL的pathinfo信息(含URL后缀)
599
     * @access public
600
     * @return string
601
     */
602
    public function pathinfo(): string
603
    {
604
        if (is_null($this->pathinfo)) {
0 ignored issues
show
introduced by
The condition is_null($this->pathinfo) is always false.
Loading history...
605
            if (isset($_GET[$this->varPathinfo])) {
606
                // 判断URL里面是否有兼容模式参数
607
                $pathinfo = $_GET[$this->varPathinfo];
608
                unset($_GET[$this->varPathinfo]);
609
                unset($this->get[$this->varPathinfo]);
610
            } elseif ($this->server('PATH_INFO')) {
611
                $pathinfo = $this->server('PATH_INFO');
612
            } elseif (false !== strpos(PHP_SAPI, 'cli')) {
613
                $pathinfo = strpos($this->server('REQUEST_URI'), '?') ? strstr($this->server('REQUEST_URI'), '?', true) : $this->server('REQUEST_URI');
614
            }
615
616
            // 分析PATHINFO信息
617
            if (!isset($pathinfo)) {
618
                foreach ($this->pathinfoFetch as $type) {
619
                    if ($this->server($type)) {
620
                        $pathinfo = (0 === strpos($this->server($type), $this->server('SCRIPT_NAME'))) ?
621
                        substr($this->server($type), strlen($this->server('SCRIPT_NAME'))) : $this->server($type);
622
                        break;
623
                    }
624
                }
625
            }
626
627
            if (!empty($pathinfo)) {
628
                unset($this->get[$pathinfo], $this->request[$pathinfo]);
629
            }
630
631
            $this->pathinfo = empty($pathinfo) || '/' == $pathinfo ? '' : ltrim($pathinfo, '/');
632
        }
633
634
        return $this->pathinfo;
635
    }
636
637
    /**
638
     * 当前URL的访问后缀
639
     * @access public
640
     * @return string
641
     */
642
    public function ext(): string
643
    {
644
        return pathinfo($this->pathinfo(), PATHINFO_EXTENSION);
645
    }
646
647
    /**
648
     * 获取当前请求的时间
649
     * @access public
650
     * @param  bool $float 是否使用浮点类型
651
     * @return integer|float
652
     */
653
    public function time(bool $float = false)
654
    {
655
        return $float ? $this->server('REQUEST_TIME_FLOAT') : $this->server('REQUEST_TIME');
656
    }
657
658
    /**
659
     * 当前请求的资源类型
660
     * @access public
661
     * @return string
662
     */
663 21
    public function type(): string
664
    {
665 21
        $accept = $this->server('HTTP_ACCEPT');
666
667 21
        if (empty($accept)) {
668 21
            return '';
669
        }
670
671
        foreach ($this->mimeType as $key => $val) {
672
            $array = explode(',', $val);
673
            foreach ($array as $k => $v) {
674
                if (stristr($accept, $v)) {
675
                    return $key;
676
                }
677
            }
678
        }
679
680
        return '';
681
    }
682
683
    /**
684
     * 设置资源类型
685
     * @access public
686
     * @param  string|array $type 资源类型名
687
     * @param  string       $val 资源类型
688
     * @return void
689
     */
690
    public function mimeType($type, $val = ''): void
691
    {
692
        if (is_array($type)) {
693
            $this->mimeType = array_merge($this->mimeType, $type);
694
        } else {
695
            $this->mimeType[$type] = $val;
696
        }
697
    }
698
699
    /**
700
     * 设置请求类型
701
     * @access public
702
     * @param  string $method 请求类型
703
     * @return $this
704
     */
705
    public function setMethod(string $method)
706
    {
707
        $this->method = strtoupper($method);
708
        return $this;
709
    }
710
711
    /**
712
     * 当前的请求类型
713
     * @access public
714
     * @param  bool $origin 是否获取原始请求类型
715
     * @return string
716
     */
717
    public function method(bool $origin = false): string
718
    {
719
        if ($origin) {
720
            // 获取原始请求类型
721
            return $this->server('REQUEST_METHOD') ?: 'GET';
722
        } elseif (!$this->method) {
723
            if (isset($this->post[$this->varMethod])) {
724
                $method = strtolower($this->post[$this->varMethod]);
725
                if (in_array($method, ['get', 'post', 'put', 'patch', 'delete'])) {
726
                    $this->method    = strtoupper($method);
727
                    $this->{$method} = $this->post;
728
                } else {
729
                    $this->method = 'POST';
730
                }
731
                unset($this->post[$this->varMethod]);
732
            } elseif ($this->server('HTTP_X_HTTP_METHOD_OVERRIDE')) {
733
                $this->method = strtoupper($this->server('HTTP_X_HTTP_METHOD_OVERRIDE'));
734
            } else {
735
                $this->method = $this->server('REQUEST_METHOD') ?: 'GET';
736
            }
737
        }
738
739
        return $this->method;
740
    }
741
742
    /**
743
     * 是否为GET请求
744
     * @access public
745
     * @return bool
746
     */
747
    public function isGet(): bool
748
    {
749
        return $this->method() == 'GET';
750
    }
751
752
    /**
753
     * 是否为POST请求
754
     * @access public
755
     * @return bool
756
     */
757
    public function isPost(): bool
758
    {
759
        return $this->method() == 'POST';
760
    }
761
762
    /**
763
     * 是否为PUT请求
764
     * @access public
765
     * @return bool
766
     */
767
    public function isPut(): bool
768
    {
769
        return $this->method() == 'PUT';
770
    }
771
772
    /**
773
     * 是否为DELTE请求
774
     * @access public
775
     * @return bool
776
     */
777
    public function isDelete(): bool
778
    {
779
        return $this->method() == 'DELETE';
780
    }
781
782
    /**
783
     * 是否为HEAD请求
784
     * @access public
785
     * @return bool
786
     */
787
    public function isHead(): bool
788
    {
789
        return $this->method() == 'HEAD';
790
    }
791
792
    /**
793
     * 是否为PATCH请求
794
     * @access public
795
     * @return bool
796
     */
797
    public function isPatch(): bool
798
    {
799
        return $this->method() == 'PATCH';
800
    }
801
802
    /**
803
     * 是否为OPTIONS请求
804
     * @access public
805
     * @return bool
806
     */
807
    public function isOptions(): bool
808
    {
809
        return $this->method() == 'OPTIONS';
810
    }
811
812
    /**
813
     * 是否为cli
814
     * @access public
815
     * @return bool
816
     */
817
    public function isCli(): bool
818
    {
819
        return PHP_SAPI == 'cli';
820
    }
821
822
    /**
823
     * 是否为cgi
824
     * @access public
825
     * @return bool
826
     */
827
    public function isCgi(): bool
828
    {
829
        return strpos(PHP_SAPI, 'cgi') === 0;
830
    }
831
832
    /**
833
     * 获取当前请求的参数
834
     * @access public
835
     * @param  string|array $name 变量名
836
     * @param  mixed        $default 默认值
837
     * @param  string|array $filter 过滤方法
838
     * @return mixed
839
     */
840 33
    public function param($name = '', $default = null, $filter = '')
841
    {
842 33
        if (empty($this->mergeParam)) {
843 33
            $method = $this->method(true);
844
845
            // 自动获取请求变量
846 22
            switch ($method) {
847 33
                case 'POST':
848 3
                    $vars = $this->post(false);
0 ignored issues
show
Bug introduced by
false of type false is incompatible with the type array|string expected by parameter $name of think\Request::post(). ( Ignorable by Annotation )

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

848
                    $vars = $this->post(/** @scrutinizer ignore-type */ false);
Loading history...
849 3
                    break;
850 33
                case 'PUT':
851 33
                case 'DELETE':
852 33
                case 'PATCH':
853
                    $vars = $this->put(false);
0 ignored issues
show
Bug introduced by
false of type false is incompatible with the type array|string expected by parameter $name of think\Request::put(). ( Ignorable by Annotation )

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

853
                    $vars = $this->put(/** @scrutinizer ignore-type */ false);
Loading history...
854
                    break;
855
                default:
856 33
                    $vars = [];
857
            }
858
859
            // 当前请求参数和URL地址中的参数合并
860 33
            $this->param = array_merge($this->param, $this->get(false), $vars, $this->route(false));
0 ignored issues
show
Bug introduced by
false of type false is incompatible with the type array|string expected by parameter $name of think\Request::get(). ( Ignorable by Annotation )

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

860
            $this->param = array_merge($this->param, $this->get(/** @scrutinizer ignore-type */ false), $vars, $this->route(false));
Loading history...
Bug introduced by
false of type false is incompatible with the type array|string expected by parameter $name of think\Request::route(). ( Ignorable by Annotation )

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

860
            $this->param = array_merge($this->param, $this->get(false), $vars, $this->route(/** @scrutinizer ignore-type */ false));
Loading history...
861
862 33
            $this->mergeParam = true;
863
        }
864
865 33
        if (is_array($name)) {
866
            return $this->only($name, $this->param, $filter);
867
        }
868
869 33
        return $this->input($this->param, $name, $default, $filter);
870
    }
871
872
    /**
873
     * 获取包含文件在内的请求参数
874
     * @access public
875
     * @param  string|array $name 变量名
876
     * @param  string|array $filter 过滤方法
877
     * @return mixed
878
     */
879
    public function all($name = '', $filter = '')
880
    {
881
        $data = array_merge($this->param(), $this->file());
0 ignored issues
show
Bug introduced by
It seems like $this->file() can also be of type null and think\file\UploadedFile; however, parameter $arrays of array_merge() does only seem to accept array, 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

881
        $data = array_merge($this->param(), /** @scrutinizer ignore-type */ $this->file());
Loading history...
Bug introduced by
It seems like $this->param() can also be of type null and object; however, parameter $arrays of array_merge() does only seem to accept array, 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

881
        $data = array_merge(/** @scrutinizer ignore-type */ $this->param(), $this->file());
Loading history...
882
883
        if (is_array($name)) {
884
            $data = $this->only($name, $data, $filter);
885
        }
886
887
        return $data;
888
    }
889
890
    /**
891
     * 设置路由变量
892
     * @access public
893
     * @param  Rule $rule 路由对象
894
     * @return $this
895
     */
896 33
    public function setRule(Rule $rule)
897
    {
898 33
        $this->rule = $rule;
899 33
        return $this;
900
    }
901
902
    /**
903
     * 获取当前路由对象
904
     * @access public
905
     * @return Rule|null
906
     */
907 3
    public function rule()
908
    {
909 3
        return $this->rule;
910
    }
911
912
    /**
913
     * 设置路由变量
914
     * @access public
915
     * @param  array $route 路由变量
916
     * @return $this
917
     */
918 33
    public function setRoute(array $route)
919
    {
920 33
        $this->route      = array_merge($this->route, $route);
921 33
        $this->mergeParam = false;
922 33
        return $this;
923
    }
924
925
    /**
926
     * 获取路由参数
927
     * @access public
928
     * @param  string|array $name 变量名
929
     * @param  mixed        $default 默认值
930
     * @param  string|array $filter 过滤方法
931
     * @return mixed
932
     */
933 33
    public function route($name = '', $default = null, $filter = '')
934
    {
935 33
        if (is_array($name)) {
936
            return $this->only($name, $this->route, $filter);
937
        }
938
939 33
        return $this->input($this->route, $name, $default, $filter);
940
    }
941
942
    /**
943
     * 获取GET参数
944
     * @access public
945
     * @param  string|array $name 变量名
946
     * @param  mixed        $default 默认值
947
     * @param  string|array $filter 过滤方法
948
     * @return mixed
949
     */
950 33
    public function get($name = '', $default = null, $filter = '')
951
    {
952 33
        if (is_array($name)) {
953
            return $this->only($name, $this->get, $filter);
954
        }
955
956 33
        return $this->input($this->get, $name, $default, $filter);
957
    }
958
959
    /**
960
     * 获取中间件传递的参数
961
     * @access public
962
     * @param  mixed $name 变量名
963
     * @param  mixed $default 默认值
964
     * @return mixed
965
     */
966
    public function middleware($name, $default = null)
967
    {
968
        return $this->middleware[$name] ?? $default;
969
    }
970
971
    /**
972
     * 获取POST参数
973
     * @access public
974
     * @param  string|array $name 变量名
975
     * @param  mixed        $default 默认值
976
     * @param  string|array $filter 过滤方法
977
     * @return mixed
978
     */
979 3
    public function post($name = '', $default = null, $filter = '')
980
    {
981 3
        if (is_array($name)) {
982
            return $this->only($name, $this->post, $filter);
983
        }
984
985 3
        return $this->input($this->post, $name, $default, $filter);
986
    }
987
988
    /**
989
     * 获取PUT参数
990
     * @access public
991
     * @param  string|array $name 变量名
992
     * @param  mixed        $default 默认值
993
     * @param  string|array $filter 过滤方法
994
     * @return mixed
995
     */
996
    public function put($name = '', $default = null, $filter = '')
997
    {
998
        if (is_array($name)) {
999
            return $this->only($name, $this->put, $filter);
1000
        }
1001
1002
        return $this->input($this->put, $name, $default, $filter);
1003
    }
1004
1005 30
    protected function getInputData($content): array
1006
    {
1007 30
        $contentType = $this->contentType();
1008 30
        if ('application/x-www-form-urlencoded' == $contentType) {
1009
            parse_str($content, $data);
1010
            return $data;
1011 30
        } elseif (false !== strpos($contentType, 'json')) {
1012
            return (array) json_decode($content, true);
1013
        }
1014
1015 30
        return [];
1016
    }
1017
1018
    /**
1019
     * 设置获取DELETE参数
1020
     * @access public
1021
     * @param  mixed        $name 变量名
1022
     * @param  mixed        $default 默认值
1023
     * @param  string|array $filter 过滤方法
1024
     * @return mixed
1025
     */
1026
    public function delete($name = '', $default = null, $filter = '')
1027
    {
1028
        return $this->put($name, $default, $filter);
1029
    }
1030
1031
    /**
1032
     * 设置获取PATCH参数
1033
     * @access public
1034
     * @param  mixed        $name 变量名
1035
     * @param  mixed        $default 默认值
1036
     * @param  string|array $filter 过滤方法
1037
     * @return mixed
1038
     */
1039
    public function patch($name = '', $default = null, $filter = '')
1040
    {
1041
        return $this->put($name, $default, $filter);
1042
    }
1043
1044
    /**
1045
     * 获取request变量
1046
     * @access public
1047
     * @param  string|array $name 数据名称
1048
     * @param  mixed        $default 默认值
1049
     * @param  string|array $filter 过滤方法
1050
     * @return mixed
1051
     */
1052
    public function request($name = '', $default = null, $filter = '')
1053
    {
1054
        if (is_array($name)) {
1055
            return $this->only($name, $this->request, $filter);
1056
        }
1057
1058
        return $this->input($this->request, $name, $default, $filter);
1059
    }
1060
1061
    /**
1062
     * 获取环境变量
1063
     * @access public
1064
     * @param  string $name 数据名称
1065
     * @param  string $default 默认值
1066
     * @return mixed
1067
     */
1068
    public function env(string $name = '', string $default = null)
1069
    {
1070
        if (empty($name)) {
1071
            return $this->env->get();
1072
        } else {
1073
            $name = strtoupper($name);
1074
        }
1075
1076
        return $this->env->get($name, $default);
1077
    }
1078
1079
    /**
1080
     * 获取session数据
1081
     * @access public
1082
     * @param  string $name 数据名称
1083
     * @param  string $default 默认值
1084
     * @return mixed
1085
     */
1086
    public function session(string $name = '', $default = null)
1087
    {
1088
        if ('' === $name) {
1089
            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

1089
            return $this->session->/** @scrutinizer ignore-call */ all();
Loading history...
1090
        }
1091
        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

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

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

1620
                $tempIP = trim(explode(',', /** @scrutinizer ignore-type */ $tempIP)[0]);
Loading history...
1621
1622
                if (!$this->isValidIP($tempIP)) {
1623
                    $tempIP = null;
1624
                } else {
1625
                    break;
1626
                }
1627
            }
1628
1629
            // tempIP不为空,说明获取到了一个IP地址
1630
            // 这时我们检查 REMOTE_ADDR 是不是指定的前端代理服务器之一
1631
            // 如果是的话说明该 IP头 是由前端代理服务器设置的
1632
            // 否则则是伪装的
1633
            if (!empty($tempIP)) {
1634
                $realIPBin = $this->ip2bin($this->realIP);
1635
1636
                foreach ($proxyIp as $ip) {
1637
                    $serverIPElements = explode('/', $ip);
1638
                    $serverIP         = $serverIPElements[0];
1639
                    $serverIPPrefix   = $serverIPElements[1] ?? 128;
1640
                    $serverIPBin      = $this->ip2bin($serverIP);
1641
1642
                    // IP类型不符
1643
                    if (strlen($realIPBin) !== strlen($serverIPBin)) {
1644
                        continue;
1645
                    }
1646
1647
                    if (strncmp($realIPBin, $serverIPBin, (int) $serverIPPrefix) === 0) {
1648
                        $this->realIP = $tempIP;
1649
                        break;
1650
                    }
1651
                }
1652
            }
1653
        }
1654
1655
        if (!$this->isValidIP($this->realIP)) {
1656
            $this->realIP = '0.0.0.0';
1657
        }
1658
1659
        return $this->realIP;
1660
    }
1661
1662
    /**
1663
     * 检测是否是合法的IP地址
1664
     *
1665
     * @param string $ip   IP地址
1666
     * @param string $type IP地址类型 (ipv4, ipv6)
1667
     *
1668
     * @return boolean
1669
     */
1670
    public function isValidIP(string $ip, string $type = ''): bool
1671
    {
1672
        switch (strtolower($type)) {
1673
            case 'ipv4':
1674
                $flag = FILTER_FLAG_IPV4;
1675
                break;
1676
            case 'ipv6':
1677
                $flag = FILTER_FLAG_IPV6;
1678
                break;
1679
            default:
1680
                $flag = 0;
1681
                break;
1682
        }
1683
1684
        return boolval(filter_var($ip, FILTER_VALIDATE_IP, $flag));
1685
    }
1686
1687
    /**
1688
     * 将IP地址转换为二进制字符串
1689
     *
1690
     * @param string $ip
1691
     *
1692
     * @return string
1693
     */
1694
    public function ip2bin(string $ip): string
1695
    {
1696
        if ($this->isValidIP($ip, 'ipv6')) {
1697
            $IPHex = str_split(bin2hex(inet_pton($ip)), 4);
1698
            foreach ($IPHex as $key => $value) {
1699
                $IPHex[$key] = intval($value, 16);
1700
            }
1701
            $IPBin = vsprintf('%016b%016b%016b%016b%016b%016b%016b%016b', $IPHex);
0 ignored issues
show
Bug introduced by
It seems like $IPHex can also be of type true; however, parameter $values of vsprintf() does only seem to accept array, 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

1701
            $IPBin = vsprintf('%016b%016b%016b%016b%016b%016b%016b%016b', /** @scrutinizer ignore-type */ $IPHex);
Loading history...
1702
        } else {
1703
            $IPHex = str_split(bin2hex(inet_pton($ip)), 2);
1704
            foreach ($IPHex as $key => $value) {
1705
                $IPHex[$key] = intval($value, 16);
1706
            }
1707
            $IPBin = vsprintf('%08b%08b%08b%08b', $IPHex);
1708
        }
1709
1710
        return $IPBin;
1711
    }
1712
1713
    /**
1714
     * 检测是否使用手机访问
1715
     * @access public
1716
     * @return bool
1717
     */
1718
    public function isMobile(): bool
1719
    {
1720
        if ($this->server('HTTP_VIA') && stristr($this->server('HTTP_VIA'), "wap")) {
1721
            return true;
1722
        } elseif ($this->server('HTTP_ACCEPT') && strpos(strtoupper($this->server('HTTP_ACCEPT')), "VND.WAP.WML")) {
1723
            return true;
1724
        } elseif ($this->server('HTTP_X_WAP_PROFILE') || $this->server('HTTP_PROFILE')) {
1725
            return true;
1726
        } elseif ($this->server('HTTP_USER_AGENT') && preg_match('/(blackberry|configuration\/cldc|hp |hp-|htc |htc_|htc-|iemobile|kindle|midp|mmp|motorola|mobile|nokia|opera mini|opera |Googlebot-Mobile|YahooSeeker\/M1A1-R2D2|android|iphone|ipod|mobi|palm|palmos|pocket|portalmmm|ppc;|smartphone|sonyericsson|sqh|spv|symbian|treo|up.browser|up.link|vodafone|windows ce|xda |xda_)/i', $this->server('HTTP_USER_AGENT'))) {
1727
            return true;
1728
        }
1729
1730
        return false;
1731
    }
1732
1733
    /**
1734
     * 当前URL地址中的scheme参数
1735
     * @access public
1736
     * @return string
1737
     */
1738
    public function scheme(): string
1739
    {
1740
        return $this->isSsl() ? 'https' : 'http';
1741
    }
1742
1743
    /**
1744
     * 当前请求URL地址中的query参数
1745
     * @access public
1746
     * @return string
1747
     */
1748
    public function query(): string
1749
    {
1750
        return $this->server('QUERY_STRING', '');
1751
    }
1752
1753
    /**
1754
     * 设置当前请求的host(包含端口)
1755
     * @access public
1756
     * @param  string $host 主机名(含端口)
1757
     * @return $this
1758
     */
1759
    public function setHost(string $host)
1760
    {
1761
        $this->host = $host;
1762
1763
        return $this;
1764
    }
1765
1766
    /**
1767
     * 当前请求的host
1768
     * @access public
1769
     * @param bool $strict  true 仅仅获取HOST
1770
     * @return string
1771
     */
1772
    public function host(bool $strict = false): string
1773
    {
1774
        if ($this->host) {
1775
            $host = $this->host;
1776
        } else {
1777
            $host = strval($this->server('HTTP_X_FORWARDED_HOST') ?: $this->server('HTTP_HOST'));
1778
        }
1779
1780
        return true === $strict && strpos($host, ':') ? strstr($host, ':', true) : $host;
1781
    }
1782
1783
    /**
1784
     * 当前请求URL地址中的port参数
1785
     * @access public
1786
     * @return int
1787
     */
1788
    public function port(): int
1789
    {
1790
        return (int) ($this->server('HTTP_X_FORWARDED_PORT') ?: $this->server('SERVER_PORT', ''));
1791
    }
1792
1793
    /**
1794
     * 当前请求 SERVER_PROTOCOL
1795
     * @access public
1796
     * @return string
1797
     */
1798
    public function protocol(): string
1799
    {
1800
        return $this->server('SERVER_PROTOCOL', '');
1801
    }
1802
1803
    /**
1804
     * 当前请求 REMOTE_PORT
1805
     * @access public
1806
     * @return int
1807
     */
1808
    public function remotePort(): int
1809
    {
1810
        return (int) $this->server('REMOTE_PORT', '');
1811
    }
1812
1813
    /**
1814
     * 当前请求 HTTP_CONTENT_TYPE
1815
     * @access public
1816
     * @return string
1817
     */
1818 30
    public function contentType(): string
1819
    {
1820 30
        $contentType = $this->header('Content-Type');
1821
1822 30
        if ($contentType) {
1823
            if (strpos($contentType, ';')) {
0 ignored issues
show
Bug introduced by
It seems like $contentType can also be of type array; however, parameter $haystack of strpos() 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

1823
            if (strpos(/** @scrutinizer ignore-type */ $contentType, ';')) {
Loading history...
1824
                [$type] = explode(';', $contentType);
0 ignored issues
show
Bug introduced by
It seems like $contentType 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

1824
                [$type] = explode(';', /** @scrutinizer ignore-type */ $contentType);
Loading history...
1825
            } else {
1826
                $type = $contentType;
1827
            }
1828
            return trim($type);
0 ignored issues
show
Bug introduced by
It seems like $type can also be of type array; however, parameter $string of trim() 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

1828
            return trim(/** @scrutinizer ignore-type */ $type);
Loading history...
1829
        }
1830
1831 30
        return '';
1832
    }
1833
1834
    /**
1835
     * 获取当前请求的安全Key
1836
     * @access public
1837
     * @return string
1838
     */
1839
    public function secureKey(): string
1840
    {
1841
        if (is_null($this->secureKey)) {
0 ignored issues
show
introduced by
The condition is_null($this->secureKey) is always false.
Loading history...
1842
            $this->secureKey = uniqid('', true);
1843
        }
1844
1845
        return $this->secureKey;
1846
    }
1847
1848
    /**
1849
     * 设置当前的控制器名
1850
     * @access public
1851
     * @param  string $controller 控制器名
1852
     * @return $this
1853
     */
1854 15
    public function setController(string $controller)
1855
    {
1856 15
        $this->controller = $controller;
1857 15
        return $this;
1858
    }
1859
1860
    /**
1861
     * 设置当前的操作名
1862
     * @access public
1863
     * @param  string $action 操作名
1864
     * @return $this
1865
     */
1866 15
    public function setAction(string $action)
1867
    {
1868 15
        $this->action = $action;
1869 15
        return $this;
1870
    }
1871
1872
    /**
1873
     * 获取当前的控制器名
1874
     * @access public
1875
     * @param  bool $convert 转换为小写
1876
     * @return string
1877
     */
1878
    public function controller(bool $convert = false): string
1879
    {
1880
        $name = $this->controller ?: '';
1881
        return $convert ? strtolower($name) : $name;
1882
    }
1883
1884
    /**
1885
     * 获取当前的操作名
1886
     * @access public
1887
     * @param  bool $convert 转换为小写
1888
     * @return string
1889
     */
1890 3
    public function action(bool $convert = false): string
1891
    {
1892 3
        $name = $this->action ?: '';
1893 3
        return $convert ? strtolower($name) : $name;
1894
    }
1895
1896
    /**
1897
     * 设置或者获取当前请求的content
1898
     * @access public
1899
     * @return string
1900
     */
1901
    public function getContent(): string
1902
    {
1903
        if (is_null($this->content)) {
0 ignored issues
show
introduced by
The condition is_null($this->content) is always false.
Loading history...
1904
            $this->content = $this->input;
1905
        }
1906
1907
        return $this->content;
1908
    }
1909
1910
    /**
1911
     * 获取当前请求的php://input
1912
     * @access public
1913
     * @return string
1914
     */
1915
    public function getInput(): string
1916
    {
1917
        return $this->input;
1918
    }
1919
1920
    /**
1921
     * 生成请求令牌
1922
     * @access public
1923
     * @param  string $name 令牌名称
1924
     * @param  mixed  $type 令牌生成方法
1925
     * @return string
1926
     */
1927
    public function buildToken(string $name = '__token__', $type = 'md5'): string
1928
    {
1929
        $type  = is_callable($type) ? $type : 'md5';
1930
        $token = call_user_func($type, $this->server('REQUEST_TIME_FLOAT'));
1931
1932
        $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

1932
        $this->session->/** @scrutinizer ignore-call */ 
1933
                        set($name, $token);
Loading history...
1933
1934
        return $token;
1935
    }
1936
1937
    /**
1938
     * 检查请求令牌
1939
     * @access public
1940
     * @param  string $token 令牌名称
1941
     * @param  array  $data  表单数据
1942
     * @return bool
1943
     */
1944
    public function checkToken(string $token = '__token__', array $data = []): bool
1945
    {
1946
        if (in_array($this->method(), ['GET', 'HEAD', 'OPTIONS'], true)) {
1947
            return true;
1948
        }
1949
1950
        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

1950
        if (!$this->session->/** @scrutinizer ignore-call */ has($token)) {
Loading history...
1951
            // 令牌数据无效
1952
            return false;
1953
        }
1954
1955
        // Header验证
1956
        if ($this->header('X-CSRF-TOKEN') && $this->session->get($token) === $this->header('X-CSRF-TOKEN')) {
1957
            // 防止重复提交
1958
            $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

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