Completed
Pull Request — feature/app (#3)
by Yo
01:42
created

ResponseNormalizer::normalize()   A

Complexity

Conditions 3
Paths 3

Size

Total Lines 20
Code Lines 11

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 10
CRAP Score 3

Importance

Changes 0
Metric Value
cc 3
eloc 11
nc 3
nop 1
dl 0
loc 20
ccs 10
cts 10
cp 1
crap 3
rs 9.4285
c 0
b 0
f 0
1
<?php
2
namespace Yoanm\JsonRpcServer\App\Serialization;
3
4
use Yoanm\JsonRpcServer\Domain\Exception\JsonRpcExceptionInterface;
5
use Yoanm\JsonRpcServer\Domain\Model\JsonRpcResponse;
6
7
/**
8
 * Class ResponseNormalizer
9
 */
10
class ResponseNormalizer
11
{
12
    const KEY_JSON_RPC = 'json-rpc';
13
    const KEY_ID = 'id';
14
    const KEY_RESULT = 'result';
15
    const KEY_ERROR = 'error';
16
17
    const SUB_KEY_ERROR_CODE = 'code';
18
    const SUB_KEY_ERROR_MESSAGE = 'message';
19
    const SUB_KEY_ERROR_DATA = 'data';
20
21
    /**
22
     * @param JsonRpcResponse $response
23
     *
24
     * @return array|null
25
     */
26 6
    public function normalize(JsonRpcResponse $response)
27
    {
28 6
        if ($response->isNotification()) {
29 1
            return null;
30
        }
31
32
        $data = [
33 5
            self::KEY_JSON_RPC => $response->getJsonRpc(),
34 5
            self::KEY_ID => $response->getId()
35
        ];
36
37 5
        if ($response->getError()) {
38 2
            $data[self::KEY_ERROR] = $this->normalizeError(
39 2
                $response->getError()
40
            );
41
        } else {
42 3
            $data[self::KEY_RESULT] = $response->getResult();
43
        }
44
45 5
        return $data;
46
    }
47
48
    /**
49
     * @param JsonRpcExceptionInterface $error
50
     *
51
     * @return array
52
     */
53 2
    private function normalizeError(JsonRpcExceptionInterface $error)
54
    {
55
        $normalizedError = [
56 2
            self::SUB_KEY_ERROR_CODE => $error->getErrorCode(),
57 2
            self::SUB_KEY_ERROR_MESSAGE => $error->getErrorMessage()
58
        ];
59
60 2
        if ($error->getErrorData()) {
61 1
            $normalizedError[self::SUB_KEY_ERROR_DATA] = $error->getErrorData();
62
        }
63
64 2
        return $normalizedError;
65
    }
66
}
67