Completed
Push — 6.0 ( 487697...a3b118 )
by yun
08:06
created

Request   F

Complexity

Total Complexity 306

Size/Duplication

Total Lines 2139
Duplicated Lines 0 %

Test Coverage

Coverage 9.55%

Importance

Changes 15
Bugs 0 Features 0
Metric Value
eloc 609
dl 0
loc 2139
ccs 60
cts 628
cp 0.0955
rs 1.991
c 15
b 0
f 0
wmc 306

106 Methods

Rating   Name   Duplication   Size   Complexity  
A getInputData() 0 10 3
B dealUploadFile() 0 46 10
A isHead() 0 3 1
A mimeType() 0 6 2
A route() 0 7 2
A only() 0 21 5
A session() 0 7 2
A setMethod() 0 4 1
A isPut() 0 3 1
A throwUploadFileError() 0 13 1
B typeCast() 0 27 7
A setRoute() 0 4 1
A isOptions() 0 3 1
A rule() 0 3 1
A delete() 0 3 1
A request() 0 7 2
B file() 0 19 7
A except() 0 11 3
A isPost() 0 3 1
A env() 0 9 2
A filterData() 0 13 2
A post() 0 7 2
A getFilter() 0 16 5
A server() 0 9 2
A filter() 0 9 2
A isCli() 0 3 1
A getData() 0 11 3
A header() 0 9 2
A middleware() 0 3 1
B filterValue() 0 29 10
A cookie() 0 19 3
B isSsl() 0 15 9
A isGet() 0 3 1
A isPatch() 0 3 1
A setRule() 0 4 1
B param() 0 30 7
A isCgi() 0 3 1
B input() 0 33 8
A isDelete() 0 3 1
A time() 0 3 2
A ext() 0 3 1
A get() 0 7 2
A put() 0 7 2
A patch() 0 3 1
A getContent() 0 7 2
A protocol() 0 3 1
A withPost() 0 4 1
B isMobile() 0 13 9
A __set() 0 3 1
A contentType() 0 14 3
A withHeader() 0 4 1
A withMiddleware() 0 4 1
A withSession() 0 4 1
A withCookie() 0 4 1
A setController() 0 4 1
A app() 0 3 2
A setHost() 0 5 1
A isPjax() 0 9 4
A port() 0 3 1
A query() 0 3 1
A secureKey() 0 7 2
A withRoute() 0 4 1
A isAjax() 0 10 5
A withGet() 0 4 1
A withEnv() 0 4 1
A remotePort() 0 3 1
A controller() 0 4 3
A setApp() 0 4 1
C ip() 0 63 12
A __get() 0 3 1
A ip2bin() 0 17 4
A action() 0 4 3
A setAction() 0 4 1
A host() 0 9 5
A withInput() 0 4 1
A scheme() 0 3 2
A withServer() 0 4 1
A __isset() 0 3 1
A isValidIP() 0 15 3
A withFiles() 0 4 1
A getInput() 0 3 1
A rootUrl() 0 10 3
A baseUrl() 0 8 4
A rootDomain() 0 11 3
A setUrl() 0 4 1
A __construct() 0 4 1
A setBaseUrl() 0 4 1
A root() 0 11 5
A setRoot() 0 4 1
A panDomain() 0 3 2
A setPanDomain() 0 4 1
A setPathinfo() 0 4 1
A setDomain() 0 4 1
B url() 0 17 8
B baseFile() 0 22 10
A domain() 0 3 1
A setSubDomain() 0 4 1
B has() 0 22 8
B method() 0 23 8
A subDomain() 0 14 3
B __make() 0 35 8
C pathinfo() 0 33 13
A type() 0 18 5
A buildToken() 0 8 2
B checkToken() 0 32 8
A isJson() 0 5 1

How to fix   Complexity   

Complex Class

Complex classes like Request often do a lot of different things. To break such a class down, we need to identify a cohesive component within that class. A common approach to find such a component is to look for fields/methods that share the same prefixes, or suffixes.

Once you have determined the fields that belong together, you can apply the Extract Class refactoring. If the component makes sense as a sub-class, Extract Subclass is also a candidate, and is often faster.

While breaking up the class, it is a good idea to analyze how other classes use Request, and based on these observations, apply Extract Interface, too.

1
<?php
2
// +----------------------------------------------------------------------
3
// | ThinkPHP [ WE CAN DO IT JUST THINK ]
4
// +----------------------------------------------------------------------
5
// | Copyright (c) 2006~2019 http://thinkphp.cn All rights reserved.
6
// +----------------------------------------------------------------------
7
// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
8
// +----------------------------------------------------------------------
9
// | Author: liu21st <[email protected]>
10
// +----------------------------------------------------------------------
11
declare (strict_types = 1);
12
13
namespace think;
14
15
use think\file\UploadedFile;
16
use think\route\Rule;
17
18
/**
19
 * 请求管理类
20
 * @package think
0 ignored issues
show
Coding Style introduced by
Package name "think" is not valid; consider "Think" instead
Loading history...
21
 */
