|
1
|
|
|
<?php |
|
2
|
|
|
|
|
3
|
|
|
namespace PhpJsonRpc\Server; |
|
4
|
|
|
|
|
5
|
|
|
use PhpJsonRpc\Core\Result\AbstractResult; |
|
6
|
|
|
use PhpJsonRpc\Core\Result\ResultError; |
|
7
|
|
|
use PhpJsonRpc\Core\Result\ResultUnit; |
|
8
|
|
|
use PhpJsonRpc\Core\ResultSpecifier; |
|
9
|
|
|
use PhpJsonRpc\Error\JsonRpcException; |
|
10
|
|
|
|
|
11
|
|
|
class ResponseBuilder |
|
12
|
|
|
{ |
|
13
|
|
|
/** |
|
14
|
|
|
* @param ResultSpecifier $result |
|
15
|
|
|
* |
|
16
|
|
|
* @return string |
|
17
|
|
|
*/ |
|
18
|
|
|
public function build(ResultSpecifier $result): string |
|
19
|
|
|
{ |
|
20
|
|
|
$response = []; |
|
21
|
|
|
$units = $result->getResults(); |
|
22
|
|
|
|
|
23
|
|
|
foreach ($units as $unit) { |
|
24
|
|
|
/** @var AbstractResult $unit */ |
|
25
|
|
|
if ($unit instanceof ResultUnit) { |
|
26
|
|
|
/** @var ResultUnit $unit */ |
|
27
|
|
|
$response[] = [ |
|
28
|
|
|
'jsonrpc' => '2.0', |
|
29
|
|
|
'result' => $unit->getResult(), |
|
30
|
|
|
'id' => $unit->getId() |
|
31
|
|
|
]; |
|
32
|
|
|
} elseif ($unit instanceof ResultError) { |
|
33
|
|
|
/** @var ResultError $unit */ |
|
34
|
|
|
$baseException = $unit->getBaseException(); |
|
35
|
|
|
$response[] = [ |
|
36
|
|
|
'jsonrpc' => '2.0', |
|
37
|
|
|
'error' => [ |
|
38
|
|
|
'code' => $baseException->getJsonRpcCode(), |
|
39
|
|
|
'message' => $this->getErrorMessage($baseException->getJsonRpcCode()), |
|
40
|
|
|
'data' => $baseException->getJsonRpcData() |
|
41
|
|
|
], |
|
42
|
|
|
'id' => null |
|
43
|
|
|
]; |
|
44
|
|
|
} |
|
45
|
|
|
} |
|
46
|
|
|
|
|
47
|
|
|
if (empty($response)) { |
|
48
|
|
|
return ''; |
|
49
|
|
|
} |
|
50
|
|
|
|
|
51
|
|
|
if ($result->isSingleResult()) { |
|
52
|
|
|
return json_encode($response[0]); |
|
53
|
|
|
} |
|
54
|
|
|
|
|
55
|
|
|
return json_encode($response); |
|
56
|
|
|
} |
|
57
|
|
|
|
|
58
|
|
|
/** |
|
59
|
|
|
* @param int $code |
|
60
|
|
|
* @return string |
|
61
|
|
|
*/ |
|
62
|
|
|
private function getErrorMessage(int $code): string |
|
63
|
|
|
{ |
|
64
|
|
|
switch ($code) { |
|
65
|
|
|
case JsonRpcException::PARSE_ERROR: |
|
66
|
|
|
return 'Parse error'; |
|
67
|
|
|
|
|
68
|
|
|
case JsonRpcException::INVALID_REQUEST: |
|
69
|
|
|
return 'Invalid Request'; |
|
70
|
|
|
|
|
71
|
|
|
case JsonRpcException::METHOD_NOT_FOUND: |
|
72
|
|
|
return 'Method not found'; |
|
73
|
|
|
|
|
74
|
|
|
case JsonRpcException::INVALID_PARAMS: |
|
75
|
|
|
return 'Invalid params'; |
|
76
|
|
|
|
|
77
|
|
|
case JsonRpcException::INTERNAL_ERROR: |
|
78
|
|
|
return 'Internal error'; |
|
79
|
|
|
|
|
80
|
|
|
case JsonRpcException::SERVER_ERROR: |
|
81
|
|
|
return 'Server Error'; |
|
82
|
|
|
|
|
83
|
|
|
default: |
|
84
|
|
|
return 'Internal error'; |
|
85
|
|
|
} |
|
86
|
|
|
} |
|
87
|
|
|
} |
|
88
|
|
|
|