1
|
|
|
<?php |
2
|
|
|
namespace Fyuze\Http; |
3
|
|
|
|
4
|
|
|
use Fyuze\Http\Message\Response as PsrResponse; |
5
|
|
|
use Fyuze\Http\Message\Stream; |
6
|
|
|
|
7
|
|
|
class Response extends PsrResponse |
8
|
|
|
{ |
9
|
|
|
/** |
10
|
|
|
* @var string |
11
|
|
|
*/ |
12
|
|
|
protected $contentType = 'text/html'; |
13
|
|
|
|
14
|
|
|
/** |
15
|
|
|
* @var boolean |
16
|
|
|
*/ |
17
|
|
|
protected $cache = false; |
18
|
|
|
|
19
|
|
|
/** |
20
|
|
|
* @var boolean |
21
|
|
|
*/ |
22
|
|
|
protected $compression = true; |
23
|
|
|
|
24
|
|
|
/** |
25
|
|
|
* @param $body |
26
|
|
|
* @param $code |
27
|
|
|
* @return Response |
28
|
|
|
*/ |
29
|
12 |
|
public static function create($body = '', $code = 200) |
30
|
|
|
{ |
31
|
12 |
|
$stream = new Stream('php://memory', 'wb+'); |
32
|
12 |
|
$stream->write($body); |
33
|
12 |
|
return (new static) |
34
|
12 |
|
->withStatus($code) |
35
|
12 |
|
->withBody($stream); |
36
|
|
|
} |
37
|
|
|
|
38
|
|
|
/** |
39
|
|
|
* Set response caching, blank for default |
40
|
|
|
* |
41
|
|
|
* @param boolean $value |
42
|
|
|
* @return bool |
43
|
|
|
*/ |
44
|
1 |
|
public function setCache($value = false) |
45
|
|
|
{ |
46
|
1 |
|
return $this->cache = $value; |
47
|
|
|
} |
48
|
|
|
|
49
|
|
|
/** |
50
|
|
|
* Set output compression, blank for default |
51
|
|
|
* |
52
|
|
|
* @param boolean $value |
53
|
|
|
* @return bool |
54
|
|
|
*/ |
55
|
1 |
|
public function setCompression($value = true) |
56
|
|
|
{ |
57
|
1 |
|
return $this->compression = $value; |
58
|
|
|
} |
59
|
|
|
|
60
|
|
|
/** |
61
|
|
|
* Modify the response |
62
|
|
|
* |
63
|
|
|
* @param \Closure $closure |
64
|
|
|
*/ |
65
|
1 |
|
public function modify(\Closure $closure) |
66
|
|
|
{ |
67
|
1 |
|
return $this->stream = $closure($this->stream); |
68
|
|
|
} |
69
|
|
|
|
70
|
|
|
/** |
71
|
|
|
* Sends the response |
72
|
|
|
* We ignore coverage here because |
73
|
|
|
* headers cannot be tested in cli sapi |
74
|
|
|
* |
75
|
|
|
* @codeCoverageIgnore |
76
|
|
|
*/ |
77
|
|
|
public function send() |
78
|
|
|
{ |
79
|
|
|
foreach ($this->headers as $key => $value) { |
80
|
|
|
header("$key: " . implode(',', $value)); |
81
|
|
|
} |
82
|
|
|
|
83
|
|
|
if($this->hasHeader('Content-Type') === false) { |
84
|
|
|
header(vsprintf( |
85
|
|
|
'Content-Type: %s', |
86
|
|
|
$this->hasHeader('Content-Type') ? $this->getHeader('Content-Type') : [$this->contentType] |
87
|
|
|
)); |
88
|
|
|
} |
89
|
|
|
|
90
|
|
|
http_response_code($this->getStatusCode()); |
91
|
|
|
|
92
|
|
|
if ($this->stream !== null) { |
93
|
|
|
if ($this->compression) { |
94
|
|
|
ob_start('ob_gzhandler'); |
95
|
|
|
} |
96
|
|
|
echo (string)$this->getBody(); |
97
|
|
|
} |
98
|
|
|
} |
99
|
|
|
|
100
|
|
|
/** |
101
|
|
|
* @return string |
102
|
|
|
*/ |
103
|
1 |
|
public function __toString() |
104
|
|
|
{ |
105
|
1 |
|
return (string)$this->getBody(); |
106
|
|
|
} |
107
|
|
|
} |
108
|
|
|
|