1: <?php
2:
3: 4: 5: 6: 7: 8: 9: 10: 11: 12:
13:
14: 15: 16: 17: 18: 19: 20: 21: 22: 23:
24: class Jyxo_Rpc_Json_Server extends Jyxo_Rpc_Server
25: {
26: 27: 28: 29: 30:
31: private static $jsonErrors = array(
32: JSON_ERROR_DEPTH => 'Maximum stack depth exceeded.',
33: JSON_ERROR_CTRL_CHAR => 'Unexpected control character found.',
34: JSON_ERROR_SYNTAX => 'Syntax error, malformed JSON.'
35: );
36:
37: 38: 39: 40: 41:
42: private $methods = array();
43:
44: 45: 46: 47: 48:
49: protected function register($func)
50: {
51: $this->methods[] = $func;
52: }
53:
54: 55: 56:
57: public function process()
58: {
59: $requestId = '';
60: try {
61: $data = file_get_contents('php://input');
62: $data = trim($data);
63: if (empty($data)) {
64: throw new Jyxo_Rpc_Json_Exception('No data received.', -32700);
65: }
66: $data = json_decode($data, true);
67:
68:
69: if ($data === null && ($faultCode = json_last_error()) != JSON_ERROR_NONE) {
70: throw new Jyxo_Rpc_Json_Exception(self::$jsonErrors[$faultCode], $faultCode);
71: }
72:
73: $requestId = isset($data['id']) ? $data['id'] : '';
74:
75:
76: if (empty($data['method']) || !isset($data['id'])) {
77: throw new Jyxo_Rpc_Json_Exception('Parse error.', 10);
78: }
79:
80:
81: if (!in_array($data['method'], $this->methods)) {
82: throw new Jyxo_Rpc_Json_Exception('Server error. Method not found.', -32601);
83: }
84:
85:
86: $params = !empty($data['params']) ? (array) $data['params'] : array();
87: $response = $this->call($data['method'], $params);
88: $response = array('result' => $response, 'id' => $data['id']);
89:
90: } catch (Jyxo_Rpc_Json_Exception $e) {
91: $response = array(
92: 'error' => array(
93: 'message' => $e->getMessage(),
94: 'code' => $e->getCode()
95: ),
96: 'id' => $requestId
97: );
98: }
99:
100: header('Content-Type: application/json; charset="utf-8"');
101: echo json_encode($response);
102: }
103: }
104: