1
|
|
|
<?php |
2
|
|
|
namespace Yoanm\JsonRpcServer\App\Creator; |
3
|
|
|
|
4
|
|
|
use Yoanm\JsonRpcServer\Domain\Exception\JsonRpcExceptionInterface; |
5
|
|
|
use Yoanm\JsonRpcServer\Domain\Exception\JsonRpcInternalErrorException; |
6
|
|
|
use Yoanm\JsonRpcServer\Domain\Model\JsonRpcRequest; |
7
|
|
|
use Yoanm\JsonRpcServer\Domain\Model\JsonRpcResponse; |
8
|
|
|
|
9
|
|
|
/** |
10
|
|
|
* Class ResponseCreator |
11
|
|
|
*/ |
12
|
|
|
class ResponseCreator |
13
|
|
|
{ |
14
|
|
|
/** |
15
|
|
|
* @param JsonRpcRequest|null $fromRequest |
16
|
|
|
* |
17
|
|
|
* @return JsonRpcResponse |
18
|
|
|
*/ |
19
|
51 |
|
public function createEmptyResponse(JsonRpcRequest $fromRequest = null) : JsonRpcResponse |
20
|
|
|
{ |
21
|
51 |
|
if (null === $fromRequest) { |
22
|
27 |
|
return new JsonRpcResponse(); |
23
|
|
|
} |
24
|
|
|
|
25
|
26 |
|
$response = (new JsonRpcResponse($fromRequest->getJsonRpc())) |
26
|
26 |
|
->setIsNotification($fromRequest->isNotification()) |
27
|
26 |
|
; |
28
|
|
|
|
29
|
|
|
// Notification response doesn't have any ID defined (notification request doesn't either) |
30
|
26 |
|
if (!$fromRequest->isNotification()) { |
31
|
20 |
|
$response->setId($fromRequest->getId()); |
32
|
|
|
} |
33
|
|
|
|
34
|
26 |
|
return $response; |
35
|
|
|
} |
36
|
|
|
|
37
|
|
|
/** |
38
|
|
|
* @param mixed $result |
39
|
|
|
* @param JsonRpcRequest|null $fromRequest |
40
|
|
|
* |
41
|
|
|
* @return JsonRpcResponse |
42
|
|
|
*/ |
43
|
12 |
|
public function createResultResponse($result, JsonRpcRequest $fromRequest = null) : JsonRpcResponse |
44
|
|
|
{ |
45
|
12 |
|
return $this->createEmptyResponse($fromRequest) |
46
|
12 |
|
->setResult($result); |
47
|
|
|
} |
48
|
|
|
|
49
|
|
|
/** |
50
|
|
|
* @param \Exception $exception |
51
|
|
|
* @param JsonRpcRequest|null $fromRequest |
52
|
|
|
* |
53
|
|
|
* @return JsonRpcResponse |
54
|
|
|
*/ |
55
|
39 |
|
public function createErrorResponse(\Exception $exception, JsonRpcRequest $fromRequest = null) : JsonRpcResponse |
56
|
|
|
{ |
57
|
39 |
|
return $this->createEmptyResponse($fromRequest) |
58
|
39 |
|
->setError( |
59
|
39 |
|
$exception instanceof JsonRpcExceptionInterface |
60
|
32 |
|
? $exception |
61
|
39 |
|
: new JsonRpcInternalErrorException($exception) |
62
|
39 |
|
) |
63
|
39 |
|
; |
64
|
|
|
} |
65
|
|
|
} |
66
|
|
|
|