1
|
|
|
<?php /** @noinspection PhpRedundantCatchClauseInspection */ |
2
|
|
|
|
3
|
|
|
namespace DMT\Aura\Psr\Message; |
4
|
|
|
|
5
|
|
|
use Aura\Web\Exception\InvalidStatusCode; |
6
|
|
|
use Aura\Web\Response as AuraResponse; |
7
|
|
|
use Aura\Web\WebFactory; |
8
|
|
|
use InvalidArgumentException; |
9
|
|
|
use Psr\Http\Message\ResponseInterface; |
10
|
|
|
|
11
|
|
|
/** |
12
|
|
|
* Class Response |
13
|
|
|
* |
14
|
|
|
* @package DMT\Aura\Psr\Message |
15
|
|
|
*/ |
16
|
|
|
class Response implements ResponseInterface |
17
|
|
|
{ |
18
|
|
|
use MessageTrait; |
|
|
|
|
19
|
|
|
|
20
|
|
|
/** |
21
|
|
|
* Response constructor. |
22
|
|
|
* |
23
|
|
|
* @param int $code |
24
|
|
|
* @param string $reasonPhrase |
25
|
|
|
*/ |
26
|
35 |
|
public function __construct(int $code = 200, string $reasonPhrase = '') |
27
|
|
|
{ |
28
|
35 |
|
$this->getInnerObject()->status->set($code, $reasonPhrase); |
29
|
35 |
|
} |
30
|
|
|
|
31
|
|
|
/** |
32
|
|
|
* @return AuraResponse |
33
|
|
|
*/ |
34
|
35 |
|
public function getInnerObject(): AuraResponse |
35
|
|
|
{ |
36
|
35 |
|
if (!$this->object) { |
37
|
35 |
|
$this->object = (new WebFactory([]))->newResponse(); |
38
|
|
|
} |
39
|
35 |
|
return $this->object; |
|
|
|
|
40
|
|
|
} |
41
|
|
|
|
42
|
|
|
/** |
43
|
|
|
* Gets the response status code. |
44
|
|
|
* |
45
|
|
|
* @return int Status code. |
46
|
|
|
*/ |
47
|
3 |
|
public function getStatusCode(): int |
48
|
|
|
{ |
49
|
3 |
|
return $this->getInnerObject()->status->getCode(); |
50
|
|
|
} |
51
|
|
|
|
52
|
|
|
/** |
53
|
|
|
* Return an instance with the specified status code and, optionally, reason phrase. |
54
|
|
|
* |
55
|
|
|
* @param int $code The 3-digit integer result code to set. |
56
|
|
|
* @param string $reasonPhrase The reason phrase to use. |
57
|
|
|
* @return static |
58
|
|
|
* @throws InvalidArgumentException |
59
|
|
|
*/ |
60
|
8 |
|
public function withStatus($code, $reasonPhrase = ''): self |
61
|
|
|
{ |
62
|
8 |
|
if (!is_int($code)) { |
|
|
|
|
63
|
4 |
|
throw new InvalidArgumentException('invalid status code given'); |
64
|
|
|
} |
65
|
|
|
|
66
|
|
|
try { |
67
|
4 |
|
$instance = clone($this); |
68
|
4 |
|
$instance->getInnerObject()->status->set($code, $reasonPhrase); |
69
|
|
|
|
70
|
2 |
|
return $instance; |
71
|
2 |
|
} catch (InvalidStatusCode $exception) { |
72
|
2 |
|
throw new InvalidArgumentException('invalid status code given'); |
73
|
|
|
} |
74
|
|
|
} |
75
|
|
|
|
76
|
|
|
/** |
77
|
|
|
* Gets the response reason phrase associated with the status code. |
78
|
|
|
* |
79
|
|
|
* @return string |
80
|
|
|
*/ |
81
|
2 |
|
public function getReasonPhrase(): string |
82
|
|
|
{ |
83
|
2 |
|
return $this->getInnerObject()->status->getPhrase() ?? ''; |
84
|
|
|
} |
85
|
|
|
} |