Json.php 1.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778
  1. <?php
  2. namespace crmeb\utils;
  3. use think\facade\Config;
  4. use think\facade\Lang;
  5. use think\Response;
  6. /**
  7. * Json输出类
  8. * Class Json
  9. * @package crmeb\utils
  10. */
  11. class Json
  12. {
  13. private $code = 200;
  14. public function code(int $code): self
  15. {
  16. $this->code = $code;
  17. return $this;
  18. }
  19. public function make(int $status, string $msg, ?array $data = null): Response
  20. {
  21. $request = app()->request;
  22. $res = compact('status', 'msg');
  23. if (!is_null($data))
  24. $res['data'] = $data;
  25. if ($res['msg'] && !is_numeric($res['msg'])) {
  26. if (!$range = $request->get('lang')) {
  27. $range = $request->cookie(Config::get('lang.cookie_var'));
  28. }
  29. $res['msg'] = Lang::get($res['msg'], [], $range !== 'deleted' && $range ? $range : 'zh-cn');
  30. }
  31. return Response::create($res, 'json', $this->code);
  32. }
  33. public function success($msg = 'ok', ?array $data = null): Response
  34. {
  35. if (is_array($msg)) {
  36. $data = $msg;
  37. $msg = 'ok';
  38. }
  39. return $this->make(200, $msg, $data);
  40. }
  41. public function successful(...$args): Response
  42. {
  43. return $this->success(...$args);
  44. }
  45. public function fail($msg = 'fail', ?array $data = null): Response
  46. {
  47. if (is_array($msg)) {
  48. $data = $msg;
  49. $msg = 'ok';
  50. }
  51. return $this->make(400, $msg, $data);
  52. }
  53. public function status($status, $msg, $result = [])
  54. {
  55. $status = strtoupper($status);
  56. if (is_array($msg)) {
  57. $result = $msg;
  58. $msg = 'ok';
  59. }
  60. return $this->success($msg, compact('status', 'result'));
  61. }
  62. }