diff --git a/library/Director/RestApi/RequestHandler.php b/library/Director/RestApi/RequestHandler.php new file mode 100644 index 00000000..46dcb94d --- /dev/null +++ b/library/Director/RestApi/RequestHandler.php @@ -0,0 +1,79 @@ +request = $request; + $this->response = $response; + $this->db = $db; + } + + abstract protected function processApiRequest(); + + public function dispatch() + { + $this->processApiRequest(); + } + + protected function sendJson($object) + { + $this->response->setHeader('Content-Type', 'application/json', true); + echo json_encode($object, JSON_PRETTY_PRINT) . "\n"; + } + + protected function sendJsonError($error, $code = null) + { + $response = $this->response; + if ($code === null) { + if ($response->getHttpResponseCode() === 200) { + $response->setHttpResponseCode(500); + } + } else { + $response->setHttpResponseCode((int) $code); + } + + if ($error instanceof Exception) { + $message = $error->getMessage(); + } else { + $message = $error; + } + + $this->sendJson((object) ['error' => $message]); + } + + // TODO: just return json_last_error_msg() for PHP >= 5.5.0 + protected function getLastJsonError() + { + switch (json_last_error()) { + case JSON_ERROR_DEPTH: + return 'The maximum stack depth has been exceeded'; + case JSON_ERROR_CTRL_CHAR: + return 'Control character error, possibly incorrectly encoded'; + case JSON_ERROR_STATE_MISMATCH: + return 'Invalid or malformed JSON'; + case JSON_ERROR_SYNTAX: + return 'Syntax error'; + case JSON_ERROR_UTF8: + return 'Malformed UTF-8 characters, possibly incorrectly encoded'; + default: + return 'An error occured when parsing a JSON string'; + } + } +} diff --git a/library/Director/Web/Controller/Extension/RestApi.php b/library/Director/Web/Controller/Extension/RestApi.php index 07006c4b..f0595597 100644 --- a/library/Director/Web/Controller/Extension/RestApi.php +++ b/library/Director/Web/Controller/Extension/RestApi.php @@ -4,7 +4,6 @@ namespace Icinga\Module\Director\Web\Controller\Extension; use Icinga\Exception\AuthenticationException; use Icinga\Exception\NotFoundError; -use Icinga\Module\Director\Controllers\ServicetemplatesController; use Icinga\Web\Response; trait RestApi