From a9cb8bfb2c9a2f5092fbebfdb0305713a611729a Mon Sep 17 00:00:00 2001 From: Eric Lippmann Date: Mon, 7 Sep 2015 13:22:58 +0200 Subject: [PATCH] lib: Add JsonResponse class refs #9606 --- library/Icinga/Web/Response/JsonResponse.php | 205 +++++++++++++++++++ 1 file changed, 205 insertions(+) create mode 100644 library/Icinga/Web/Response/JsonResponse.php diff --git a/library/Icinga/Web/Response/JsonResponse.php b/library/Icinga/Web/Response/JsonResponse.php new file mode 100644 index 000000000..7d7cc83f0 --- /dev/null +++ b/library/Icinga/Web/Response/JsonResponse.php @@ -0,0 +1,205 @@ +encodingOptions; + } + + /** + * Set the JSON encoding options + * + * @param int $encodingOptions + * + * @return $this + */ + public function setEncodingOptions($encodingOptions) + { + $this->encodingOptions = (int) $encodingOptions; + return $this; + } + + /** + * Get the error message if the API call failed due to a server error + * + * @return string|null + */ + public function getErrorMessage() + { + return $this->errorMessage; + } + + /** + * Set the error message if the API call failed due to a server error + * + * @param string $errorMessage + * + * @return $this + */ + public function setErrorMessage($errorMessage) + { + $this->errorMessage = (string) $errorMessage; + $this->status = static::STATUS_ERROR; + return $this; + } + + /** + * Get the fail data for rejected API calls + * + * @return array|null + */ + public function getFailData() + { + return $this->failData; + } + + /** + * Set the fail data for rejected API calls + * + * @param array $failData + * + * @return $this + */ + public function setFailData(array $failData) + { + $this->failData = $failData; + $this->status = static::STATUS_FAIL; + return $this; + } + + /** + * Get the data for successful API requests + * + * @return array|null + */ + public function getSuccessData() + { + return $this->successData; + } + + /** + * Set the data for successful API requests + * + * @param array $successData + * + * @return $this + */ + public function setSuccessData(array $successData) + { + $this->successData = $successData; + $this->status = static::STATUS_SUCCESS; + return $this; + } + + /** + * {@inheritdoc} + */ + public function outputBody() + { + $body = array( + 'status' => $this->status + ); + switch ($this->status) { + case static::STATUS_ERROR: + $body['message'] = $this->getErrorMessage(); + break; + case static::STATUS_FAIL: + $body['data'] = $this->getFailData(); + break; + case static::STATUS_SUCCESS: + $body['data'] = $this->getSuccessData(); + break; + } + echo json_encode($body, $this->getEncodingOptions()); + } + + /** + * {@inheritdoc} + */ + public function sendHeaders() + { + $this->setHeader('Content-Type', 'application/json', true); + parent::sendHeaders(); + } + + /** + * {@inheritdoc} + */ + public function sendResponse() + { + Zend_Controller_Action_HelperBroker::getStaticHelper('viewRenderer')->setNoRender(true); + parent::sendResponse(); + exit; + } +}