Failed Conditions
Pull Request — release/3.0.0-dev (#32)
by Yo
01:46
created

ResponseCreator::createEmptyResponse()   A

Complexity

Conditions 3
Paths 3

Size

Total Lines 15
Code Lines 7

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 8
CRAP Score 3

Importance

Changes 0
Metric Value
cc 3
eloc 7
nc 3
nop 1
dl 0
loc 15
ccs 8
cts 8
cp 1
crap 3
rs 9.4285
c 0
b 0
f 0
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
            ->setError(
58 4
                $exception instanceof JsonRpcExceptionInterface
59 3
                    ? $exception
60 4
                    : new JsonRpcInternalErrorException($exception)
61
            )
62
        ;
63
    }
64
}
65