Json.php 2.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697
  1. <?php
  2. declare (strict_types = 1);
  3. namespace library\utils;
  4. use think\facade\Config;
  5. use think\facade\Lang;
  6. use think\Response;
  7. /**
  8. * Json输出类
  9. * Class Json
  10. * @package crmeb\utils
  11. */
  12. class Json
  13. {
  14. private $code = 200;
  15. public function code(int $code): self
  16. {
  17. $this->code = $code;
  18. return $this;
  19. }
  20. public function make(int $code, string $msg, ?array $data = null): Response
  21. {
  22. $request = app()->request;
  23. $res = compact('code', 'msg');
  24. if (!is_null($data))
  25. $res['data'] = $data;
  26. if ($res['msg'] && !is_numeric($res['msg'])) {
  27. if (!$range = $request->get('lang')) {
  28. $range = $request->cookie(Config::get('lang.cookie_var'));
  29. }
  30. $res['msg'] = Lang::get($res['msg'], [], $range !== 'deleted' && $range ? $range : 'zh-cn');
  31. }
  32. //Null处理
  33. $res = $this->JsonNull($res);
  34. return Response::create($res, 'json', $this->code)->header(["Content-type"=>"text/html;charset=utf-8;"]);
  35. }
  36. public function success($msg = 'ok', ?array $data = null): Response
  37. {
  38. if (is_array($msg)) {
  39. $data = $msg;
  40. $msg = 'ok';
  41. }
  42. return $this->make(200, $msg, $data);
  43. }
  44. public function successful(...$args): Response
  45. {
  46. return $this->success(...$args);
  47. }
  48. public function fail($msg = 'fail', ?array $data = null): Response
  49. {
  50. if (is_array($msg)) {
  51. $data = $msg;
  52. $msg = 'ok';
  53. }
  54. return $this->make(-1, $msg, $data);
  55. }
  56. public function status($status, $msg, $result = [])
  57. {
  58. $status = strtoupper($status);
  59. if (is_array($msg)) {
  60. $result = $msg;
  61. $msg = 'ok';
  62. }
  63. return $this->success($msg, compact('status', 'result'));
  64. }
  65. /**
  66. * 处理Json Null Bug字符串
  67. * @param array|null $data
  68. * @return array
  69. */
  70. public function JsonNull(?array $data) : array {
  71. foreach ($data as $k=>$v){
  72. if(is_array($v)) {
  73. $v = $this->JsonNull($v);
  74. } else {
  75. $v = is_null($v) ? '' : $v;
  76. }
  77. $data[$k] = $v;
  78. }
  79. return $data;
  80. }
  81. }