1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
declare(strict_types=1); |
4
|
|
|
|
5
|
|
|
namespace Usox\HyperSonic\Response; |
6
|
|
|
|
7
|
|
|
use AaronDDM\XMLBuilder\XMLArray; |
8
|
|
|
use AaronDDM\XMLBuilder\XMLBuilder; |
9
|
|
|
use Psr\Http\Message\ResponseInterface; |
10
|
|
|
use Usox\HyperSonic\Exception\ErrorCodeEnum; |
11
|
|
|
|
12
|
|
|
/** |
13
|
|
|
* Writes response data in xml format |
14
|
|
|
*/ |
15
|
|
|
final class XmlResponseWriter implements ResponseWriterInterface |
16
|
|
|
{ |
17
|
|
|
private ?XMLArray $rootNode = null; |
18
|
|
|
|
19
|
3 |
|
public function __construct( |
20
|
|
|
private readonly XMLBuilder $xmlBuilder, |
21
|
|
|
private readonly string $apiVersion, |
22
|
|
|
) { |
23
|
3 |
|
} |
24
|
|
|
|
25
|
|
|
/** |
26
|
|
|
* Write response for successful api requests |
27
|
|
|
*/ |
28
|
1 |
|
public function write( |
29
|
|
|
ResponseInterface $response, |
30
|
|
|
FormattedResponderInterface $responder, |
31
|
|
|
): ResponseInterface { |
32
|
1 |
|
$rootNode = $this->getRootNode(); |
33
|
|
|
|
34
|
1 |
|
$responder->writeXml($rootNode); |
35
|
|
|
|
36
|
1 |
|
$rootNode->end(); |
37
|
|
|
|
38
|
1 |
|
return $this->writeToResponse($response); |
39
|
|
|
} |
40
|
|
|
|
41
|
|
|
/** |
42
|
|
|
* Write response for erroneous api requests |
43
|
|
|
*/ |
44
|
1 |
|
public function writeError( |
45
|
|
|
ResponseInterface $response, |
46
|
|
|
ErrorCodeEnum $errorCode, |
47
|
|
|
string $message = '' |
48
|
|
|
): ResponseInterface { |
49
|
1 |
|
$this->xmlBuilder->createXMLArray() |
50
|
1 |
|
->start( |
51
|
1 |
|
'subsonic-response', |
52
|
1 |
|
[ |
53
|
1 |
|
'xmlns' => 'http://subsonic.org/restapi', |
54
|
1 |
|
'status' => 'failed', |
55
|
1 |
|
'version' => $this->apiVersion, |
56
|
1 |
|
] |
57
|
1 |
|
) |
58
|
1 |
|
->add( |
59
|
1 |
|
'error', |
60
|
1 |
|
null, |
61
|
1 |
|
['code' => $errorCode->value, 'message' => $message] |
62
|
1 |
|
) |
63
|
1 |
|
->end(); |
64
|
|
|
|
65
|
1 |
|
return $this->writeToResponse($response); |
66
|
|
|
} |
67
|
|
|
|
68
|
2 |
|
private function writeToResponse( |
69
|
|
|
ResponseInterface $response |
70
|
|
|
): ResponseInterface { |
71
|
2 |
|
$response->getBody()->write( |
72
|
2 |
|
$this->xmlBuilder->getXML() |
73
|
2 |
|
); |
74
|
|
|
|
75
|
2 |
|
return $response->withHeader('Content-Type', 'application/xml'); |
|
|
|
|
76
|
|
|
} |
77
|
|
|
|
78
|
1 |
|
private function getRootNode(): XMLArray |
79
|
|
|
{ |
80
|
1 |
|
if ($this->rootNode === null) { |
81
|
1 |
|
$this->rootNode = $this->xmlBuilder->createXMLArray() |
82
|
1 |
|
->start( |
83
|
1 |
|
'subsonic-response', |
84
|
1 |
|
[ |
85
|
1 |
|
'xmlns' => 'http://subsonic.org/restapi', |
86
|
1 |
|
'status' => 'ok', |
87
|
1 |
|
'version' => $this->apiVersion, |
88
|
1 |
|
] |
89
|
1 |
|
); |
90
|
|
|
} |
91
|
|
|
|
92
|
1 |
|
return $this->rootNode; |
|
|
|
|
93
|
|
|
} |
94
|
|
|
} |
95
|
|
|
|