|
1
|
|
|
<?php |
|
2
|
|
|
|
|
3
|
|
|
declare(strict_types=1); |
|
4
|
|
|
|
|
5
|
|
|
namespace Usox\HyperSonic\Response; |
|
6
|
|
|
|
|
7
|
|
|
use Psr\Http\Message\ResponseInterface; |
|
8
|
|
|
use Usox\HyperSonic\Exception\ErrorCodeEnum; |
|
9
|
|
|
|
|
10
|
|
|
/** |
|
11
|
|
|
* Writes response data in json format |
|
12
|
|
|
*/ |
|
13
|
|
|
final class JsonResponseWriter implements ResponseWriterInterface |
|
14
|
|
|
{ |
|
15
|
3 |
|
public function __construct( |
|
16
|
|
|
private readonly string $apiVersion |
|
17
|
|
|
) { |
|
18
|
3 |
|
} |
|
19
|
|
|
|
|
20
|
|
|
/** |
|
21
|
|
|
* Write response for successful api requests |
|
22
|
|
|
*/ |
|
23
|
1 |
|
public function write( |
|
24
|
|
|
ResponseInterface $response, |
|
25
|
|
|
FormattedResponderInterface $responder |
|
26
|
|
|
): ResponseInterface { |
|
27
|
1 |
|
$root = [ |
|
28
|
1 |
|
'status' => 'ok', |
|
29
|
1 |
|
'version' => $this->apiVersion, |
|
30
|
1 |
|
]; |
|
31
|
|
|
|
|
32
|
1 |
|
$responder->writeJson($root); |
|
33
|
|
|
|
|
34
|
1 |
|
return $this->writeToResponse( |
|
35
|
1 |
|
$response, |
|
36
|
1 |
|
$root |
|
37
|
1 |
|
); |
|
38
|
|
|
} |
|
39
|
|
|
|
|
40
|
|
|
/** |
|
41
|
|
|
* Write response for erroneous api requests |
|
42
|
|
|
*/ |
|
43
|
1 |
|
public function writeError( |
|
44
|
|
|
ResponseInterface $response, |
|
45
|
|
|
ErrorCodeEnum $errorCode, |
|
46
|
|
|
string $message = '' |
|
47
|
|
|
): ResponseInterface { |
|
48
|
1 |
|
return $this->writeToResponse( |
|
49
|
1 |
|
$response, |
|
50
|
1 |
|
[ |
|
51
|
1 |
|
'status' => 'failed', |
|
52
|
1 |
|
'version' => $this->apiVersion, |
|
53
|
1 |
|
'error' => [ |
|
54
|
1 |
|
'code' => $errorCode->value, |
|
55
|
1 |
|
'message' => $message, |
|
56
|
1 |
|
], |
|
57
|
1 |
|
] |
|
58
|
1 |
|
); |
|
59
|
|
|
} |
|
60
|
|
|
|
|
61
|
|
|
/** |
|
62
|
|
|
* @param array<mixed> $data |
|
63
|
|
|
*/ |
|
64
|
2 |
|
private function writeToResponse( |
|
65
|
|
|
ResponseInterface $response, |
|
66
|
|
|
array $data |
|
67
|
|
|
): ResponseInterface { |
|
68
|
2 |
|
$response->getBody()->write( |
|
69
|
2 |
|
(string) json_encode( |
|
70
|
2 |
|
['subsonic-response' => $data], |
|
71
|
2 |
|
JSON_PRETTY_PRINT |
|
72
|
2 |
|
) |
|
73
|
2 |
|
); |
|
74
|
|
|
|
|
75
|
2 |
|
return $response->withHeader('Content-Type', 'application/json'); |
|
|
|
|
|
|
76
|
|
|
} |
|
77
|
|
|
} |
|
78
|
|
|
|