1: <?php
2:
3: /**
4: * Jyxo PHP Library
5: *
6: * LICENSE
7: *
8: * This source file is subject to the new BSD license that is bundled
9: * with this package in the file license.txt.
10: * It is also available through the world-wide-web at this URL:
11: * https://github.com/jyxo/php/blob/master/license.txt
12: */
13:
14: namespace Jyxo\Rpc\Json;
15:
16: /**
17: * Class for sending requests using JSON-RPC.
18: * Requires json and curl PHP extensions.
19: *
20: * @category Jyxo
21: * @package Jyxo\Rpc
22: * @subpackage Json
23: * @copyright Copyright (c) 2005-2011 Jyxo, s.r.o.
24: * @license https://github.com/jyxo/php/blob/master/license.txt
25: * @author Jan Pěček
26: */
27: class Client extends \Jyxo\Rpc\Client
28: {
29: /**
30: * Sends a request and fetches server's response.
31: *
32: * @param string $method Method name
33: * @param array $params Method parameters
34: * @return mixed
35: * @throws \BadMethodCallException If no server address was provided
36: * @throws \Jyxo\Rpc\Json\Exception On error
37: */
38: public function send($method, array $params)
39: {
40: // Start profiling
41: $this->profileStart();
42:
43: // Generates ID
44: $id = md5(uniqid(rand(), true));
45:
46: try {
47: // Prepare JSON-RPC request
48: $data = json_encode(
49: array(
50: 'method' => $method,
51: 'params' => $params,
52: 'id' => $id
53: )
54: );
55:
56: // Fetch response
57: $response = $this->process('application/json', $data);
58:
59: // Process response
60: $response = json_decode($response, true);
61:
62: } catch (\Jyxo\Rpc\Exception $e) {
63: // Finish profiling
64: $this->profileEnd('JSON', $method, $params, $e->getMessage());
65:
66: throw new Exception($e->getMessage(), 0, $e);
67: }
68:
69: // Finish profiling
70: $this->profileEnd('JSON', $method, $params, $response);
71:
72: // Error in response
73: if (!is_array($response) || !isset($response['id'])) {
74: throw new Exception('Invalid response data.');
75: }
76:
77: if ($id !== $response['id']) {
78: throw new Exception('Response ID does not correspond to request ID.');
79: }
80:
81: if (isset($response['error'])) {
82: throw new Exception(preg_replace('~\s+~', ' ', $response['error']['message']), $response['error']['code']);
83: }
84:
85: if (!isset($response['result'])) {
86: throw new Exception('No response data.');
87: }
88:
89: return $response['result'];
90: }
91: }
92: