Json.php 2.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283
  1. <?php
  2. // +----------------------------------------------------------------------
  3. // | CRMEB [ CRMEB赋能开发者,助力企业发展 ]
  4. // +----------------------------------------------------------------------
  5. // | Copyright (c) 2016~2023 https://www.crmeb.com All rights reserved.
  6. // +----------------------------------------------------------------------
  7. // | Licensed CRMEB并不是自由软件,未经许可不能去掉CRMEB相关版权
  8. // +----------------------------------------------------------------------
  9. // | Author: CRMEB Team <admin@crmeb.com>
  10. // +----------------------------------------------------------------------
  11. namespace crmeb\utils;
  12. use think\Response;
  13. /**
  14. * Json输出类
  15. * Class Json
  16. * @package crmeb\utils
  17. */
  18. class Json
  19. {
  20. private $code = 200;
  21. private $header = [];
  22. public function code(int $code): self
  23. {
  24. $this->code = $code;
  25. return $this;
  26. }
  27. public function header(array $header): self
  28. {
  29. $this->header = $header;
  30. return $this;
  31. }
  32. public function make(int $status, string $msg, ?array $data = null, ?array $replace = []): Response
  33. {
  34. $res = compact('status', 'msg');
  35. if (!is_null($data))
  36. $res['data'] = $data;
  37. if (is_numeric($res['msg'])) {
  38. $res['code'] = $res['msg'];
  39. $res['msg'] = getLang($res['msg'], $replace);
  40. }
  41. return Response::create($res, 'json', $this->code)->header($this->header);
  42. }
  43. public function success($msg = 'success', ?array $data = null, ?array $replace = []): Response
  44. {
  45. if (is_array($msg)) {
  46. $data = $msg;
  47. $msg = 'success';
  48. }
  49. return $this->make(200, $msg, $data, $replace);
  50. }
  51. public function fail($msg = 'fail', ?array $data = null, ?array $replace = []): Response
  52. {
  53. if (is_array($msg)) {
  54. $data = $msg;
  55. $msg = 'fail';
  56. }
  57. return $this->make(400, $msg, $data, $replace);
  58. }
  59. public function status($status, $msg, $result = [])
  60. {
  61. $status = strtoupper($status);
  62. if (is_array($msg)) {
  63. $result = $msg;
  64. $msg = 'success';
  65. }
  66. return $this->success($msg, compact('status', 'result'));
  67. }
  68. }