|
1
|
|
|
<?php |
|
2
|
|
|
|
|
3
|
|
|
declare(strict_types=1); |
|
4
|
|
|
|
|
5
|
|
|
namespace Furious\Psr7; |
|
6
|
|
|
|
|
7
|
|
|
use Furious\Psr7\Exception\InvalidArgumentException; |
|
8
|
|
|
use Furious\Psr7\Response\Phrases; |
|
9
|
|
|
use Psr\Http\Message\ResponseInterface; |
|
10
|
|
|
use function is_int; |
|
11
|
|
|
use function is_string; |
|
12
|
|
|
|
|
13
|
|
|
class Response extends Message implements ResponseInterface |
|
14
|
|
|
{ |
|
15
|
|
|
private int $statusCode; |
|
|
|
|
|
|
16
|
|
|
private string $reasonPhrase = ''; |
|
17
|
|
|
|
|
18
|
|
|
public function __construct( |
|
19
|
|
|
int $statusCode = 200, array $headers = [], $body = null, |
|
20
|
|
|
string $version = '1.1', string $reason = null |
|
21
|
|
|
) |
|
22
|
|
|
{ |
|
23
|
|
|
if ('' !== $body and null !== $body) { |
|
24
|
|
|
$this->stream = Stream::new($body); |
|
25
|
|
|
} |
|
26
|
|
|
|
|
27
|
|
|
$this->validateStatusCode($statusCode); |
|
28
|
|
|
$this->statusCode = $statusCode; |
|
29
|
|
|
$this->setHeaders($headers); |
|
30
|
|
|
$this->initializeReasonPhrase($reason); |
|
31
|
|
|
$this->protocolVersion = $version; |
|
32
|
|
|
} |
|
33
|
|
|
|
|
34
|
|
|
private function initializeReasonPhrase(?string $reason): void |
|
35
|
|
|
{ |
|
36
|
|
|
if (null === $reason and isset(Phrases::LIST[$this->statusCode])) { |
|
37
|
|
|
$this->reasonPhrase = Phrases::LIST[$this->statusCode]; |
|
38
|
|
|
} else { |
|
39
|
|
|
$this->reasonPhrase = $reason ?? ''; |
|
40
|
|
|
} |
|
41
|
|
|
} |
|
42
|
|
|
|
|
43
|
|
|
// Get |
|
44
|
|
|
|
|
45
|
|
|
public function getStatusCode(): int |
|
46
|
|
|
{ |
|
47
|
|
|
return $this->statusCode; |
|
48
|
|
|
} |
|
49
|
|
|
|
|
50
|
|
|
public function getReasonPhrase(): string |
|
51
|
|
|
{ |
|
52
|
|
|
return $this->reasonPhrase; |
|
53
|
|
|
} |
|
54
|
|
|
|
|
55
|
|
|
// With |
|
56
|
|
|
|
|
57
|
|
|
public function withStatus($code, $reasonPhrase = ''): self |
|
58
|
|
|
{ |
|
59
|
|
|
$this->validateStatusCode($code); |
|
60
|
|
|
|
|
61
|
|
|
$response = clone $this; |
|
62
|
|
|
$response->statusCode = $code; |
|
63
|
|
|
|
|
64
|
|
|
if ( |
|
65
|
|
|
(null === $reasonPhrase or '' === $reasonPhrase) and |
|
66
|
|
|
isset(Phrases::LIST[$response->statusCode]) |
|
67
|
|
|
) { |
|
68
|
|
|
$reasonPhrase = Phrases::LIST[$response->statusCode]; |
|
69
|
|
|
} |
|
70
|
|
|
|
|
71
|
|
|
$response->reasonPhrase = $reasonPhrase; |
|
72
|
|
|
return $response; |
|
73
|
|
|
} |
|
74
|
|
|
|
|
75
|
|
|
private function validateStatusCode($code): void |
|
76
|
|
|
{ |
|
77
|
|
|
if (!is_int($code) and !is_string($code)) { |
|
78
|
|
|
throw new InvalidArgumentException('Status code has to be an integer'); |
|
79
|
|
|
} |
|
80
|
|
|
|
|
81
|
|
|
if ($code < 100 or $code > 599) { |
|
82
|
|
|
throw new InvalidArgumentException('Status code has to be an integer between 100 and 599'); |
|
83
|
|
|
} |
|
84
|
|
|
} |
|
85
|
|
|
} |