Json.php 1.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364
  1. <?php
  2. namespace crmeb\utils;
  3. use think\Response;
  4. class Json
  5. {
  6. private $code = 200;
  7. public function code(int $code): self
  8. {
  9. $this->code = $code;
  10. return $this;
  11. }
  12. public function make(int $status, string $msg, ?array $data = null): Response
  13. {
  14. $res = compact('status', 'msg');
  15. if (!is_null($data))
  16. $res['data'] = $data;
  17. return Response::create($res, 'json', $this->code);
  18. }
  19. public function success($msg = 'ok', ?array $data = null): Response
  20. {
  21. if (is_array($msg)) {
  22. $data = $msg;
  23. $msg = 'ok';
  24. }
  25. return $this->make(200, $msg, $data);
  26. }
  27. public function successful(...$args): Response
  28. {
  29. return $this->success(...$args);
  30. }
  31. public function fail($msg = 'fail', ?array $data = null): Response
  32. {
  33. if (is_array($msg)) {
  34. $data = $msg;
  35. $msg = 'ok';
  36. }
  37. return $this->make(400, $msg, $data);
  38. }
  39. public function status($status, $msg, $result = [])
  40. {
  41. $status = strtoupper($status);
  42. if (is_array($msg)) {
  43. $result = $msg;
  44. $msg = 'ok';
  45. }
  46. return $this->success($msg, compact('status', 'result'));
  47. }
  48. }