Passed
Push — 6.0 ( de6c84...b392ff )
by liu
02:34
created

Response::allowCache()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 5
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 1
eloc 2
nc 1
nop 1
dl 0
loc 5
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\response\Redirect as RedirectResponse;
16
17
class Response
1 ignored issue
show
Coding Style introduced by
Missing class doc comment
Loading history...
18
{
19
    /**
20
     * 原始数据
21
     * @var mixed
22
     */
23
    protected $data;
24
25
    /**
26
     * 当前contentType
27
     * @var string
28
     */
29
    protected $contentType = 'text/html';
30
31
    /**
32
     * 字符集
33
     * @var string
34
     */
35
    protected $charset = 'utf-8';
36
37
    /**
38
     * 状态码
39
     * @var integer
40
     */
41
    protected $code = 200;
42
43
    /**
44
     * 是否允许请求缓存
45
     * @var bool
46
     */
47
    protected $allowCache = true;
48
49
    /**
50
     * 输出参数
51
     * @var array
52
     */
53
    protected $options = [];
54
55
    /**
56
     * header参数
0 ignored issues
show
Coding Style introduced by
Doc comment short description must start with a capital letter
Loading history...
57
     * @var array
58
     */
59
    protected $header = [];
60
61
    /**
62
     * 输出内容
63
     * @var string
64
     */
65
    protected $content = null;
66
67
    /**
68
     * 架构函数
69
     * @access public
70
     * @param  mixed $data    输出数据
0 ignored issues
show
Coding Style introduced by
Expected 1 spaces after parameter name; 4 found
Loading history...
71
     * @param  int   $code
0 ignored issues
show
Coding Style introduced by
Missing parameter comment
Loading history...
72
     */
73
    public function __construct($data = '', int $code = 200)
74
    {
75
        $this->data($data);
76
        $this->code = $code;
77
78
        $this->contentType($this->contentType, $this->charset);
79
    }
80
81
    /**
82
     * 创建Response对象
83
     * @access public
84
     * @param  mixed  $data    输出数据
0 ignored issues
show
Coding Style introduced by
Expected 1 spaces after parameter name; 4 found
Loading history...
85
     * @param  string $type    输出类型
0 ignored issues
show
Coding Style introduced by
Expected 1 spaces after parameter name; 4 found
Loading history...
86
     * @param  int    $code
0 ignored issues
show
Coding Style introduced by
Missing parameter comment
Loading history...
87
     * @return Response
88
     */
89
    public static function create($data = '', string $type = '', int $code = 200): Response
90
    {
91
        $class = false !== strpos($type, '\\') ? $type : '\\think\\response\\' . ucfirst(strtolower($type));
92
93
        if (class_exists($class)) {
94
            return new $class($data, $code);
95
        }
96
97
        return new static($data, $code);
98
    }
99
100
    /**
101
     * 发送数据到客户端
102
     * @access public
103
     * @return void
104
     * @throws \InvalidArgumentException
105
     */
106
    public function send(): void
107
    {
108
        // 监听response_send
109
        Container::pull('event')->trigger('ResponseSend', $this);
110
111
        // 处理输出数据
112
        $data = $this->getContent();
113
114
        if (200 == $this->code && $this->allowCache) {
115
            $cache = Container::pull('request')->getCache();
116
            if ($cache) {
117
                $this->header['Cache-Control'] = 'max-age=' . $cache[1] . ',must-revalidate';
118
                $this->header['Last-Modified'] = gmdate('D, d M Y H:i:s') . ' GMT';
119
                $this->header['Expires']       = gmdate('D, d M Y H:i:s', $_SERVER['REQUEST_TIME'] + $cache[1]) . ' GMT';
120
121
                Container::pull('cache')->tag($cache[2])->set($cache[0], [$data, $this->header], $cache[1]);
122
            }
123
        }
124
125
        if (!headers_sent() && !empty($this->header)) {
126
            // 发送状态码
127
            http_response_code($this->code);
128
            // 发送头部信息
129
            foreach ($this->header as $name => $val) {
130
                header($name . (!is_null($val) ? ':' . $val : ''));
131
            }
132
        }
133
134
        Container::pull('cookie')->save();
135
136
        $this->sendData($data);
137
138
        if (function_exists('fastcgi_finish_request')) {
139
            // 提高页面响应
140
            fastcgi_finish_request();
141
        }
142
143
        // 监听response_end
144
        Container::pull('event')->trigger('ResponseEnd', $this);
145
146
        // 清空当次请求有效的数据
147
        if (!($this instanceof RedirectResponse)) {
148
            Container::pull('session')->flush();
149
        }
150
    }
151
152
    /**
153
     * 处理数据
154
     * @access protected
155
     * @param  mixed $data 要处理的数据
156
     * @return mixed
157
     */
158
    protected function output($data)
159
    {
160
        return $data;
161
    }
162
163
    /**
164
     * 输出数据
165
     * @access protected
166
     * @param string $data 要处理的数据
1 ignored issue
show
Coding Style introduced by
Tag value indented incorrectly; expected 2 spaces but found 1
Loading history...
167
     * @return void
168
     */
169
    protected function sendData(string $data): void
170
    {
171
        echo $data;
172
    }
173
174
    /**
175
     * 输出的参数
176
     * @access public
177
     * @param  mixed $options 输出参数
178
     * @return $this
179
     */
180
    public function options(array $options = [])
181
    {
182
        $this->options = array_merge($this->options, $options);
183
184
        return $this;
185
    }
186
187
    /**
188
     * 输出数据设置
189
     * @access public
190
     * @param  mixed $data 输出数据
191
     * @return $this
192
     */
193
    public function data($data)
194
    {
195
        $this->data = $data;
196
197
        return $this;
198
    }
199
200
    /**
201
     * 是否允许请求缓存
202
     * @access public
203
     * @param  bool $cache 允许请求缓存
204
     * @return $this
205
     */
206
    public function allowCache(bool $cache)
207
    {
208
        $this->allowCache = $cache;
209
210
        return $this;
211
    }
212
213
    /**
214
     * 设置响应头
215
     * @access public
216
     * @param  array $header  参数
0 ignored issues
show
Coding Style introduced by
Expected 1 spaces after parameter name; 2 found
Loading history...
217
     * @return $this
218
     */
219
    public function header(array $header = [])
220
    {
221
        $this->header = array_merge($this->header, $header);
222
223
        return $this;
224
    }
225
226
    /**
227
     * 设置页面输出内容
228
     * @access public
229
     * @param  mixed $content
0 ignored issues
show
Coding Style introduced by
Missing parameter comment
Loading history...
230
     * @return $this
231
     */
232
    public function content($content)
233
    {
234
        if (null !== $content && !is_string($content) && !is_numeric($content) && !is_callable([
0 ignored issues
show
Coding Style introduced by
The opening parenthesis of a multi-line function call should be the last content on the line.
Loading history...
235
            $content,
236
            '__toString',
237
        ])
0 ignored issues
show
Coding Style introduced by
For multi-line function calls, the closing parenthesis should be on a new line.

If a function call spawns multiple lines, the coding standard suggests to move the closing parenthesis to a new line:

someFunctionCall(
    $firstArgument,
    $secondArgument,
    $thirdArgument
); // Closing parenthesis on a new line.
Loading history...
238
        ) {
239
            throw new \InvalidArgumentException(sprintf('variable type error: %s', gettype($content)));
240
        }
241
242
        $this->content = (string) $content;
243
244
        return $this;
245
    }
246
247
    /**
248
     * 发送HTTP状态
249
     * @access public
250
     * @param  integer $code 状态码
251
     * @return $this
252
     */
253
    public function code(int $code)
254
    {
255
        $this->code = $code;
256
257
        return $this;
258
    }
259
260
    /**
261
     * LastModified
262
     * @access public
263
     * @param  string $time
0 ignored issues
show
Coding Style introduced by
Missing parameter comment
Loading history...
264
     * @return $this
265
     */
266
    public function lastModified(string $time)
267
    {
268
        $this->header['Last-Modified'] = $time;
269
270
        return $this;
271
    }
272
273
    /**
274
     * Expires
275
     * @access public
276
     * @param  string $time
0 ignored issues
show
Coding Style introduced by
Missing parameter comment
Loading history...
277
     * @return $this
278
     */
279
    public function expires(string $time)
280
    {
281
        $this->header['Expires'] = $time;
282
283
        return $this;
284
    }
285
286
    /**
287
     * ETag
288
     * @access public
289
     * @param  string $eTag
0 ignored issues
show
Coding Style introduced by
Missing parameter comment
Loading history...
290
     * @return $this
291
     */
292
    public function eTag(string $eTag)
293
    {
294
        $this->header['ETag'] = $eTag;
295
296
        return $this;
297
    }
298
299
    /**
300
     * 页面缓存控制
301
     * @access public
302
     * @param  string $cache 状态码
303
     * @return $this
304
     */
305
    public function cacheControl(string $cache)
306
    {
307
        $this->header['Cache-control'] = $cache;
308
309
        return $this;
310
    }
311
312
    /**
313
     * 页面输出类型
314
     * @access public
315
     * @param  string $contentType 输出类型
316
     * @param  string $charset     输出编码
317
     * @return $this
318
     */
319
    public function contentType(string $contentType, string $charset = 'utf-8')
320
    {
321
        $this->header['Content-Type'] = $contentType . '; charset=' . $charset;
322
323
        return $this;
324
    }
325
326
    /**
327
     * 获取头部信息
328
     * @access public
329
     * @param  string $name 头部名称
330
     * @return mixed
331
     */
332
    public function getHeader(string $name = '')
333
    {
334
        if (!empty($name)) {
335
            return $this->header[$name] ?? null;
336
        }
337
338
        return $this->header;
339
    }
340
341
    /**
342
     * 获取原始数据
343
     * @access public
344
     * @return mixed
345
     */
346
    public function getData()
347
    {
348
        return $this->data;
349
    }
350
351
    /**
352
     * 获取输出数据
353
     * @access public
354
     * @return string
355
     */
356
    public function getContent(): string
357
    {
358
        if (null == $this->content) {
359
            $content = $this->output($this->data);
360
361
            if (null !== $content && !is_string($content) && !is_numeric($content) && !is_callable([
0 ignored issues
show
Coding Style introduced by
The opening parenthesis of a multi-line function call should be the last content on the line.
Loading history...
362
                $content,
363
                '__toString',
364
            ])
0 ignored issues
show
Coding Style introduced by
For multi-line function calls, the closing parenthesis should be on a new line.

If a function call spawns multiple lines, the coding standard suggests to move the closing parenthesis to a new line:

someFunctionCall(
    $firstArgument,
    $secondArgument,
    $thirdArgument
); // Closing parenthesis on a new line.
Loading history...
365
            ) {
366
                throw new \InvalidArgumentException(sprintf('variable type error: %s', gettype($content)));
367
            }
368
369
            $this->content = (string) $content;
370
        }
371
372
        return $this->content;
373
    }
374
375
    /**
376
     * 获取状态码
377
     * @access public
378
     * @return integer
379
     */
380
    public function getCode(): int
381
    {
382
        return $this->code;
383
    }
384
}
385