diff --git a/JsonRpc2/Controller.php b/JsonRpc2/Controller.php index 85dd0dc..335b36f 100644 --- a/JsonRpc2/Controller.php +++ b/JsonRpc2/Controller.php @@ -56,7 +56,7 @@ public function runAction($id, $params = []) $response = new Response(); $response->format = Response::FORMAT_JSON; - $response->data = $isBatch ? $resultData : current($resultData); + $response->data = $isBatch || null === $resultData ? $resultData : current($resultData); return $response; } @@ -69,7 +69,7 @@ public function runAction($id, $params = []) */ private function getActionResponse($requestObject) { - $result = $error = null; + $this->requestObject = $result = $error = null; try { $this->parseAndValidateRequestObject($requestObject); ob_start(); @@ -84,7 +84,7 @@ private function getActionResponse($requestObject) $error = new Exception("Internal error", Exception::INTERNAL_ERROR); } - if (!isset($this->requestObject->id) && (empty($error) || $error->getCode() != Exception::PARSE_ERROR)) + if (!isset($this->requestObject->id) && (empty($error) || !in_array($error->getCode(), [Exception::PARSE_ERROR, Exception::INVALID_REQUEST]))) return null; return Helper::formatResponse($result, $error, !empty($this->requestObject->id)? $this->requestObject->id : null); @@ -192,13 +192,18 @@ private function initRequest($id) */ private function parseAndValidateRequestObject($requestObject) { - if (!is_object($requestObject)) + if (null === $requestObject) throw new Exception("Parse error", Exception::PARSE_ERROR); - if (!isset($requestObject->jsonrpc) || $requestObject->jsonrpc !== '2.0' || empty($requestObject->method)) + if (!is_object($requestObject) + || !isset($requestObject->jsonrpc) || $requestObject->jsonrpc !== '2.0' + || empty($requestObject->method) || "string" != gettype($requestObject->method) + ) throw new Exception("Invalid Request", Exception::INVALID_REQUEST); $this->requestObject = $requestObject; + if (!isset($this->requestObject->params)) + $this->requestObject->params = []; } /** diff --git a/JsonRpc2/Helper.php b/JsonRpc2/Helper.php index 74b311c..2fc190d 100644 --- a/JsonRpc2/Helper.php +++ b/JsonRpc2/Helper.php @@ -18,19 +18,22 @@ class Helper */ public static function formatResponse ($result = null, Exception $error = null, $id = null) { - $response = [ - 'jsonrpc' => '2.0', - 'id' => $id, - ]; + $resultKey = 'result'; - if (!empty($error)) - $response['error'] = $error->toArray(); + if (!empty($error)) { + $resultKey = 'error'; + $resultValue = $error->toArray(); + } else if (null === $result) - $response['result'] = self::$defaultResult; + $resultValue = self::$defaultResult; else - $response['result'] = $result; + $resultValue = $result; - return $response; + return [ + 'jsonrpc' => '2.0', + $resultKey => $resultValue, + 'id' => $id, + ]; } /**