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