Response.php 2.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374
  1. <?php
  2. /**
  3. * @example: Response::sendJson($data);
  4. * @example: Response::sendPlainText($data);
  5. * @example: Response::sendJsonExit($data);
  6. * @example: Response::sendPlainTextExit($data);
  7. * @example: Response::sendTryCatchJson(array($this, 'methodNameReponseCallback'), $args);
  8. */
  9. class Response {
  10. public static function sendJson($data) {
  11. header("Content-type: application/json");
  12. echo json_encode($data);
  13. }
  14. public static function sendPlainText($data) {
  15. header("Content-type: text/plain");
  16. if (!is_scalar($data)) throw new Exception("Wrong data type - only scalar values allowed");
  17. echo $data;
  18. }
  19. public static function sendJsonExit($data) {
  20. self::sendJson($data);
  21. exit;
  22. }
  23. public static function sendPlainTextExit($data) {
  24. self::sendPlainText($data);
  25. exit;
  26. }
  27. public static function sendTryCatchJson($callback, $args = array()) {// @param callback must return $response object to send as json or throw exception
  28. $response = array();
  29. try {
  30. if (!is_callable($callback)) throw new Exception("#1L" . __LINE__ . " Callback is not callable");
  31. $response = call_user_func_array($callback, $args);
  32. } catch (AlertDangerException $e) {
  33. Http::sendHeaderByCode(200);
  34. $response['type'] = 'error';
  35. $response['msg'] = $e->getMessage();
  36. $response['code'] = "#" . $e->getCode() . "L" . $e->getLine();
  37. Response::sendJsonExit($response);
  38. } catch (AlertSuccessException $e) {
  39. Http::sendHeaderByCode(200);
  40. $response['type'] = 'success';
  41. $response['msg'] = $e->getMessage();
  42. $response['code'] = "#" . $e->getCode() . "L" . $e->getLine();
  43. Response::sendJsonExit($response);
  44. } catch (AlertInfoException $e) {
  45. Http::sendHeaderByCode(200);
  46. $response['type'] = 'info';
  47. $response['msg'] = $e->getMessage();
  48. $response['code'] = "#" . $e->getCode() . "L" . $e->getLine();
  49. Response::sendJsonExit($response);
  50. } catch (AlertWarningException $e) {
  51. Http::sendHeaderByCode(200);
  52. $response['type'] = 'warning';
  53. $response['msg'] = $e->getMessage();
  54. $response['code'] = "#" . $e->getCode() . "L" . $e->getLine();
  55. Response::sendJsonExit($response);
  56. } catch (Exception $e) {
  57. Http::sendHeaderByCode(500);
  58. $response['type'] = 'error';
  59. $response['msg'] = $e->getMessage();
  60. $response['code'] = "#" . $e->getCode() . "L" . $e->getLine();
  61. Response::sendJsonExit($response);
  62. }
  63. Http::sendHeaderByCode(200);
  64. Response::sendJsonExit($response);
  65. }
  66. }