IResponse.php 1.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485
  1. <?php
  2. namespace app\http;
  3. use think\exception\HttpResponseException;
  4. use think\Paginator;
  5. use think\Response;
  6. use think\response\Json;
  7. class IResponse
  8. {
  9. /**
  10. * 成功消息
  11. *
  12. * @author 许祖兴 < zuxing.xu@lettered.cn>
  13. * @date 2020/3/16 11:27
  14. *
  15. * @param array $data
  16. * @param string $message
  17. * @return mixed
  18. */
  19. public static function success($data = [], $message = 'OK!')
  20. {
  21. if (gettype($data) == 'string'){
  22. $message = $data;
  23. $data = [];
  24. }
  25. return self::response(10000, $data, $message);
  26. }
  27. /**
  28. * 分页
  29. *
  30. * @author 许祖兴 < zuxing.xu@lettered.cn>
  31. * @date 2020/3/16 11:28
  32. *
  33. * @param Paginator $list
  34. * @return mixed
  35. */
  36. public static function paginate(Paginator $list)
  37. {
  38. return self::success([
  39. 'total' => $list->total(),
  40. 'list' => $list->getCollection(),
  41. ]);
  42. }
  43. /**
  44. *
  45. * @author 许祖兴 < zuxing.xu@lettered.cn>
  46. * @date 2020/3/16 11:33
  47. *
  48. * @param string $message
  49. * @return mixed
  50. */
  51. public static function failure($message = 'Error!')
  52. {
  53. return self::response(90001, [], $message);
  54. }
  55. /**
  56. *
  57. * @author 许祖兴 < zuxing.xu@lettered.cn>
  58. * @date 2020/3/16 11:20
  59. *
  60. * @param int $code
  61. * @param array $data
  62. * @param string $message
  63. * @return mixed
  64. * @throws HttpResponseException
  65. */
  66. final private static function response($code = 0, $data = [], $message = 'OK!')
  67. {
  68. throw new HttpResponseException(Response::create([
  69. 'REQUEST_ID' => RequestID::generate(),
  70. 'RUN_IP' => request()->ip(),
  71. 'code' => $code,
  72. 'message' => $message,
  73. 'data' => $data
  74. ],'json'));
  75. }
  76. }