Passed
Push — 6.0 ( 2749ab...de6c84 )
by liu
02:35
created

Request::setMethod()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 4
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 1
eloc 2
nc 1
nop 1
dl 0
loc 4
rs 10
c 0
b 0
f 0
1
<?php
2
// +----------------------------------------------------------------------
1 ignored issue
show
Coding Style introduced by
You must use "/**" style comments for a file comment
Loading history...
3
// | ThinkPHP [ WE CAN DO IT JUST THINK ]
4
// +----------------------------------------------------------------------
5
// | Copyright (c) 2006~2019 http://thinkphp.cn All rights reserved.
6
// +----------------------------------------------------------------------
7
// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
8
// +----------------------------------------------------------------------
9
// | Author: liu21st <[email protected]>
10
// +----------------------------------------------------------------------
11
declare (strict_types = 1);
12
13
namespace think;
14
15
use think\route\Dispatch;
16
17
class Request
1 ignored issue
show
Coding Style introduced by
Missing class doc comment
Loading history...
18
{
19
    /**
20
     * 配置
21
     * @var array
22
     */
23
    protected $config = [
24
        // PATHINFO变量名 用于兼容模式
25
        'var_pathinfo'           => 's',
26
        // 兼容PATH_INFO获取
27
        'pathinfo_fetch'         => ['ORIG_PATH_INFO', 'REDIRECT_PATH_INFO', 'REDIRECT_URL'],
28
        // 表单请求类型伪装变量
29
        'var_method'             => '_method',
30
        // 表单ajax伪装变量
31
        'var_ajax'               => '_ajax',
32
        // 表单pjax伪装变量
33
        'var_pjax'               => '_pjax',
34
        // 默认全局过滤方法 用逗号分隔多个
35
        'default_filter'         => '',
36
        // 域名根,如thinkphp.cn
37
        'url_domain_root'        => '',
38
        // HTTPS代理标识
39
        'https_agent_name'       => '',
40
        // 前端代理服务器IP
41
        'proxy_server_ip'        => [],
42
        // 前端代理服务器真实IP头
43
        'proxy_server_ip_header' => ['HTTP_X_REAL_IP', 'HTTP_X_FORWARDED_FOR', 'HTTP_CLIENT_IP', 'HTTP_X_CLIENT_IP', 'HTTP_X_CLUSTER_CLIENT_IP'],
44
        // URL伪静态后缀
45
        'url_html_suffix'        => 'html',
46
        // 是否开启请求缓存 true自动缓存 支持设置请求缓存规则
47
        'request_cache'          => false,
48
        // 请求缓存有效期
49
        'request_cache_expire'   => null,
50
        // 全局请求缓存排除规则
51
        'request_cache_except'   => [],
52
        // 请求缓存的Tag
53
        'request_cache_tag'      => '',
54
    ];
55
56
    /**
57
     * 请求类型
58
     * @var string
59
     */
60
    protected $method;
61
62
    /**
63
     * 域名(含协议及端口)
64
     * @var string
65
     */
66
    protected $domain;
67
68
    /**
69
     * HOST(含端口)
70
     * @var string
71
     */
72
    protected $host;
73
74
    /**
75
     * 子域名
76
     * @var string
77
     */
78
    protected $subDomain;
79
80
    /**
81
     * 泛域名
82
     * @var string
83
     */
84
    protected $panDomain;
85
86
    /**
87
     * 当前URL地址
88
     * @var string
89
     */
90
    protected $url;
91
92
    /**
93
     * 基础URL
94
     * @var string
95
     */
96
    protected $baseUrl;
97
98
    /**
99
     * 当前执行的文件
100
     * @var string
101
     */
102
    protected $baseFile;
103
104
    /**
105
     * 访问的ROOT地址
106
     * @var string
107
     */
108
    protected $root;
109
110
    /**
111
     * pathinfo
0 ignored issues
show
Coding Style introduced by
Doc comment short description must start with a capital letter
Loading history...
112
     * @var string
113
     */
114
    protected $pathinfo;
115
116
    /**
117
     * pathinfo(不含后缀)
0 ignored issues
show
Coding Style introduced by
Doc comment short description must start with a capital letter
Loading history...
118
     * @var string
119
     */
120
    protected $path;
121
122
    /**
123
     * 当前请求的IP地址
124
     * @var string
125
     */
126
    protected $realIP;
127
128
    /**
129
     * 当前路由信息
130
     * @var array
131
     */
132
    protected $routeInfo = [];
133
134
    /**
135
     * 当前调度信息
136
     * @var Dispatch
137
     */
138
    protected $dispatch;
139
140
    /**
141
     * 当前应用名
142
     * @var string
143
     */
144
    protected $app;
145
146
    /**
147
     * 当前控制器名
148
     * @var string
149
     */
150
    protected $controller;
151
152
    /**
153
     * 当前操作名
154
     * @var string
155
     */
156
    protected $action;
157
158
    /**
159
     * 当前语言集
160
     * @var string
161
     */
162
    protected $langset;
163
164
    /**
165
     * 当前请求参数
166
     * @var array
167
     */
168
    protected $param = [];
169
170
    /**
171
     * 当前GET参数
172
     * @var array
173
     */
174
    protected $get = [];
175
176
    /**
177
     * 当前POST参数
178
     * @var array
179
     */
180
    protected $post = [];
181
182
    /**
183
     * 当前REQUEST参数
184
     * @var array
185
     */
186
    protected $request = [];
187
188
    /**
189
     * 当前ROUTE参数
190
     * @var array
191
     */
192
    protected $route = [];
193
194
    /**
195
     * 中间件传递的参数
196
     * @var array
197
     */
198
    protected $middleware = [];
199
200
    /**
201
     * 当前PUT参数
202
     * @var array
203
     */
204
    protected $put;
205
206
    /**
207
     * SESSION对象
208
     * @var Session
209
     */
210
    protected $session;
211
212
    /**
213
     * COOKIE数据
214
     * @var array
215
     */
216
    protected $cookie = [];
217
218
    /**
219
     * ENV对象
220
     * @var Env
221
     */
222
    protected $env;
223
224
    /**
225
     * 当前SERVER参数
226
     * @var array
227
     */
228
    protected $server = [];
229
230
    /**
231
     * 当前FILE参数
232
     * @var array
233
     */
234
    protected $file = [];
235
236
    /**
237
     * 当前HEADER参数
238
     * @var array
239
     */
240
    protected $header = [];
241
242
    /**
243
     * 资源类型定义
244
     * @var array
245
     */
246
    protected $mimeType = [
247
        'xml'   => 'application/xml,text/xml,application/x-xml',
248
        'json'  => 'application/json,text/x-json,application/jsonrequest,text/json',
249
        'js'    => 'text/javascript,application/javascript,application/x-javascript',
250
        'css'   => 'text/css',
251
        'rss'   => 'application/rss+xml',
252
        'yaml'  => 'application/x-yaml,text/yaml',
253
        'atom'  => 'application/atom+xml',
254
        'pdf'   => 'application/pdf',
255
        'text'  => 'text/plain',
256
        'image' => 'image/png,image/jpg,image/jpeg,image/pjpeg,image/gif,image/webp,image/*',
257
        'csv'   => 'text/csv',
258
        'html'  => 'text/html,application/xhtml+xml,*/*',
259
    ];
260
261
    /**
262
     * 当前请求内容
263
     * @var string
264
     */
265
    protected $content;
266
267
    /**
268
     * 全局过滤规则
269
     * @var array
270
     */
271
    protected $filter;
272
273
    /**
274
     * php://input内容
0 ignored issues
show
Coding Style introduced by
Doc comment short description must start with a capital letter
Loading history...
275
     * @var string
276
     */
277
    // php://input
278
    protected $input;
279
280
    /**
281
     * 请求缓存
282
     * @var array
283
     */
284
    protected $cache;
285
286
    /**
287
     * 缓存是否检查
288
     * @var bool
289
     */
290
    protected $isCheckCache;
291
292
    /**
293
     * 请求安全Key
294
     * @var string
295
     */
296
    protected $secureKey;
297
298
    /**
299
     * 是否合并Param
300
     * @var bool
301
     */
302
    protected $mergeParam = false;
303
304
    /**
305
     * 架构函数
306
     * @access public
307
     * @param  array  $options 参数
308
     */
309
    public function __construct(array $options = [])
310
    {
311
        $this->init($options);
312
313
        // 保存 php://input
314
        $this->input = file_get_contents('php://input');
315
    }
316
317
    public function init(array $options = []): void
0 ignored issues
show
Coding Style introduced by
Missing function doc comment
Loading history...
318
    {
319
        $this->config = array_merge($this->config, $options);
320
321
        if (is_null($this->filter) && !empty($this->config['default_filter'])) {
0 ignored issues
show
introduced by
The condition is_null($this->filter) is always false.
Loading history...
322
            $this->filter = $this->config['default_filter'];
323
        }
324
    }
325
326
    public function config($name = null)
0 ignored issues
show
Coding Style introduced by
Missing function doc comment
Loading history...
327
    {
328
        if (is_null($name)) {
329
            return $this->config;
330
        }
331
332
        return $this->config[$name] ?? null;
333
    }
334
335
    public static function __make(App $app, Config $config)
1 ignored issue
show
Coding Style introduced by
Method name "Request::__make" is invalid; only PHP magic methods should be prefixed with a double underscore
Loading history...
Coding Style introduced by
Missing function doc comment
Loading history...
336
    {
337
        $request = new static($config->get('route'));
0 ignored issues
show
Bug introduced by
It seems like $config->get('route') can also be of type null; however, parameter $options of think\Request::__construct() 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

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

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