Completed
Push — master ( f743de...f8a04a )
by Daniel
03:18
created

JsonRpcResponse::get()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 4
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
c 1
b 0
f 0
dl 0
loc 4
rs 10
cc 1
eloc 2
nc 1
nop 1
1
<?php
2
3
namespace Cmobi\RabbitmqBundle\Rpc\Response;
4
5
use Cmobi\RabbitmqBundle\Rpc\Exception\JsonRpcGenericErrorException;
6
use Symfony\Component\DependencyInjection\ParameterBag\ParameterBag;
7
8
class JsonRpcResponse implements RpcResponseInterface
9
{
10
    const VERSION = '2.0';
11
12
    public $id;
13
    public $method;
14
    public $attributes;
15
    public $error;
16
17
    public function __construct(array $attributes = [], JsonRpcGenericErrorException $error = null)
18
    {
19
        $this->error = $error;
20
        $this->attributes = new ParameterBag($attributes);
21
    }
22
23
    /**
24
     * @return int|string
25
     */
26
    public function getId()
27
    {
28
        return $this->id;
29
    }
30
31
    /**
32
     * @param int|string $id
33
     */
34
    public function setId($id)
35
    {
36
        $this->id = $id;
37
    }
38
39
    /**
40
     * @return string
41
     */
42
    public function getMethod()
43
    {
44
        return $this->method;
45
    }
46
47
    /**
48
     * @param string $method
49
     */
50
    public function setMethod($method)
51
    {
52
        $this->method = $method;
53
    }
54
55
    /**
56
     * @return string
57
     */
58
    public function getVersion()
59
    {
60
        return self::VERSION;
61
    }
62
63
    /**
64
     * @return null|array
65
     */
66
    public function getError()
67
    {
68
        return $this->error;
69
    }
70
71
    /**
72
     * @param JsonRpcGenericErrorException $error
73
     */
74
    public function setError(JsonRpcGenericErrorException $error)
75
    {
76
        $this->error = $error;
77
    }
78
79
    /**
80
     * @param $key
81
     * @return mixed
82
     */
83
    public function get($key)
84
    {
85
        return $this->attributes->get($key);
86
    }
87
88
    public function __toString()
89
    {
90
        $jsonRpc = [
91
            'id' => $this->id,
92
            'jsonrpc' => self::VERSION,
93
            'result' => $this->attributes->all()
94
        ];
95
96
        if ($this->error instanceof JsonRpcGenericErrorException) {
97
            $error = json_decode((string)$this->error, true);
98
            $jsonRpc['error'] = $error;
99
            unset($jsonRpc['result']);
100
        }
101
102
        return json_encode($jsonRpc);
103
    }
104
}