Completed
Pull Request — 6.0 (#1873)
by
unknown
05:24
created

Response::create()   A

Complexity

Conditions 3
Paths 4

Size

Total Lines 9
Code Lines 4

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 12

Importance

Changes 0
Metric Value
cc 3
eloc 4
nc 4
nop 3
dl 0
loc 9
ccs 0
cts 5
cp 0
crap 12
rs 10
c 0
b 0
f 0
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
/**
16
 * 响应输出基础类
17
 */
18
class Response
19
{
20
    /**
21
     * 原始数据
22
     * @var mixed
23
     */
24
    protected $data;
25
26
    /**
27
     * 当前contentType
28
     * @var string
29
     */
30
    protected $contentType = 'text/html';
31
32
    /**
33
     * 字符集
34
     * @var string
35
     */
36
    protected $charset = 'utf-8';
37
38
    /**
39
     * 状态码
40
     * @var integer
41
     */
42
    protected $code = 200;
43
44
    /**
45
     * 是否允许请求缓存
46
     * @var bool
47
     */
48
    protected $allowCache = true;
49
50
    /**
51
     * 输出参数
52
     * @var array
53
     */
54
    protected $options = [];
55
56
    /**
57
     * header参数
0 ignored issues
show
Coding Style introduced by
Doc comment short description must start with a capital letter
Loading history...
58
     * @var array
59
     */
60
    protected $header = [];
61
62
    /**
63
     * 输出内容
64
     * @var string
65
     */
66
    protected $content = null;
67
68
    /**
69
     * Cookie对象
70
     * @var Cookie
71
     */
72
    protected $cookie;
73
74
    /**
75
     * Session对象
76
     * @var Session
77
     */
78
    protected $session;
79
80
    /**
81
     * 架构函数
82
     * @access public
83
     * @param  mixed $data    输出数据
0 ignored issues
show
Coding Style introduced by
Expected 1 spaces after parameter name; 4 found
Loading history...
84
     * @param  int   $code
0 ignored issues
show
Coding Style introduced by
Missing parameter comment
Loading history...
85
     */
86
    public function __construct($data = '', int $code = 200)
87
    {
88
        $this->data($data);
89
        $this->code = $code;
90
91
        $this->contentType($this->contentType, $this->charset);
92
    }
93
94
    /**
95
     * 创建Response对象
96
     * @access public
97
     * @param  mixed  $data    输出数据
0 ignored issues
show
Coding Style introduced by
Expected 1 spaces after parameter name; 4 found
Loading history...
98
     * @param  string $type    输出类型
0 ignored issues
show
Coding Style introduced by
Expected 1 spaces after parameter name; 4 found
Loading history...
99
     * @param  int    $code
0 ignored issues
show
Coding Style introduced by
Missing parameter comment
Loading history...
100
     * @return Response
101
     */
102
    public static function create($data = '', string $type = '', int $code = 200): Response
103
    {
104
        $class = false !== strpos($type, '\\') ? $type : '\\think\\response\\' . ucfirst(strtolower($type));
105
106
        if (class_exists($class)) {
107
            return Container::getInstance()->invokeClass($class, [$data, $code]);
108
        }
109
110
        return new static($data, $code);
111
    }
112
113
    /**
114
     * 设置Cookie对象
115
     * @access public
116
     * @param  Cookie $cookie Cookie对象
117
     * @return $this
118
     */
119 7
    public function setCookie(Cookie $cookie)
120
    {
121 7
        $this->cookie = $cookie;
122 7
        return $this;
123
    }
124
125
    /**
126
     * 设置Session对象
127
     * @access public
128
     * @param  Session $session Session对象
129
     * @return $this
130
     */
131
    public function setSession(Session $session)
132
    {
133
        $this->session = $session;
134
        return $this;
135
    }
136
137
    /**
138
     * 发送数据到客户端
139
     * @access public
140
     * @return void
141
     * @throws \InvalidArgumentException
142
     */
143
    public function send(): void
144
    {
145
        // 触发请求发送前置事件
146
        event('BeforeSend');
147
        // 处理输出数据
148
        $data = $this->getContent();
149
150
        if (!headers_sent() && !empty($this->header)) {
151
            // 发送状态码
152
            http_response_code($this->code);
153
            // 发送头部信息
154
            foreach ($this->header as $name => $val) {
155
                header($name . (!is_null($val) ? ':' . $val : ''));
156
            }
157
        }
158
159
        $this->cookie->save();
160
161
        $this->sendData($data);
162
163
        if (function_exists('fastcgi_finish_request')) {
164
            // 提高页面响应
165
            fastcgi_finish_request();
166
        }
167
168
        // 触发请求发送后置事件
169
        event('AfterSend');
170
    }
171
172
    /**
173
     * 处理数据
174
     * @access protected
175
     * @param  mixed $data 要处理的数据
176
     * @return mixed
177
     */
178
    protected function output($data)
179
    {
180
        return $data;
181
    }
182
183
    /**
184
     * 输出数据
185
     * @access protected
186
     * @param string $data 要处理的数据
187
     * @return void
188
     */
189
    protected function sendData(string $data): void
190
    {
191
        echo $data;
192
    }
193
194
    /**
195
     * 输出的参数
196
     * @access public
197
     * @param  mixed $options 输出参数
198
     * @return $this
199
     */
200
    public function options(array $options = [])
201
    {
202
        $this->options = array_merge($this->options, $options);
203
204
        return $this;
205
    }
206
207
    /**
208
     * 输出数据设置
209
     * @access public
210
     * @param  mixed $data 输出数据
211
     * @return $this
212
     */
213
    public function data($data)
214
    {
215
        $this->data = $data;
216
217
        return $this;
218
    }
219
220
    /**
221
     * 是否允许请求缓存
222
     * @access public
223
     * @param  bool $cache 允许请求缓存
224
     * @return $this
225
     */
226
    public function allowCache(bool $cache)
227
    {
228
        $this->allowCache = $cache;
229
230
        return $this;
231
    }
232
233
    /**
234
     * 是否允许请求缓存
235
     * @access public
236
     * @return $this
237
     */
238
    public function isAllowCache()
239
    {
240
        return $this->allowCache;
0 ignored issues
show
Bug Best Practice introduced by
The expression return $this->allowCache returns the type boolean which is incompatible with the documented return type think\Response.
Loading history...
241
    }
242
243
    /**
244
     * 设置响应头
245
     * @access public
246
     * @param  array $header  参数
0 ignored issues
show
Coding Style introduced by
Expected 1 spaces after parameter name; 2 found
Loading history...
247
     * @return $this
248
     */
249
    public function header(array $header = [])
250
    {
251
        $this->header = array_merge($this->header, $header);
252
253
        return $this;
254
    }
255
256
    /**
257
     * 设置页面输出内容
258
     * @access public
259
     * @param  mixed $content
0 ignored issues
show
Coding Style introduced by
Missing parameter comment
Loading history...
260
     * @return $this
261
     */
262
    public function content($content)
263
    {
264
        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...
265
            $content,
266
            '__toString',
267
        ])
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...
268
        ) {
269
            throw new \InvalidArgumentException(sprintf('variable type error: %s', gettype($content)));
270
        }
