Json.php 2.4 KB

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