| 1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374 |
- <?php
- /**
- * @example: Response::sendJson($data);
- * @example: Response::sendPlainText($data);
- * @example: Response::sendJsonExit($data);
- * @example: Response::sendPlainTextExit($data);
- * @example: Response::sendTryCatchJson(array($this, 'methodNameReponseCallback'), $args);
- */
- class Response {
- public static function sendJson($data) {
- header("Content-type: application/json");
- echo json_encode($data);
- }
- public static function sendPlainText($data) {
- header("Content-type: text/plain");
- if (!is_scalar($data)) throw new Exception("Wrong data type - only scalar values allowed");
- echo $data;
- }
- public static function sendJsonExit($data) {
- self::sendJson($data);
- exit;
- }
- public static function sendPlainTextExit($data) {
- self::sendPlainText($data);
- exit;
- }
- public static function sendTryCatchJson($callback, $args = array()) {// @param callback must return $response object to send as json or throw exception
- $response = array();
- try {
- if (!is_callable($callback)) throw new Exception("#1L" . __LINE__ . " Callback is not callable");
- $response = call_user_func_array($callback, $args);
- } catch (AlertDangerException $e) {
- Http::sendHeaderByCode(200);
- $response['type'] = 'error';
- $response['msg'] = $e->getMessage();
- $response['code'] = "#" . $e->getCode() . "L" . $e->getLine();
- Response::sendJsonExit($response);
- } catch (AlertSuccessException $e) {
- Http::sendHeaderByCode(200);
- $response['type'] = 'success';
- $response['msg'] = $e->getMessage();
- $response['code'] = "#" . $e->getCode() . "L" . $e->getLine();
- Response::sendJsonExit($response);
- } catch (AlertInfoException $e) {
- Http::sendHeaderByCode(200);
- $response['type'] = 'info';
- $response['msg'] = $e->getMessage();
- $response['code'] = "#" . $e->getCode() . "L" . $e->getLine();
- Response::sendJsonExit($response);
- } catch (AlertWarningException $e) {
- Http::sendHeaderByCode(200);
- $response['type'] = 'warning';
- $response['msg'] = $e->getMessage();
- $response['code'] = "#" . $e->getCode() . "L" . $e->getLine();
- Response::sendJsonExit($response);
- } catch (Exception $e) {
- Http::sendHeaderByCode(500);
- $response['type'] = 'error';
- $response['msg'] = $e->getMessage();
- $response['code'] = "#" . $e->getCode() . "L" . $e->getLine();
- Response::sendJsonExit($response);
- }
- Http::sendHeaderByCode(200);
- Response::sendJsonExit($response);
- }
- }
|