Completed
Push — master ( 064a57...a259e3 )
by Anton
01:47
created

JsonRPC::handleBody()   A

Complexity

Conditions 3
Paths 3

Size

Total Lines 12
Code Lines 6

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 12
rs 9.4285
c 0
b 0
f 0
cc 3
eloc 6
nc 3
nop 2
1
<?php
2
/**
3
 * Dead simple, high performance, drop-in bridge to Golang RPC with zero dependencies
4
 *
5
 * @author Wolfy-J
6
 */
7
8
namespace Spiral\Goridge;
9
10
use Spiral\Goridge\Exceptions\ServiceException;
11
12
/**
13
 * Packs client requests and responses using JSON.
14
 */
15
class JsonRPC
16
{
17
    /** @var \Spiral\Goridge\ConnectionInterface */
18
    private $conn;
19
20
    /**
21
     * @param \Spiral\Goridge\ConnectionInterface $conn
22
     */
23
    public function __construct(ConnectionInterface $conn)
24
    {
25
        $this->conn = $conn;
26
    }
27
28
    /**
29
     * @param string $method
30
     * @param mixed  $argument An input argument or array of arguments for complex types.
31
     * @param int    $flags    Payload control flags.
32
     *
33
     * @return mixed
34
     *
35
     * @throws \Spiral\Goridge\Exceptions\TransportException
36
     * @throws \Spiral\Goridge\Exceptions\ServiceException
37
     */
38
    public function call(string $method, $argument, int $flags = 0)
39
    {
40
        $this->conn->send($method);
41
42
        if ($flags & ConnectionInterface::RAW_BODY) {
43
            $this->conn->send($argument, $flags);
44
        } else {
45
            $body = json_encode($argument);
46
            if ($body === false) {
47
                throws new ServiceException(sprintf(
0 ignored issues
show
Bug introduced by
This code did not parse for me. Apparently, there is an error somewhere around this line:

Syntax error, unexpected T_NEW
Loading history...
48
                    "json error: %s",
49
                    json_last_error_msg()
50
                ));
51
            }
52
            
53
            $this->conn->send(json_encode($argument));
54
        }
55
56
        $body = $this->conn->receiveSync($flags);
57
58
        return $this->handleBody($body, $flags);
59
    }
60
61
    /**
62
     * Handle response body.
63
     *
64
     * @param string|binary $body
65
     * @param int           $flags
66
     *
67
     * @return mixed
68
     *
69
     * @throws \Spiral\Goridge\Exceptions\ServiceException
70
     */
71
    protected function handleBody($body, int $flags)
72
    {
73
        if ($flags & ConnectionInterface::ERROR_BODY) {
74
            throw new ServiceException("error '$body' on '{$this->conn}'");
75
        }
76
77
        if ($flags & ConnectionInterface::RAW_BODY) {
78
            return $body;
79
        }
80
81
        return json_decode($body, true);
82
    }
83
}
84