|
1
|
|
|
<?php |
|
2
|
|
|
declare(strict_types=1); |
|
3
|
|
|
|
|
4
|
|
|
namespace PTS\Psr7\Response; |
|
5
|
|
|
|
|
6
|
|
|
use Psr\Http\Message\StreamInterface; |
|
7
|
|
|
use PTS\Psr7\Message; |
|
8
|
|
|
use PTS\Psr7\Response as HttpResponse; |
|
9
|
|
|
use PTS\Psr7\Stream; |
|
10
|
|
|
|
|
11
|
|
|
class JsonResponse extends HttpResponse implements JsonResponseInterface |
|
12
|
|
|
{ |
|
13
|
|
|
protected array $data = []; |
|
14
|
|
|
protected bool $isSyncBody = false; |
|
15
|
|
|
|
|
16
|
7 |
|
public function __construct( |
|
17
|
|
|
array $data, |
|
18
|
|
|
int $status = 200, |
|
19
|
|
|
array $headers = [], |
|
20
|
|
|
string $version = '1.1' |
|
21
|
|
|
) { |
|
22
|
7 |
|
$headers['Content-Type'] = 'application/json'; |
|
23
|
7 |
|
parent::__construct($status, $headers, null, $version); |
|
24
|
7 |
|
$this->data = $data; |
|
25
|
7 |
|
} |
|
26
|
|
|
|
|
27
|
3 |
|
public function getData(): array |
|
28
|
|
|
{ |
|
29
|
3 |
|
return $this->data; |
|
30
|
|
|
} |
|
31
|
|
|
|
|
32
|
|
|
// @todo very slow, need php bench test and add method getContent |
|
33
|
5 |
|
public function getBody(): StreamInterface |
|
34
|
|
|
{ |
|
35
|
5 |
|
if (!$this->isSyncBody) { |
|
36
|
5 |
|
$this->isSyncBody = true; |
|
37
|
5 |
|
$data = json_encode($this->data, JSON_THROW_ON_ERROR | JSON_UNESCAPED_UNICODE, 512); |
|
38
|
5 |
|
parent::withBody(Stream::create($data)); |
|
39
|
|
|
} |
|
40
|
|
|
|
|
41
|
5 |
|
return parent::getBody(); |
|
42
|
|
|
} |
|
43
|
|
|
|
|
44
|
|
|
public function getContent(): string |
|
45
|
|
|
{ |
|
46
|
|
|
return json_encode($this->data, JSON_THROW_ON_ERROR | JSON_UNESCAPED_UNICODE); |
|
47
|
|
|
} |
|
48
|
|
|
|
|
49
|
1 |
|
public function withBody(StreamInterface $body): Message |
|
50
|
|
|
{ |
|
51
|
1 |
|
$this->data = json_decode((string)$body, true, 512, JSON_THROW_ON_ERROR); |
|
52
|
1 |
|
$this->isSyncBody = true; |
|
53
|
1 |
|
return parent::withBody($body); |
|
54
|
|
|
} |
|
55
|
|
|
|
|
56
|
1 |
|
public function setData(array $data): static |
|
57
|
|
|
{ |
|
58
|
1 |
|
$this->isSyncBody = false; |
|
59
|
1 |
|
$this->data = $data; |
|
60
|
1 |
|
return $this; |
|
61
|
|
|
} |
|
62
|
|
|
|
|
63
|
1 |
|
public function reset(): static |
|
64
|
|
|
{ |
|
65
|
1 |
|
$this->isSyncBody = false; |
|
66
|
1 |
|
$this->data = []; |
|
67
|
1 |
|
$this->protocol = '1.1'; |
|
68
|
1 |
|
$this->statusCode = 200; |
|
69
|
1 |
|
$this->attributes = []; |
|
70
|
1 |
|
$this->headers = ['content-type' => ['application/json']]; |
|
71
|
|
|
|
|
72
|
1 |
|
if ($this->stream) { |
|
73
|
1 |
|
$this->stream->close(); |
|
74
|
1 |
|
$this->stream = null; |
|
75
|
|
|
} |
|
76
|
|
|
|
|
77
|
1 |
|
return $this; |
|
78
|
|
|
} |
|
79
|
|
|
} |