Failed Conditions
Pull Request — master (#1)
by Yo
05:58 queued 03:23
created

ResponseCreator::createEmptyResponse()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 9
Code Lines 5

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 6

Importance

Changes 0
Metric Value
cc 2
eloc 5
nc 2
nop 1
dl 0
loc 9
ccs 0
cts 9
cp 0
crap 6
rs 9.6666
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
    public function createEmptyResponse(JsonRpcRequest $fromRequest = null) : JsonRpcResponse
20
    {
21
        return null === $fromRequest
22
            ? new JsonRpcResponse()
23
            : (
24
                new JsonRpcResponse($fromRequest->getJsonRpc())
25
            )
26
                ->setIsNotification($fromRequest->isNotification())
27
                ->setId($fromRequest->getId())
28
        ;
29
    }
30
31
    /**
32
     * @param mixed               $result
33
     * @param JsonRpcRequest|null $fromRequest
34
     *
35
     * @return JsonRpcResponse
36
     */
37
    public function createResultResponse($result, JsonRpcRequest $fromRequest = null) : JsonRpcResponse
38
    {
39
        return $this->createEmptyResponse($fromRequest)
40
            ->setResult($result);
41
    }
42
43
    /**
44
     * @param \Exception          $exception
45
     * @param JsonRpcRequest|null $fromRequest
46
     *
47
     * @return JsonRpcResponse
48
     */
49
    public function createErrorResponse(\Exception $exception, JsonRpcRequest $fromRequest = null) : JsonRpcResponse
50
    {
51
        return $this->createEmptyResponse($fromRequest)
52
            ->setIsNotification(false)
53
            ->setError(
54
                $exception instanceof JsonRpcExceptionInterface
55
                    ? $exception
56
                    : new JsonRpcInternalErrorException($exception)
57
            )
58
        ;
59
    }
60
}
61