Completed
Push — master ( 8bbcd1...4bee86 )
by Denis
04:24
created

Server::__construct()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 8
Code Lines 5

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 8
c 0
b 0
f 0
rs 9.4285
cc 1
eloc 5
nc 1
nop 1
1
<?php
2
3
namespace PhpJsonRpc;
4
5
use PhpJsonRpc\Server\Processor;
6
use PhpJsonRpc\Server\RequestParser;
7
use PhpJsonRpc\Server\ResponseBuilder;
8
use PhpJsonRpc\Server\MapperInterface;
9
10
/**
11
 * Implementation of JSON-RPC2 specification
12
 *
13
 * @link http://www.jsonrpc.org/specification 
14
 */
15
class Server
16
{
17
    /**
18
     * @var string array
19
     */
20
    private $payload;
21
22
    /**
23
     * @var Processor
24
     */
25
    private $processor;
26
27
    /**
28
     * @var RequestParser
29
     */
30
    private $requestParser;
31
32
    /**
33
     * @var ResponseBuilder
34
     */
35
    private $responseBuilder;
36
37
    /**
38
     * Server constructor.
39
     *
40
     * @param string $payload
41
     */
42
    public function __construct(string $payload = null)
43
    {
44
        $this->payload   = $payload ?? file_get_contents('php://input');
45
        $this->processor = new Processor();
46
47
        $this->requestParser   = new RequestParser();
48
        $this->responseBuilder = new ResponseBuilder();
49
    }
50
51
    /**
52
     * Add handler-object for handling request
53
     *
54
     * @param mixed $object
55
     * @return $this
56
     */
57
    public function addHandler($object)
58
    {
59
        $this->processor->addHandler($object);
60
        return $this;
61
    }
62
63
    /**
64
     * Add mapper-object for mapping request-method on class and method
65
     *
66
     * @param MapperInterface $mapper
67
     * @return $this
68
     */
69
    public function addMapper(MapperInterface $mapper)
70
    {
71
        $this->processor->addMapper($mapper);
72
        return $this;
73
    }
74
75
    /**
76
     * Run server
77
     *
78
     * @return string
79
     */
80
    public function execute(): string
81
    {
82
        $calls  = $this->requestParser->parse($this->payload);
83
        $result = $this->processor->process($calls);
84
85
        return $this->responseBuilder->build($result);
86
    }
87
}
88