Passed
Branch release/0.1.0 (dcda87)
by Yo
02:43 queued 44s
created

ResponseCreator   A

Complexity

Total Complexity 6

Size/Duplication

Total Lines 50
Duplicated Lines 0 %

Test Coverage

Coverage 100%

Importance

Changes 0
Metric Value
dl 0
loc 50
ccs 18
cts 18
cp 1
rs 10
c 0
b 0
f 0
wmc 6

3 Methods

Rating   Name   Duplication   Size   Complexity  
A createEmptyResponse() 0 15 3
A createErrorResponse() 0 8 2
A createResultResponse() 0 4 1
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 10
    public function createEmptyResponse(JsonRpcRequest $fromRequest = null) : JsonRpcResponse
20
    {
21 10
        if (null === $fromRequest) {
22 6
            return new JsonRpcResponse();
23
        }
24
25 4
        $response = (new JsonRpcResponse($fromRequest->getJsonRpc()))
26 4
                ->setIsNotification($fromRequest->isNotification())
27
        ;
28
29 4
        if ($fromRequest->getId()) {
30 3
            $response->setId($fromRequest->getId());
31
        }
32
33 4
        return $response;
34
    }
35
36
    /**
37
     * @param mixed               $result
38
     * @param JsonRpcRequest|null $fromRequest
39
     *
40
     * @return JsonRpcResponse
41
     */
42 3
    public function createResultResponse($result, JsonRpcRequest $fromRequest = null) : JsonRpcResponse
43
    {
44 3
        return $this->createEmptyResponse($fromRequest)
45 3
            ->setResult($result);
46
    }
47
48
    /**
49
     * @param \Exception          $exception
50
     * @param JsonRpcRequest|null $fromRequest
51
     *
52
     * @return JsonRpcResponse
53
     */
54 4
    public function createErrorResponse(\Exception $exception, JsonRpcRequest $fromRequest = null) : JsonRpcResponse
55
    {
56 4
        return $this->createEmptyResponse($fromRequest)
57 4
            ->setIsNotification(false)
58 4
            ->setError(
59 4
                $exception instanceof JsonRpcExceptionInterface
60 3
                    ? $exception
61 4
                    : new JsonRpcInternalErrorException($exception)
62
            )
63
        ;
64
    }
65
}
66