271
272
        $this->content = (string) $content;
273
274
        return $this;
275
    }
276
277
    /**
278
     * 发送HTTP状态
279
     * @access public
280
     * @param  integer $code 状态码
281
     * @return $this
282
     */
283
    public function code(int $code)
284
    {
285
        $this->code = $code;
286
287
        return $this;
288
    }
289
290
    /**
291
     * LastModified
292
     * @access public
293
     * @param  string $time
0 ignored issues
show
Coding Style introduced by
Missing parameter comment
Loading history...
294
     * @return $this
295
     */
296
    public function lastModified(string $time)
297
    {
298
        $this->header['Last-Modified'] = $time;
299
300
        return $this;
301
    }
302
303
    /**
304
     * Expires
305
     * @access public
306
     * @param  string $time
0 ignored issues
show
Coding Style introduced by
Missing parameter comment
Loading history...
307
     * @return $this
308
     */
309
    public function expires(string $time)
310
    {
311
        $this->header['Expires'] = $time;
312
313
        return $this;
314
    }
315
316
    /**
317
     * ETag
318
     * @access public
319
     * @param  string $eTag
0 ignored issues
show
Coding Style introduced by
Missing parameter comment
Loading history...
320
     * @return $this
321
     */
322
    public function eTag(string $eTag)
323
    {
324
        $this->header['ETag'] = $eTag;
325
326
        return $this;
327
    }
328
329
    /**
330
     * 页面缓存控制
331
     * @access public
332
     * @param  string $cache 状态码
333
     * @return $this
334
     */
335
    public function cacheControl(string $cache)
336
    {
337
        $this->header['Cache-control'] = $cache;
338
339
        return $this;
340
    }
341
342
    /**
343
     * 页面输出类型
344
     * @access public
345
     * @param  string $contentType 输出类型
346
     * @param  string $charset     输出编码
347
     * @return $this
348
     */
349
    public function contentType(string $contentType, string $charset = 'utf-8')
350
    {
351
        $this->header['Content-Type'] = $contentType . '; charset=' . $charset;
352
353
        return $this;
354
    }
355
356
    /**
357
     * 获取头部信息
358
     * @access public
359
     * @param  string $name 头部名称
360
     * @return mixed
361
     */
362
    public function getHeader(string $name = '')
363
    {
364
        if (!empty($name)) {
365
            return $this->header[$name] ?? null;
366
        }
367
368
        return $this->header;
369
    }
370
371
    /**
372
     * 获取原始数据
373
     * @access public
374
     * @return mixed
375
     */
376
    public function getData()
377
    {
378
        return $this->data;
379
    }
380
381
    /**
382
     * 获取输出数据
383
     * @access public
384
     * @return string
385
     */
386
    public function getContent(): string
387
    {
388
        if (null == $this->content) {
389
            $content = $this->output($this->data);
390
391
            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...
392
                $content,
393
                '__toString',
394
            ])
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...
395
            ) {
396
                throw new \InvalidArgumentException(sprintf('variable type error: %s', gettype($content)));
397
            }
398
399
            $this->content = (string) $content;
400
        }
401
402
        return $this->content;
403
    }
404
405
    /**
406
     * 获取状态码
407
     * @access public
408
     * @return integer
409
     */
410
    public function getCode(): int
411
    {
412
        return $this->code;
413
    }
414
}
415