Completed
Push — 6.0 ( b80043...cd08ae )
by liu
02:38
created

Request::rootDomain()   A

Complexity

Conditions 3
Paths 3

Size

Total Lines 11
Code Lines 6

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 12

Importance

Changes 0
Metric Value
cc 3
eloc 6
nc 3
nop 0
dl 0
loc 11
ccs 0
cts 7
cp 0
crap 12
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 doc comment for class Request
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 array
161
     */
162
    protected $param = [];
163
164
    /**
165
     * 当前GET参数
166
     * @var array
167
     */
168
    protected $get = [];
169
170
    /**
171
     * 当前POST参数
172
     * @var array
173
     */
174
    protected $post = [];
175
176
    /**
177
     * 当前REQUEST参数
178
     * @var array
179
     */
180
    protected $request = [];
181
182
    /**
183
     * 当前ROUTE参数
184
     * @var array
185
     */
186
    protected $route = [];
187
188
    /**
189
     * 中间件传递的参数
190
     * @var array
191
     */
192
    protected $middleware = [];
193
194
    /**
195
     * 当前PUT参数
196
     * @var array
197
     */
198
    protected $put;
199
200
    /**
201
     * SESSION对象
202
     * @var Session
203
     */
204
    protected $session;
205
206
    /**
207
     * COOKIE数据
208
     * @var array
209
     */
210
    protected $cookie = [];
211
212
    /**
213
     * ENV对象
214
     * @var Env
215
     */
216
    protected $env;
217
218
    /**
219
     * 当前SERVER参数
220
     * @var array
221
     */
222
    protected $server = [];
223
224
    /**
225
     * 当前FILE参数
226
     * @var array
227
     */
228
    protected $file = [];
229
230
    /**
231
     * 当前HEADER参数
232
     * @var array
233
     */
234
    protected $header = [];
235
236
    /**
237
     * 资源类型定义
238
     * @var array
239
     */
240
    protected $mimeType = [
241
        'xml'   => 'application/xml,text/xml,application/x-xml',
242
        'json'  => 'application/json,text/x-json,application/jsonrequest,text/json',
243
        'js'    => 'text/javascript,application/javascript,application/x-javascript',
244
        'css'   => 'text/css',
245
        'rss'   => 'application/rss+xml',
246
        'yaml'  => 'application/x-yaml,text/yaml',
247
        'atom'  => 'application/atom+xml',
248
        'pdf'   => 'application/pdf',
249
        'text'  => 'text/plain',
250
        'image' => 'image/png,image/jpg,image/jpeg,image/pjpeg,image/gif,image/webp,image/*',
251
        'csv'   => 'text/csv',
252
        'html'  => 'text/html,application/xhtml+xml,*/*',
253
    ];
254
255
    /**
256
     * 当前请求内容
257
     * @var string
258
     */
259
    protected $content;
260
261
    /**
262
     * 全局过滤规则
263
     * @var array
264
     */
265
    protected $filter;
266
267
    /**
268
     * php://input内容
0 ignored issues
show
Coding Style introduced by
Doc comment short description must start with a capital letter
Loading history...
269
     * @var string
270
     */
271
    // php://input
272
    protected $input;
273
274
    /**
275
     * 请求缓存
276
     * @var array
277
     */
278
    protected $cache;
279
280
    /**
281
     * 缓存是否检查
282
     * @var bool
283
     */
284
    protected $isCheckCache;
285
286
    /**
287
     * 请求安全Key
288
     * @var string
289
     */
290
    protected $secureKey;
291
292
    /**
293
     * 是否合并Param
294
     * @var bool
295
     */
296
    protected $mergeParam = false;
297
298
    /**
299
     * 架构函数
300
     * @access public
301
     * @param  array  $options 参数
302
     */
303
    public function __construct(array $options = [])
304
    {
305
        $this->init($options);
306
307
        // 保存 php://input
308
        $this->input = file_get_contents('php://input');
309
    }
310
311
    public function init(array $options = []): void
0 ignored issues
show
Coding Style introduced by
Missing doc comment for function init()
Loading history...
312
    {
313
        $this->config = array_merge($this->config, $options);
314
315
        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...
316
            $this->filter = $this->config['default_filter'];
317
        }
318
    }
319
320
    public function config($name = null)
0 ignored issues
show
Coding Style introduced by
Missing doc comment for function config()
Loading history...
321
    {
322
        if (is_null($name)) {
323
            return $this->config;
324
        }
325
326
        return $this->config[$name] ?? null;
327
    }
328
329
    public static function __make(App $app, Config $config)
2 ignored issues
show
Coding Style introduced by
Missing doc comment for function __make()
Loading history...
Coding Style introduced by
Method name "Request::__make" is invalid; only PHP magic methods should be prefixed with a double underscore
Loading history...
Coding Style introduced by
Public method name "Request::__make" must not be prefixed with an underscore
Loading history...
330
    {
331
        $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

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

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