Server::handle()   A
last analyzed

Complexity

Conditions 4
Paths 5

Size

Total Lines 19
Code Lines 13

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
c 1
b 0
f 0
dl 0
loc 19
rs 9.2
cc 4
eloc 13
nc 5
nop 1
1
<?php
2
3
namespace Tonic\Component\ApiLayer\JsonRpc;
4
5
use Tonic\Component\ApiLayer\JsonRpc\Method\MethodDispatcherInterface;
6
use Tonic\Component\ApiLayer\JsonRpc\Request\RequestParserInterface;
7
use Tonic\Component\ApiLayer\JsonRpc\Response\ErrorResponseFactory;
8
use Tonic\Component\ApiLayer\JsonRpc\Response\ResponseSerializerInterface;
9
use Tonic\Component\ApiLayer\JsonRpc\Response\SuccessResponse;
10
11
/**
12
 * Responsible for handling JSON-RPC request and provide appropriate JSON-RPC response.
13
 */
14
class Server implements ServerInterface
15
{
16
    /**
17
     * @var RequestParserInterface
18
     */
19
    private $requestParser;
20
21
    /**
22
     * @var MethodDispatcherInterface
23
     */
24
    private $methodDispatcher;
25
26
    /**
27
     * @var ResponseSerializerInterface
28
     */
29
    private $responseSerializer;
30
    /**
31
     * @var ErrorResponseFactory
32
     */
33
    private $errorResponseFactory;
34
35
    /**
36
     * Constructor.
37
     *
38
     * @param RequestParserInterface      $requestParser
39
     * @param MethodDispatcherInterface   $methodDispatcher
40
     * @param ResponseSerializerInterface $responseSerializer
41
     * @param ErrorResponseFactory        $errorResponseFactory
42
     */
43
    public function __construct(
44
        RequestParserInterface $requestParser,
45
        MethodDispatcherInterface $methodDispatcher,
46
        ResponseSerializerInterface $responseSerializer,
47
        ErrorResponseFactory $errorResponseFactory
48
    ) {
49
        $this->requestParser = $requestParser;
50
        $this->methodDispatcher = $methodDispatcher;
51
        $this->responseSerializer = $responseSerializer;
52
        $this->errorResponseFactory = $errorResponseFactory;
53
    }
54
55
    /**
56
     * {@inheritdoc}
57
     */
58
    public function handle($requestContent)
59
    {
60
        $request = null;
61
        try {
62
            $request = $this->requestParser->parse($requestContent);
63
            $result = $this->methodDispatcher->dispatch($request->getMethod(), $request->getParams());
64
            $response = new SuccessResponse($request->getId(), $result);
65
            $responseContent = $this->responseSerializer->serializeResponse($request->getVersion(), $response);
66
        } catch (\Exception $e) {
67
            $response = $this->errorResponseFactory->createForException($e, $request ? $request->getId() : null);
68
69
            $responseContent = $this->responseSerializer->serializeResponse(
70
                $request ? $request->getVersion() : '2.0',
71
                $response
72
            );
73
        }
74
75
        return $responseContent;
76
    }
77
}
78