Completed
Push — master ( 54e267...8d7cab )
by Marco
02:36
created

JsonProcessor::encode()   A

Complexity

Conditions 5
Paths 12

Size

Total Lines 21

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 10
CRAP Score 5

Importance

Changes 0
Metric Value
dl 0
loc 21
ccs 10
cts 10
cp 1
rs 9.2728
c 0
b 0
f 0
cc 5
nc 12
nop 1
crap 5
1
<?php namespace Comodojo\RpcClient\Processor;
2
3
use \Psr\Log\LoggerInterface;
4
use \Comodojo\Exception\RpcException;
5
use \Comodojo\RpcClient\RpcRequest;
6
use \Exception;
7
8
/**
9
 * @package     Comodojo Spare Parts
10
 * @author      Marco Giovinazzi <[email protected]>
11
 * @license     MIT
12
 *
13
 * LICENSE:
14
 *
15
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
21
 * THE SOFTWARE.
22
 */
23
24
class JsonProcessor extends AbstractProcessor {
25
26
    private $ids = [];
27
28
    private $is_multicall = false;
29
30
    /**
31
     * {@inheritdoc}
32
     */
33 24
    public function encode(array $requests) {
34
35 24
        $requests = array_values($requests);
36
37 24
        $this->is_multicall = sizeof($requests) > 1 ? true : false;
38
39 24
        $payload = [];
40
41 24
        foreach ($requests as $request) {
42
43 24
            list($composed, $rid) = self::composeJsonRequest($request);
44
45 24
            $payload[] = $composed;
46
47 24
            if ( $rid !== null ) $this->ids[] = $rid;
48
49 8
        }
50
51 24
        return sizeof($payload) > 1 ? json_encode($payload) : json_encode($payload[0]);
52
53
    }
54
55
    /**
56
     * {@inheritdoc}
57
     */
58 24
    public function decode($response) {
59
60
        try {
61
62 24
            if ( sizeof($this->ids) == 0 ) {
63
64 3
                return true;
65
66
            }
67
68 21
            $content = json_decode($response, true);
69
70 21
            if ( is_null($content) ) throw new Exception("Incomprehensible or empty response");
71
72 21
            if ( $this->is_multicall === false ) {
73
74 18
                if ( $content["id"] != $this->ids[0] ) throw new Exception("Invalid response ID received");
75
76 18
                $return = $content["result"];
77
78 6
            } else {
79
80 3
                $batch_content = [];
81
82 3
                foreach ( $this->ids as $key => $id ) {
83
84 3
                    if ( !isset($content[$key]) ) {
85
                        $batch_content[$key] = [
86
                            "error" => [
87
                                "code" => null,
88
                                "message" => "Empty response"
89
                            ]
90
                        ];
91 3
                    } else if ( isset($content[$key]["error"]) ) {
92
                        $batch_content[$key] = [
93
                            "error" => $content["error"]
94
                        ];
95 3
                    } else if ( !isset($content[$key]["id"]) ) {
96
                        $batch_content[$key] = [
97
                            "error" => [
98
                                "code" => null,
99
                                "message" => "Malformed response received"
100
                            ]
101
                        ];
102 3
                    } else if ( $content[$key]["id"] != $id ) {
103
                        $batch_content[$key] = [
104
                            "error" => [
105
                                "code" => null,
106
                                "message" => "Invalid response ID received"
107
                            ]
108
                        ];
109
                    } else {
110 3
                        $batch_content[$key] = [
111 3
                            "result" => $content[$key]["result"]
112 1
                        ];
113
                    }
114
115 1
                }
116
117 15
                $return = $batch_content;
118
119
            }
120
121 7
        } catch (Exception $xe) {
122
123
            throw $xe;
124
125
        }
126
127 21
        return $return;
128
129
    }
130
131 24
    private static function composeJsonRequest(RpcRequest $request) {
132
133
        $return = [
134 24
            "jsonrpc"   =>  "2.0",
135 24
            "method"    =>  $request->getMethod(),
136 24
            "params"    =>  $request->getParameters()
137 8
        ];
138
139 24
        $rid = $request->getId();
140
141 24
        if ( $rid === true ) {
142
143 12
            $id = $return["id"] = $request->getUniqueId();
144
145 16
        } else if ( is_scalar($rid) ) {
146
147 9
            $id = $return["id"] = $rid;
148
149 3
        } else {
150
151 3
            $id = null;
152
153
        }
154
155 24
        return [$return, $id];
156
157
    }
158
159
}
160