22
class Request
23
{
24
    /**
25
     * 兼容PATH_INFO获取
26
     * @var array
27
     */
28
    protected $pathinfoFetch = ['ORIG_PATH_INFO', 'REDIRECT_PATH_INFO', 'REDIRECT_URL'];
29
30
    /**
31
     * PATHINFO变量名 用于兼容模式
32
     * @var string
33
     */
34
    protected $varPathinfo = 's';
35
36
    /**
37
     * 请求类型
38
     * @var string
39
     */
40
    protected $varMethod = '_method';
41
42
    /**
43
     * 表单ajax伪装变量
44
     * @var string
45
     */
46
    protected $varAjax = '_ajax';
47
48
    /**
49
     * 表单pjax伪装变量
50
     * @var string
51
     */
52
    protected $varPjax = '_pjax';
53
54
    /**
55
     * 域名根
56
     * @var string
57
     */
58
    protected $rootDomain = '';
59
60
    /**
61
     * HTTPS代理标识
62
     * @var string
63
     */
64
    protected $httpsAgentName = '';
65
66
    /**
67
     * 前端代理服务器IP
68
     * @var array
69
     */
70
    protected $proxyServerIp = [];
71
72
    /**
73
     * 前端代理服务器真实IP头
74
     * @var array
75
     */
76
    protected $proxyServerIpHeader = ['HTTP_X_REAL_IP', 'HTTP_X_FORWARDED_FOR', 'HTTP_CLIENT_IP', 'HTTP_X_CLIENT_IP', 'HTTP_X_CLUSTER_CLIENT_IP'];
77
78
    /**
79
     * 请求类型
80
     * @var string
81
     */
82
    protected $method;
83
84
    /**
85
     * 域名(含协议及端口)
86
     * @var string
87
     */
88
    protected $domain;
89
90
    /**
91
     * HOST(含端口)
92
     * @var string
93
     */
94
    protected $host;
95
96
    /**
97
     * 子域名
98
     * @var string
99
     */
100
    protected $subDomain;
101
102
    /**
103
     * 泛域名
104
     * @var string
105
     */
106
    protected $panDomain;
107
108
    /**
109
     * 当前URL地址
110
     * @var string
111
     */
112
    protected $url;
113
114
    /**
115
     * 基础URL
116
     * @var string
117
     */
118
    protected $baseUrl;
119
120
    /**
121
     * 当前执行的文件
122
     * @var string
123
     */
124
    protected $baseFile;
125
126
    /**
127
     * 访问的ROOT地址
128
     * @var string
129
     */
130
    protected $root;
131
132
    /**
133
     * pathinfo
0 ignored issues
show
Coding Style introduced by
Doc comment short description must start with a capital letter
Loading history...
134
     * @var string
135
     */
136
    protected $pathinfo;
137
138
    /**
139
     * pathinfo(不含后缀)
0 ignored issues
show
Coding Style introduced by
Doc comment short description must start with a capital letter
Loading history...
140
     * @var string
141
     */
142
    protected $path;
143
144
    /**
145
     * 当前请求的IP地址
146
     * @var string
147
     */
148
    protected $realIP;
149
150
    /**
151
     * 当前应用名
152
     * @var string
153
     */
154
    protected $app;
155
156
    /**
157
     * 当前控制器名
158
     * @var string
159
     */
160
    protected $controller;
161
162
    /**
163
     * 当前操作名
164
     * @var string
165
     */
166
    protected $action;
167
168
    /**
169
     * 当前请求参数
170
     * @var array
171
     */
172
    protected $param = [];
173
174
    /**
175
     * 当前GET参数
176
     * @var array
177
     */
178
    protected $get = [];
179
180
    /**
181
     * 当前POST参数
182
     * @var array
183
     */
184
    protected $post = [];
185
186
    /**
187
     * 当前REQUEST参数
188
     * @var array
189
     */
190
    protected $request = [];
191
192
    /**
193
     * 当前路由对象
194
     * @var Rule
195
     */
196
    protected $rule;
197
198
    /**
199
     * 当前ROUTE参数
200
     * @var array
201
     */
202
    protected $route = [];
203
204
    /**
205
     * 中间件传递的参数
206
     * @var array
207
     */
208
    protected $middleware = [];
209
210
    /**
211
     * 当前PUT参数
212
     * @var array
213
     */
214
    protected $put;
215
216
    /**
217
     * SESSION对象
218
     * @var Session
219
     */
220
    protected $session;
221
222
    /**
223
     * COOKIE数据
224
     * @var array
225
     */
226
    protected $cookie = [];
227
228
    /**
229
     * ENV对象
230
     * @var Env
231
     */
232
    protected $env;
233
234
    /**
235
     * 当前SERVER参数
236
     * @var array
237
     */
238
    protected $server = [];
239
240
    /**
241
     * 当前FILE参数
242
     * @var array
243
     */
244
    protected $file = [];
245
246
    /**
247
     * 当前HEADER参数
248
     * @var array
249
     */
250
    protected $header = [];
251
252
    /**
253
     * 资源类型定义
254
     * @var array
255
     */
256
    protected $mimeType = [
257
        'xml'   => 'application/xml,text/xml,application/x-xml',
258
        'json'  => 'application/json,text/x-json,application/jsonrequest,text/json',
259
        'js'    => 'text/javascript,application/javascript,application/x-javascript',
260
        'css'   => 'text/css',
261
        'rss'   => 'application/rss+xml',
262
        'yaml'  => 'application/x-yaml,text/yaml',
263
        'atom'  => 'application/atom+xml',
264
        'pdf'   => 'application/pdf',
265
        'text'  => 'text/plain',
266
        'image' => 'image/png,image/jpg,image/jpeg,image/pjpeg,image/gif,image/webp,image/*',
267
        'csv'   => 'text/csv',
268
        'html'  => 'text/html,application/xhtml+xml,*/*',
269
    ];
270
271
    /**
272
     * 当前请求内容
273
     * @var string
274
     */
275
    protected $content;
276
277
    /**
278
     * 全局过滤规则
279
     * @var array
280
     */
281
    protected $filter;
282
283
    /**
284
     * php://input内容
0 ignored issues
show
Coding Style introduced by
Doc comment short description must start with a capital letter
Loading history...
285
     * @var string
286
     */
287
    // php://input
288
    protected $input;
289
290
    /**
291
     * 请求缓存
292
     * @var array
293
     */
294
    protected $cache;
295
296
    /**
297
     * 缓存是否检查
298
     * @var bool
299
     */
300
    protected $isCheckCache;
301
302
    /**
303
     * 请求安全Key
304
     * @var string
305
     */
306
    protected $secureKey;
307
308
    /**
309
     * 是否合并Param
310
     * @var bool
311
     */
312
    protected $mergeParam = false;
313
314
    /**
315
     * 架构函数
316
     * @access public
317
     */
318 7
    public function __construct()
319
    {
320
        // 保存 php://input
321 7
        $this->input = file_get_contents('php://input');
322 7
    }
323
324 7
    public static function __make(App $app)
0 ignored issues
show
Coding Style introduced by
Missing doc comment for function __make()
Loading history...
325
    {
326 7
        $request = new static();
327
328 7
        $request->server  = $_SERVER;
329 7
        $request->env     = $app->env;
330 7
        $request->get     = $_GET;
331 7
        $request->post    = $_POST ?: $request->getInputData($request->input);
332 7
        $request->put     = $request->getInputData($request->input);
333 7
        $request->request = $_REQUEST;
334 7
        $request->cookie  = $_COOKIE;
335 7
        $request->file    = $_FILES ?? [];
336
337 7
        if (function_exists('apache_request_headers') && $result = apache_request_headers()) {
338
            $header = $result;
339
        } else {
340 7
            $header = [];
341 7
            $server = $_SERVER;
342 7
            foreach ($server as $key => $val) {
343 7
                if (0 === strpos($key, 'HTTP_')) {
344
                    $key          = str_replace('_', '-', strtolower(substr($key, 5)));
345
                    $header[$key] = $val;
346
                }
347
            }
348 7
            if (isset($server['CONTENT_TYPE'])) {
349
                $header['content-type'] = $server['CONTENT_TYPE'];
350
            }
351 7
            if (isset($server['CONTENT_LENGTH'])) {
352
                $header['content-length'] = $server['CONTENT_LENGTH'];
353
            }
354
        }
355
356 7
        $request->header = array_change_key_case($header);
357
358 7
        return $request;
359
    }
360
361
    /**
362
     * 设置当前包含协议的域名
363
     * @access public
364
     * @param  string $domain 域名
365
     * @return $this
366
     */
367
    public function setDomain(string $domain)
368
    {
369
        $this->domain = $domain;
370
        return $this;
371
    }
372
373
    /**
374
     * 获取当前包含协议的域名
375
     * @access public
376
     * @param  bool $port 是否需要去除端口号
377
     * @return string
378
     */
379
    public function domain(bool $port = false): string
380
    {
381
        return $this->scheme() . '://' . $this->host($port);
382
    }
383
384
    /**
385
     * 获取当前根域名
386
     * @access public
387
     * @return string
388
     */
389 3
    public function rootDomain(): string
390
    {
391 3
        $root = $this->rootDomain;
392
393 3
        if (!$root) {
394 3
            $item  = explode('.', $this->host());
395 3
            $count = count($item);
396 3
            $root  = $count > 1 ? $item[$count - 2] . '.' . $item[$count - 1] : $item[0];
397
        }
398
399 3
        return $root;
400
    }
401
402
    /**
403
     * 设置当前泛域名的值
404
     * @access public
405
     * @param  string $domain 域名
406
     * @return $this
407
     */
408
    public function setSubDomain(string $domain)
409
    {
410
        $this->subDomain = $domain;
411
        return $this;
412
    }
413
414
    /**
415
     * 获取当前子域名
416
     * @access public
417
     * @return string
418
     */
419 3
    public function subDomain(): string
420
    {
421 3
        if (is_null($this->subDomain)) {
0 ignored issues
show
introduced by
The condition is_null($this->subDomain) is always false.
Loading history...
422
            // 获取当前主域名
423 3
            $rootDomain = $this->rootDomain();
424
425 3
            if ($rootDomain) {
426
                $this->subDomain = rtrim(stristr($this->host(), $rootDomain, true), '.');
427
            } else {
428 3
                $this->subDomain = '';
429
            }
430
        }
431
432 3
        return $this->subDomain;
433
    }
434
435
    /**
436
     * 设置当前泛域名的值
437
     * @access public
438
     * @param  string $domain 域名
439
     * @return $this
440
     */
441
    public function setPanDomain(string $domain)
442
    {
443
        $this->panDomain = $domain;
444
        return $this;
445
    }
446
447
    /**
448
     * 获取当前泛域名的值
449
     * @access public
450
     * @return string
451
     */
452
    public function panDomain(): string
453
    {
454
        return $this->panDomain ?: '';
455
    }
456
457
    /**
458
     * 设置当前完整URL 包括QUERY_STRING
459
     * @access public
460
     * @param  string $url URL地址
461
     * @return $this
462
     */
463
    public function setUrl(string $url)
464
    {
465
        $this->url = $url;
466
        return $this;
467
    }
468
469
    /**
470
     * 获取当前完整URL 包括QUERY_STRING
471
     * @access public
472
     * @param  bool $complete 是否包含完整域名
473
     * @return string
474
     */
475
    public function url(bool $complete = false): string
476
    {
477
        if ($this->url) {
478
            $url = $this->url;
479
        } elseif ($this->server('HTTP_X_REWRITE_URL')) {
480
            $url = $this->server('HTTP_X_REWRITE_URL');
481
        } elseif ($this->server('REQUEST_URI')) {
482
            $url = $this->server('REQUEST_URI');
483
        } elseif ($this->server('ORIG_PATH_INFO')) {
484
            $url = $this->server('ORIG_PATH_INFO') . (!empty($this->server('QUERY_STRING')) ? '?' . $this->server('QUERY_STRING') : '');
485
        } elseif (isset($_SERVER['argv'][1])) {
486
            $url = $_SERVER['argv'][1];
487
        } else {
488
            $url = '';
489
        }
490
491
        return $complete ? $this->domain() . $url : $url;
492
    }
493
494
    /**
495
     * 设置当前URL 不含QUERY_STRING
496
     * @access public
497
     * @param  string $url URL地址
498
     * @return $this
499
     */
500
    public function setBaseUrl(string $url)
501
    {
502
        $this->baseUrl = $url;
503
        return $this;
504
    }
505
506
    /**
507
     * 获取当前URL 不含QUERY_STRING
508
     * @access public
509
     * @param  bool $complete 是否包含完整域名
510
     * @return string
511
     */
512
    public function baseUrl(bool $complete = false): string
513
    {
514
        if (!$this->baseUrl) {
515
            $str           = $this->url();
516
            $this->baseUrl = strpos($str, '?') ? strstr($str, '?', true) : $str;
517
        }
518
519
        return $complete ? $this->domain() . $this->baseUrl : $this->baseUrl;
520
    }
521
522
    /**
523
     * 获取当前执行的文件 SCRIPT_NAME
524
     * @access public
525
     * @param  bool $complete 是否包含完整域名
526
     * @return string
527
     */
528
    public function baseFile(bool $complete = false): string
529
    {
530
        if (!$this->baseFile) {
531
            $url = '';
532
            if (!$this->isCli()) {
533
                $script_name = basename($this->server('SCRIPT_FILENAME'));
534
                if (basename($this->server('SCRIPT_NAME')) === $script_name) {
535
                    $url = $this->server('SCRIPT_NAME');
536
                } elseif (basename($this->server('PHP_SELF')) === $script_name) {
537
                    $url = $this->server('PHP_SELF');
538
                } elseif (basename($this->server('ORIG_SCRIPT_NAME')) === $script_name) {
539
                    $url = $this->server('ORIG_SCRIPT_NAME');
540
                } elseif (($pos = strpos($this->server('PHP_SELF'), '/' . $script_name)) !== false) {
541
                    $url = substr($this->server('SCRIPT_NAME'), 0, $pos) . '/' . $script_name;
542
                } elseif ($this->server('DOCUMENT_ROOT') && strpos($this->server('SCRIPT_FILENAME'), $this->server('DOCUMENT_ROOT')) === 0) {
543
                    $url = str_replace('\\', '/', str_replace($this->server('DOCUMENT_ROOT'), '', $this->server('SCRIPT_FILENAME')));
544
                }
545
            }
546
            $this->baseFile = $url;
547
        }
548
549
        return $complete ? $this->domain() . $this->baseFile : $this->baseFile;
550
    }
551
552
    /**
553
     * 设置URL访问根地址
554
     * @access public
555
     * @param  string $url URL地址
556
     * @return $this
557
     */
558 2
    public function setRoot(string $url)
559
    {
560 2
        $this->root = $url;
561 2
        return $this;
562
    }
563
564
    /**
565
     * 获取URL访问根地址
566
     * @access public
567
     * @param  bool $complete 是否包含完整域名
568
     * @return string
569
     */
570
    public function root(bool $complete = false): string
571
    {
572
        if (!$this->root) {
573
            $file = $this->baseFile();
574
            if ($file && 0 !== strpos($this->url(), $file)) {
575
                $file = str_replace('\\', '/', dirname($file));
576
            }
577
            $this->root = rtrim($file, '/');
578
        }
579
580
        return $complete ? $this->domain() . $this->root : $this->root;
581
    }
582
583
    /**
584
     * 获取URL访问根目录
585
     * @access public
586
     * @return string
587
     */
588
    public function rootUrl(): string
589
    {
590
        $base = $this->root();
591
        $root = strpos($base, '.') ? ltrim(dirname($base), DIRECTORY_SEPARATOR) : $base;
592
593
        if ('' != $root) {
594
            $root = '/' . ltrim($root, '/');
595
        }
596
597
        return $root;
598
    }
599
600
    /**
601
     * 设置当前请求的pathinfo
602
     * @access public
603
     * @param  string $pathinfo
0 ignored issues
show
Coding Style introduced by
Missing parameter comment
Loading history...
604
     * @return $this
605
     */
606 2
    public function setPathinfo(string $pathinfo)
607
    {
608 2
        $this->pathinfo = $pathinfo;
609 2
        return $this;
610
    }
611
612
    /**
613
     * 获取当前请求URL的pathinfo信息(含URL后缀)
614
     * @access public
615
     * @return string
616
     */
617
    public function pathinfo(): string
618
    {
619
        if (is_null($this->pathinfo)) {
0 ignored issues
show
introduced by
The condition is_null($this->pathinfo) is always false.
Loading history...
620
            if (isset($_GET[$this->varPathinfo])) {
621
                // 判断URL里面是否有兼容模式参数
622
                $pathinfo = $_GET[$this->varPathinfo];
623
                unset($_GET[$this->varPathinfo]);
624
                unset($this->get[$this->varPathinfo]);
625
            } elseif ($this->server('PATH_INFO')) {
626
                $pathinfo = $this->server('PATH_INFO');
627
            } elseif (false !== strpos(PHP_SAPI, 'cli')) {
628
                $pathinfo = strpos($this->server('REQUEST_URI'), '?') ? strstr($this->server('REQUEST_URI'), '?', true) : $this->server('REQUEST_URI');
629
            }
630
631
            // 分析PATHINFO信息
632
            if (!isset($pathinfo)) {
633
                foreach ($this->pathinfoFetch as $type) {
634
                    if ($this->server($type)) {
635
                        $pathinfo = (0 === strpos($this->server($type), $this->server('SCRIPT_NAME'))) ?
636
                        substr($this->server($type), strlen($this->server('SCRIPT_NAME'))) : $this->server($type);
637
                        break;
638
                    }
639
                }
640
            }
641
642
            if (!empty($pathinfo)) {
643
                unset($this->get[$pathinfo], $this->request[$pathinfo]);
644
            }
645
646
            $this->pathinfo = empty($pathinfo) || '/' == $pathinfo ? '' : ltrim($pathinfo, '/');
647
        }
648
649
        return $this->pathinfo;
650
    }
651
652
    /**
653
     * 当前URL的访问后缀
654
     * @access public
655
     * @return string
656
     */
657
    public function ext(): string
658
    {
659
        return pathinfo($this->pathinfo(), PATHINFO_EXTENSION);
660
    }
661
662
    /**
663
     * 获取当前请求的时间
664
     * @access public
665
     * @param  bool $float 是否使用浮点类型
666
     * @return integer|float
667
     */
668
    public function time(bool $float = false)
669
    {
670
        return $float ? $this->server('REQUEST_TIME_FLOAT') : $this->server('REQUEST_TIME');
0 ignored issues
show
Bug Best Practice introduced by
The expression return $float ? $this->s...>server('REQUEST_TIME') also could return the type string which is incompatible with the documented return type double|integer.
Loading history...
671
    }
672
673
    /**
674
     * 当前请求的资源类型
675
     * @access public
676
     * @return string
677
     */
678
    public function type(): string
679
    {
680
        $accept = $this->server('HTTP_ACCEPT');
681
682
        if (empty($accept)) {
683
            return '';
684
        }
685
686
        foreach ($this->mimeType as $key => $val) {
687
            $array = explode(',', $val);
688
            foreach ($array as $k => $v) {
689
                if (stristr($accept, $v)) {
690
                    return $key;
691
                }
692
            }
693
        }
694
695
        return '';
696
    }
697
698
    /**
699
     * 设置资源类型
700
     * @access public
701
     * @param  string|array $type 资源类型名
702
     * @param  string       $val 资源类型
0 ignored issues
show
Coding Style introduced by
Expected 2 spaces after parameter name; 1 found
Loading history...
703
     * @return void
704
     */
705
    public function mimeType($type, $val = ''): void
706
    {
707
        if (is_array($type)) {
708
            $this->mimeType = array_merge($this->mimeType, $type);
709
        } else {
710
            $this->mimeType[$type] = $val;
711
        }
712
    }
713
714
    /**
715
     * 设置请求类型
716
     * @access public
717
     * @param  string $method 请求类型
718
     * @return $this
719
     */
720
    public function setMethod(string $method)
721
    {
722
        $this->method = strtoupper($method);
723
        return $this;
724
    }
725
726
    /**
727
     * 当前的请求类型
728
     * @access public
729
     * @param  bool $origin 是否获取原始请求类型
730
     * @return string
731
     */
732
    public function method(bool $origin = false): string
733
    {
734
        if ($origin) {
735
            // 获取原始请求类型
736
            return $this->server('REQUEST_METHOD') ?: 'GET';
737
        } elseif (!$this->method) {
738
            if (isset($this->post[$this->varMethod])) {
739
                $method = strtolower($this->post[$this->varMethod]);
740
                if (in_array($method, ['get', 'post', 'put', 'patch', 'delete'])) {
741
                    $this->method    = strtoupper($method);
742
                    $this->{$method} = $this->post;
743
                } else {
744
                    $this->method = 'POST';
745
                }
746
                unset($this->post[$this->varMethod]);
747
            } elseif ($this->server('HTTP_X_HTTP_METHOD_OVERRIDE')) {
748
                $this->method = strtoupper($this->server('HTTP_X_HTTP_METHOD_OVERRIDE'));
749
            } else {
750
                $this->method = $this->server('REQUEST_METHOD') ?: 'GET';
751
            }
752
        }
753
754
        return $this->method;
755
    }
756
757
    /**
758
     * 是否为GET请求
759
     * @access public
760
     * @return bool
761
     */
762
    public function isGet(): bool
763
    {
764
        return $this->method() == 'GET';
765
    }
766
767
    /**
768
     * 是否为POST请求
769
     * @access public
770
     * @return bool
771
     */
772
    public function isPost(): bool
773
    {
774
        return $this->method() == 'POST';
775
    }
776
777
    /**
778
     * 是否为PUT请求
779
     * @access public
780
     * @return bool
781
     */
782
    public function isPut(): bool
783
    {
784
        return $this->method() == 'PUT';
785
    }
786
787
    /**
788
     * 是否为DELTE请求
789
     * @access public
790
     * @return bool
791
     */
792
    public function isDelete(): bool
793
    {
794
        return $this->method() == 'DELETE';
795
    }
796
797
    /**
798
     * 是否为HEAD请求
799
     * @access public
800
     * @return bool
801
     */
802
    public function isHead(): bool
803
    {
804
        return $this->method() == 'HEAD';
805
    }
806
807
    /**
808
     * 是否为PATCH请求
809
     * @access public
810
     * @return bool
811
     */
812
    public function isPatch(): bool
813
    {
814
        return $this->method() == 'PATCH';
815
    }
816
817
    /**
818
     * 是否为OPTIONS请求
819
     * @access public
820
     * @return bool
821
     */
822
    public function isOptions(): bool
823
    {
824
        return $this->method() == 'OPTIONS';
825
    }
826
827
    /**
828
     * 是否为cli
829
     * @access public
830
     * @return bool
831
     */
832
    public function isCli(): bool
833
    {
834
        return PHP_SAPI == 'cli';
835
    }
836
837
    /**
838
     * 是否为cgi
839
     * @access public
840
     * @return bool
841
     */
842
    public function isCgi(): bool
843
    {
844
        return strpos(PHP_SAPI, 'cgi') === 0;
845
    }
846
847
    /**
848
     * 获取当前请求的参数
849
     * @access public
850
     * @param  string|array $name 变量名
0 ignored issues
show
Coding Style introduced by
Expected 4 spaces after parameter name; 1 found
Loading history...
851
     * @param  mixed        $default 默认值
852
     * @param  string|array $filter 过滤方法
0 ignored issues
show
Coding Style introduced by
Expected 2 spaces after parameter name; 1 found
Loading history...
853
     * @return mixed
854
     */
855
    public function param($name = '', $default = null, $filter = '')
856
    {
857
        if (empty($this->mergeParam)) {
858
            $method = $this->method(true);
859
860
            // 自动获取请求变量
861
            switch ($method) {
862
                case 'POST':
863
                    $vars = $this->post(false);
864
                    break;
865
                case 'PUT':
866
                case 'DELETE':
867
                case 'PATCH':
868
                    $vars = $this->put(false);
869
                    break;
870
                default:
871
                    $vars = [];
872
            }
873
874
            // 当前请求参数和URL地址中的参数合并
875
            $this->param = array_merge($this->param, $this->get(false), $vars, $this->route(false));
876
877
            $this->mergeParam = true;
878
        }
879
880
        if (is_array($name)) {
881
            return $this->only($name, $this->param, $filter);
882
        }
883
884
        return $this->input($this->param, $name, $default, $filter);
885
    }
886
887
    /**
888
     * 设置路由变量
889
     * @access public
890
     * @param  Rule $rule 路由对象
891
     * @return $this
892
     */
893
    public function setRule(Rule $rule)
894
    {
895
        $this->rule = $rule;
896
        return $this;
897
    }
898
899
    /**
900
     * 获取当前路由对象
901
     * @access public
902
     * @return Rule|null
903
     */
904
    public function rule()
905
    {
906
        return $this->rule;
907
    }
908
909
    /**
910
     * 设置路由变量
911
     * @access public
912
     * @param  array $route 路由变量
913
     * @return $this
914
     */
915
    public function setRoute(array $route)
916
    {
917
        $this->route = array_merge($this->route, $route);
918
        return $this;
919
    }
920
921
    /**
922
     * 获取路由参数
923
     * @access public
924
     * @param  mixed        $name 变量名
0 ignored issues
show
Coding Style introduced by
Expected 4 spaces after parameter name; 1 found
Loading history...
925
     * @param  mixed        $default 默认值
926
     * @param  string|array $filter 过滤方法
0 ignored issues
show
Coding Style introduced by
Expected 2 spaces after parameter name; 1 found
Loading history...
927
     * @return mixed
928
     */
929
    public function route($name = '', $default = null, $filter = '')
930
    {
931
        if (is_array($name)) {
932
            return $this->only($name, $this->route, $filter);
933
        }
934
935
        return $this->input($this->route, $name, $default, $filter);
936
    }
937
938
    /**
939
     * 获取GET参数
940
     * @access public
941
     * @param  mixed        $name 变量名
0 ignored issues
show
Coding Style introduced by
Expected 4 spaces after parameter name; 1 found
Loading history...
942
     * @param  mixed        $default 默认值
943
     * @param  string|array $filter 过滤方法
0 ignored issues
show
Coding Style introduced by
Expected 2 spaces after parameter name; 1 found
Loading history...
944
     * @return mixed
945
     */
946
    public function get($name = '', $default = null, $filter = '')
947
    {
948
        if (is_array($name)) {
949
            return $this->only($name, $this->get, $filter);
950
        }
951
952
        return $this->input($this->get, $name, $default, $filter);
953
    }
954
955
    /**
956
     * 获取中间件传递的参数
957
     * @access public
958
     * @param  mixed $name 变量名
0 ignored issues
show
Coding Style introduced by
Expected 4 spaces after parameter name; 1 found
Loading history...
959
     * @param  mixed $default 默认值
960
     * @return mixed
961
     */
962
    public function middleware($name, $default = null)
963
    {
964
        return $this->middleware[$name] ?? $default;
965
    }
966
967
    /**
968
     * 获取POST参数
969
     * @access public
970
     * @param  mixed        $name 变量名
0 ignored issues
show
Coding Style introduced by
Expected 4 spaces after parameter name; 1 found
Loading history...
971
     * @param  mixed        $default 默认值
972
     * @param  string|array $filter 过滤方法
0 ignored issues
show
Coding Style introduced by
Expected 2 spaces after parameter name; 1 found
Loading history...
973
     * @return mixed
974
     */
975
    public function post($name = '', $default = null, $filter = '')
976
    {
977
        if (is_array($name)) {
978
            return $this->only($name, $this->post, $filter);
979
        }
980
981
        return $this->input($this->post, $name, $default, $filter);
982
    }
983
984
    /**
985
     * 获取PUT参数
986
     * @access public
987
     * @param  mixed        $name 变量名
0 ignored issues
show
Coding Style introduced by
Expected 4 spaces after parameter name; 1 found
Loading history...
988
     * @param  mixed        $default 默认值
989
     * @param  string|array $filter 过滤方法
0 ignored issues
show
Coding Style introduced by
Expected 2 spaces after parameter name; 1 found
Loading history...
990
     * @return mixed
991
     */
992
    public function put($name = '', $default = null, $filter = '')
993
    {
994
        if (is_array($name)) {
995
            return $this->only($name, $this->put, $filter);
996
        }
997
998
        return $this->input($this->put, $name, $default, $filter);
999
    }
1000
1001 7
    protected function getInputData($content): array
0 ignored issues
show
Coding Style introduced by
Missing doc comment for function getInputData()
Loading history...
1002
    {
1003 7
        if (false !== strpos($this->contentType(), 'json')) {
1004
            return (array) json_decode($content, true);
1005 7
        } elseif (strpos($content, '=')) {
1006
            parse_str($content, $data);
1007
            return $data;
1008
        }
1009
1010 7
        return [];
1011
    }
1012
1013
    /**
1014
     * 设置获取DELETE参数
1015
     * @access public
1016
     * @param  mixed        $name 变量名
0 ignored issues
show
Coding Style introduced by
Expected 4 spaces after parameter name; 1 found
Loading history...
1017
     * @param  mixed        $default 默认值
1018
     * @param  string|array $filter 过滤方法
0 ignored issues
show
Coding Style introduced by
Expected 2 spaces after parameter name; 1 found
Loading history...
1019
     * @return mixed
1020
     */
1021
    public function delete($name = '', $default = null, $filter = '')
1022
    {
1023
        return $this->put($name, $default, $filter);
1024
    }
1025
1026
    /**
1027
     * 设置获取PATCH参数
1028
     * @access public
1029
     * @param  mixed        $name 变量名
0 ignored issues
show
Coding Style introduced by
Expected 4 spaces after parameter name; 1 found
Loading history...
1030
     * @param  mixed        $default 默认值
1031
     * @param  string|array $filter 过滤方法
0 ignored issues
show
Coding Style introduced by
Expected 2 spaces after parameter name; 1 found
Loading history...
1032
     * @return mixed
1033
     */
1034
    public function patch($name = '', $default = null, $filter = '')
1035
    {
1036
        return $this->put($name, $default, $filter);
1037
    }
1038
1039
    /**
1040
     * 获取request变量
1041
     * @access public
1042
     * @param  mixed        $name 数据名称
0 ignored issues
show
Coding Style introduced by
Expected 4 spaces after parameter name; 1 found
Loading history...
1043
     * @param  mixed        $default 默认值
1044
     * @param  string|array $filter 过滤方法
0 ignored issues
show
Coding Style introduced by
Expected 2 spaces after parameter name; 1 found
Loading history...
1045
     * @return mixed
1046
     */
1047
    public function request($name = '', $default = null, $filter = '')
1048
    {
1049
        if (is_array($name)) {
1050
            return $this->only($name, $this->request, $filter);
1051
        }
1052
1053
        return $this->input($this->request, $name, $default, $filter);
1054
    }
1055
1056
    /**
1057
     * 获取环境变量
1058
     * @access public
1059
     * @param  string $name 数据名称
0 ignored issues
show
Coding Style introduced by
Expected 4 spaces after parameter name; 1 found
Loading history...
1060
     * @param  string $default 默认值
1061
     * @return mixed
1062
     */
1063
    public function env(string $name = '', string $default = null)
1064
    {
1065
        if (empty($name)) {
1066
            return $this->env->get();
1067
        } else {
1068
            $name = strtoupper($name);
1069
        }
1070
1071
        return $this->env->get($name, $default);
1072
    }
1073
1074
    /**
1075
     * 获取session数据
1076
     * @access public
1077
     * @param  string $name 数据名称
0 ignored issues
show
Coding Style introduced by
Expected 4 spaces after parameter name; 1 found
Loading history...
1078
     * @param  string $default 默认值
1079
     * @return mixed
1080
     */
1081
    public function session(string $name = '', $default = null)
1082
    {
1083
        if ('' === $name) {
1084
            return $this->session->get();
1085
        }
1086
1087
        return $this->getData($this->session->get(), $name, $default);
1088
    }
1089
1090
    /**
1091
     * 获取cookie参数
1092
     * @access public
1093
     * @param  mixed        $name 数据名称
0 ignored issues
show
Coding Style introduced by
Expected 4 spaces after parameter name; 1 found
Loading history...
1094
     * @param  string       $default 默认值
1095
     * @param  string|array $filter 过滤方法
0 ignored issues
show
Coding Style introduced by
Expected 2 spaces after parameter name; 1 found
Loading history...
1096
     * @return mixed
1097
     */
1098
    public function cookie(string $name = '', $default = null, $filter = '')
1099
    {
1100
        if (!empty($name)) {
1101
            $data = $this->getData($this->cookie, $name, $default);
1102
        } else {
1103
            $data = $this->cookie;
1104
        }
1105
1106
        // 解析过滤器
1107
        $filter = $this->getFilter($filter, $default);
1108
1109
        if (is_array($data)) {
1110
            array_walk_recursive($data, [$this, 'filterValue'], $filter);
1111
            reset($data);
1112
        } else {
1113
            $this->filterValue($data, $name, $filter);
1114
        }
1115
1116
        return $data;
1117
    }
1118
1119
    /**
1120
     * 获取server参数
1121
     * @access public
1122
     * @param  string $name 数据名称
0 ignored issues
show
Coding Style introduced by
Expected 4 spaces after parameter name; 1 found
Loading history...
1123
     * @param  string $default 默认值
1124
     * @return mixed
1125
     */
1126 8
    public function server(string $name = '', string $default = '')
1127
    {
1128 8
        if (empty($name)) {
1129
            return $this->server;
1130
        } else {
1131 8
            $name = strtoupper($name);
1132
        }
1133
1134 8
        return $this->server[$name] ?? $default;
1135
    }
1136
1137
    /**
1138
     * 获取上传的文件信息
1139
     * @access public
1140
     * @param  string $name 名称
1141
     * @return null|array|UploadedFile
1142
     */
1143
    public function file(string $name = '')
1144
    {
1145
        $files = $this->file;
1146
        if (!empty($files)) {
1147
1148
            if (strpos($name, '.')) {
1149
                list($name, $sub) = explode('.', $name);
1150
            }
1151
1152
            // 处理上传文件
1153
            $array = $this->dealUploadFile($files, $name);
1154
1155
            if ('' === $name) {
1156
                // 获取全部文件
1157
                return $array;
1158
            } elseif (isset($sub) && isset($array[$name][$sub])) {
1159
                return $array[$name][$sub];
1160
            } elseif (isset($array[$name])) {
1161
                return $array[$name];
1162
            }
1163
        }
1164
    }
1165
1166
    protected function dealUploadFile(array $files, string $name): array
0 ignored issues
show
Coding Style introduced by
Missing doc comment for function dealUploadFile()
Loading history...
1167
    {
1168
        $array = [];
1169
        foreach ($files as $key => $file) {
1170
            if (is_array($file['name'])) {
1171
                $item  = [];
1172
                $keys  = array_keys($file);
1173
                $count = count($file['name']);
1174
1175
                for ($i = 0; $i < $count; $i++) {
1176
                    if ($file['error'][$i] > 0) {
1177
                        if ($name == $key) {
1178
                            $this->throwUploadFileError($file['error'][$i]);
1179
                        } else {
1180
                            continue;
1181
                        }
1182
                    }
1183
1184
                    $temp['key'] = $key;
1185
1186
                    foreach ($keys as $_key) {
1187
                        $temp[$_key] = $file[$_key][$i];
1188
                    }
1189
1190
                    $item[] = new UploadedFile($temp['tmp_name'], $temp['name'], $temp['type'], $temp['error']);
1191
                }
1192
1193
                $array[$key] = $item;
1194
            } else {
1195
                if ($file instanceof File) {
1196
                    $array[$key] = $file;
1197
                } else {
1198
                    if ($file['error'] > 0) {
1199
                        if ($key == $name) {
1200
                            $this->throwUploadFileError($file['error']);
1201
                        } else {
1202
                            continue;
1203
                        }
1204
                    }
1205
1206
                    $array[$key] = new UploadedFile($file['tmp_name'], $file['name'], $file['type'], $file['error']);
1207
                }
1208
            }
1209
        }
1210
1211
        return $array;
1212
    }
1213
1214
    protected function throwUploadFileError($error)
0 ignored issues
show
Coding Style introduced by
Missing doc comment for function throwUploadFileError()
Loading history...
1215
    {
1216
        static $fileUploadErrors = [
1217
            1 => 'upload File size exceeds the maximum value',
1218
            2 => 'upload File size exceeds the maximum value',
1219
            3 => 'only the portion of file is uploaded',
1220
            4 => 'no file to uploaded',
1221
            6 => 'upload temp dir not found',
1222
            7 => 'file write error',
1223
        ];
1224
1225
        $msg = $fileUploadErrors[$error];
1226
        throw new Exception($msg, $error);
1227
    }
1228
1229
    /**
1230
     * 设置或者获取当前的Header
1231
     * @access public
1232
     * @param  string $name header名称
0 ignored issues
show
Coding Style introduced by
Expected 4 spaces after parameter name; 1 found
Loading history...
1233
     * @param  string $default 默认值
1234
     * @return string|array
1235
     */
1236
    public function header(string $name = '', string $default = null)
1237
    {
1238
        if ('' === $name) {
1239
            return $this->header;
1240
        }
1241
1242
        $name = str_replace('_', '-', strtolower($name));
1243
1244
        return $this->header[$name] ?? $default;
1245
    }
1246
1247
    /**
1248
     * 获取变量 支持过滤和默认值
1249
     * @access public
1250
     * @param  array        $data 数据源
0 ignored issues
show
Coding Style introduced by
Expected 4 spaces after parameter name; 1 found
Loading history...
1251
     * @param  string|false $name 字段名
0 ignored issues
show
Coding Style introduced by
Expected 4 spaces after parameter name; 1 found
Loading history...
1252
     * @param  mixed        $default 默认值
1253
     * @param  string|array $filter 过滤函数
0 ignored issues
show
Coding Style introduced by
Expected 2 spaces after parameter name; 1 found
Loading history...
1254
     * @return mixed
1255
     */
1256
    public function input(array $data = [], $name = '', $default = null, $filter = '')
1257
    {
1258
        if (false === $name) {
1259
            // 获取原始数据
1260
            return $data;
1261
        }
1262
1263
        $name = (string) $name;
1264
        if ('' != $name) {
1265
            // 解析name
1266
            if (strpos($name, '/')) {
1267
                list($name, $type) = explode('/', $name);
1268
            }
1269
1270
            $data = $this->getData($data, $name);
1271
1272
            if (is_null($data)) {
1273
                return $default;
1274
            }
1275
1276
            if (is_object($data)) {
1277
                return $data;
1278
            }
1279
        }
1280
1281
        $data = $this->filterData($data, $filter, $name, $default);
1282
1283
        if (isset($type) && $data !== $default) {
1284
            // 强制类型转换
1285
            $this->typeCast($data, $type);
1286
        }
1287
1288
        return $data;
1289
    }
1290
1291
    protected function filterData($data, $filter, $name, $default)
0 ignored issues
show
Coding Style introduced by
Missing doc comment for function filterData()
Loading history...
1292
    {
1293
        // 解析过滤器
1294
        $filter = $this->getFilter($filter, $default);
1295
1296
        if (is_array($data)) {
1297
            array_walk_recursive($data, [$this, 'filterValue'], $filter);
1298
            reset($data);
1299
        } else {
1300
            $this->filterValue($data, $name, $filter);
1301
        }
1302
1303
        return $data;
1304
    }
1305
1306
    /**
1307
     * 强制类型转换
1308
     * @access public
1309
     * @param  mixed  $data
0 ignored issues
show
Coding Style introduced by
Missing parameter comment
Loading history...
1310
     * @param  string $type
0 ignored issues
show
Coding Style introduced by
Missing parameter comment
Loading history...
1311
     * @return mixed
1312
     */
1313
    private function typeCast(&$data, string $type)
0 ignored issues
show
Coding Style introduced by
Private method name "Request::typeCast" must be prefixed with an underscore
Loading history...
1314
    {
1315
        switch (strtolower($type)) {
1316
            // 数组
1317
            case 'a':
1318
                $data = (array) $data;
1319
                break;
1320
            // 数字
1321
            case 'd':
1322
                $data = (int) $data;
1323
                break;
1324
            // 浮点
1325
            case 'f':
1326
                $data = (float) $data;
1327
                break;
1328
            // 布尔
1329
            case 'b':
1330
                $data = (boolean) $data;
1331
                break;
1332
            // 字符串
1333
            case 's':
1334
                if (is_scalar($data)) {
1335
                    $data = (string) $data;
1336
                } else {
1337
                    throw new \InvalidArgumentException('variable type error:' . gettype($data));
1338
                }
1339
                break;
1340
        }
1341
    }
1342
1343
    /**
1344
     * 获取数据
1345
     * @access public
1346
     * @param  array  $data 数据源
0 ignored issues
show
Coding Style introduced by
Expected 4 spaces after parameter name; 1 found
Loading history...
1347
     * @param  string $name 字段名
0 ignored issues
show
Coding Style introduced by
Expected 4 spaces after parameter name; 1 found
Loading history...
1348
     * @param  mixed  $default 默认值
1349
     * @return mixed
1350
     */
1351
    protected function getData(array $data, string $name, $default = null)
1352
    {
1353
        foreach (explode('.', $name) as $val) {
1354
            if (isset($data[$val])) {
1355
                $data = $data[$val];
1356
            } else {
1357
                return $default;
1358
            }
1359
        }
1360
1361
        return $data;
1362
    }
1363
1364
    /**
1365
     * 设置或获取当前的过滤规则
1366
     * @access public
1367
     * @param  mixed $filter 过滤规则
1368
     * @return mixed
1369
     */
1370
    public function filter($filter = null)
1371
    {
1372
        if (is_null($filter)) {
1373
            return $this->filter;
1374
        }
1375
1376
        $this->filter = $filter;
1377
1378
        return $this;
1379
    }
1380
1381
    protected function getFilter($filter, $default): array
0 ignored issues
show
Coding Style introduced by
Missing doc comment for function getFilter()
Loading history...
1382
    {
1383
        if (is_null($filter)) {
1384
            $filter = [];
1385
        } else {
1386
            $filter = $filter ?: $this->filter;
1387
            if (is_string($filter) && false === strpos($filter, '/')) {
1388
                $filter = explode(',', $filter);
1389
            } else {
1390
                $filter = (array) $filter;
1391
            }
1392
        }
1393
1394
        $filter[] = $default;
1395
1396
        return $filter;
1397
    }
1398
1399
    /**
1400
     * 递归过滤给定的值
1401
     * @access public
1402
     * @param  mixed $value 键值
0 ignored issues
show
Coding Style introduced by
Expected 3 spaces after parameter name; 1 found
Loading history...
1403
     * @param  mixed $key 键名
0 ignored issues
show
Coding Style introduced by
Expected 5 spaces after parameter name; 1 found
Loading history...
1404
     * @param  array $filters 过滤方法+默认值
1405
     * @return mixed
1406
     */
1407
    public function filterValue(&$value, $key, $filters)
1408
    {
1409
        $default = array_pop($filters);
1410
1411
        foreach ($filters as $filter) {
1412
            if (is_callable($filter)) {
1413
                // 调用函数或者方法过滤
1414
                $value = call_user_func($filter, $value);
1415
            } elseif (is_scalar($value)) {
1416
                if (is_string($filter) && false !== strpos($filter, '/')) {
1417
                    // 正则过滤
1418
                    if (!preg_match($filter, $value)) {
1419
                        // 匹配不成功返回默认值
1420
                        $value = $default;
1421
                        break;
1422
                    }
1423
                } elseif (!empty($filter)) {
1424
                    // filter函数不存在时, 则使用filter_var进行过滤
1425
                    // filter为非整形值时, 调用filter_id取得过滤id
1426
                    $value = filter_var($value, is_int($filter) ? $filter : filter_id($filter));
1427
                    if (false === $value) {
1428
                        $value = $default;
1429
                        break;
1430
                    }
1431
                }
1432
            }
1433
        }
1434
1435
        return $value;
1436
    }
1437
1438
    /**
1439
     * 是否存在某个请求参数
1440
     * @access public
1441
     * @param  string $name 变量名
0 ignored issues
show
Coding Style introduced by
Expected 7 spaces after parameter name; 1 found
Loading history...
1442
     * @param  string $type 变量类型
0 ignored issues
show
Coding Style introduced by
Expected 7 spaces after parameter name; 1 found
Loading history...
1443
     * @param  bool   $checkEmpty 是否检测空值
1444
     * @return bool
1445
     */
1446
    public function has(string $name, string $type = 'param', bool $checkEmpty = false): bool
1447
    {
1448
        if (!in_array($type, ['param', 'get', 'post', 'put', 'patch', 'route', 'delete', 'cookie', 'session', 'env', 'request', 'server', 'header', 'file'])) {
1449
            return false;
1450
        }
1451
1452
        $param = empty($this->$type) ? $this->$type() : $this->$type;
1453
1454
        if (is_object($param)) {
1455
            return $param->has($name);
1456
        }
1457
1458
        // 按.拆分成多维数组进行判断
1459
        foreach (explode('.', $name) as $val) {
1460
            if (isset($param[$val])) {
1461
                $param = $param[$val];
1462
            } else {
1463
                return false;
1464
            }
1465
        }
1466
1467
        return ($checkEmpty && '' === $param) ? false : true;
1468
    }
1469
1470
    /**
1471
     * 获取指定的参数
1472
     * @access public
1473
     * @param  array        $name 变量名
0 ignored issues
show
Coding Style introduced by
Expected 3 spaces after parameter name; 1 found
Loading history...
1474
     * @param  mixed        $data 数据或者变量类型
0 ignored issues
show
Coding Style introduced by
Expected 3 spaces after parameter name; 1 found
Loading history...
1475
     * @param  string|array $filter 过滤方法
1476
     * @return array
1477
     */
1478
    public function only(array $name, $data = 'param', $filter = ''): array
1479
    {
1480
        $data = is_array($data) ? $data : $this->$data();
1481
1482
        $item = [];
1483
        foreach ($name as $key => $val) {
1484
1485
            if (is_int($key)) {
1486
                $default = null;
1487
                $key     = $val;
1488
                if (!isset($data[$key])) {
1489
                    continue;
1490
                }
1491
            } else {
1492
                $default = $val;
1493
            }
1494
1495
            $item[$key] = $this->filterData($data[$key] ?? $default, $filter, $key, $default);
1496
        }
1497
1498
        return $item;
1499
    }
1500
1501
    /**
1502
     * 排除指定参数获取
1503
     * @access public
1504
     * @param  array  $name 变量名
1505
     * @param  string $type 变量类型
1506
     * @return mixed
1507
     */
1508
    public function except(array $name, string $type = 'param'): array
1509
    {
1510
        $param = $this->$type();
1511
1512
        foreach ($name as $key) {
1513
            if (isset($param[$key])) {
1514
                unset($param[$key]);
1515
            }
1516
        }
1517
1518
        return $param;
1519
    }
1520
1521
    /**
1522
     * 当前是否ssl
1523
     * @access public
1524
     * @return bool
1525
     */
1526
    public function isSsl(): bool
1527
    {
1528
        if ($this->server('HTTPS') && ('1' == $this->server('HTTPS') || 'on' == strtolower($this->server('HTTPS')))) {
1529
            return true;
1530
        } elseif ('https' == $this->server('REQUEST_SCHEME')) {
1531
            return true;
1532
        } elseif ('443' == $this->server('SERVER_PORT')) {
1533
            return true;
1534
        } elseif ('https' == $this->server('HTTP_X_FORWARDED_PROTO')) {
1535
            return true;
1536
        } elseif ($this->httpsAgentName && $this->server($this->httpsAgentName)) {
1537
            return true;
1538
        }
1539
1540
        return false;
1541
    }
1542
1543
    /**
1544
     * 当前是否JSON请求
1545
     * @access public
1546
     * @return bool
1547
     */
1548
    public function isJson(): bool
1549
    {
1550
        $acceptType = $this->type();
1551
1552
        return false !== strpos($acceptType, 'json');
1553
    }
1554
1555
    /**
1556
     * 当前是否Ajax请求
1557
     * @access public
1558
     * @param  bool $ajax true 获取原始ajax请求
1559
     * @return bool
1560
     */
1561
    public function isAjax(bool $ajax = false): bool
1562
    {
1563
        $value  = $this->server('HTTP_X_REQUESTED_WITH');
1564
        $result = $value && 'xmlhttprequest' == strtolower($value) ? true : false;
1565
1566
        if (true === $ajax) {
1567
            return $result;
1568
        }
1569
1570
        return $this->param($this->varAjax) ? true : $result;
1571
    }
1572
1573
    /**
1574
     * 当前是否Pjax请求
1575
     * @access public
1576
     * @param  bool $pjax true 获取原始pjax请求
1577
     * @return bool
1578
     */
1579
    public function isPjax(bool $pjax = false): bool
1580
    {
1581
        $result = !empty($this->server('HTTP_X_PJAX')) ? true : false;
1582
1583
        if (true === $pjax) {
1584
            return $result;
1585
        }
1586
1587
        return $this->param($this->varPjax) ? true : $result;
1588
    }
1589
1590
    /**
1591
     * 获取客户端IP地址
1592
     * @access public
1593
     * @return string
1594
     */
1595
    public function ip(): string
1596
    {
1597
        if (!empty($this->realIP)) {
1598
            return $this->realIP;
1599
        }
1600
1601
        $this->realIP = $this->server('REMOTE_ADDR', '');
1602
1603
        // 如果指定了前端代理服务器IP以及其会发送的IP头
1604
        // 则尝试获取前端代理服务器发送过来的真实IP
1605
        $proxyIp       = $this->proxyServerIp;
1606
        $proxyIpHeader = $this->proxyServerIpHeader;
1607
1608
        if (count($proxyIp) > 0 && count($proxyIpHeader) > 0) {
1609
            // 从指定的HTTP头中依次尝试获取IP地址
1610
            // 直到获取到一个合法的IP地址
1611
            foreach ($proxyIpHeader as $header) {
1612
                $tempIP = $this->server($header);
1613
1614
                if (empty($tempIP)) {
1615
                    continue;
1616
                }
1617
1618
                $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

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