12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697 |
- <?php
- declare (strict_types = 1);
- namespace library\utils;
- use think\facade\Config;
- use think\facade\Lang;
- use think\Response;
- /**
- * Json输出类
- * Class Json
- * @package crmeb\utils
- */
- class Json
- {
- private $code = 200;
- public function code(int $code): self
- {
- $this->code = $code;
- return $this;
- }
- public function make(int $code, string $msg, ?array $data = null): Response
- {
- $request = app()->request;
- $res = compact('code', 'msg');
- if (!is_null($data))
- $res['data'] = $data;
- if ($res['msg'] && !is_numeric($res['msg'])) {
- if (!$range = $request->get('lang')) {
- $range = $request->cookie(Config::get('lang.cookie_var'));
- }
- $res['msg'] = Lang::get($res['msg'], [], $range !== 'deleted' && $range ? $range : 'zh-cn');
- }
- //Null处理
- $res = $this->JsonNull($res);
- return Response::create($res, 'json', $this->code)->header(["Content-type"=>"text/html;charset=utf-8;"]);
- }
- public function success($msg = 'ok', ?array $data = null): Response
- {
- if (is_array($msg)) {
- $data = $msg;
- $msg = 'ok';
- }
- return $this->make(200, $msg, $data);
- }
- public function successful(...$args): Response
- {
- return $this->success(...$args);
- }
- public function fail($msg = 'fail', ?array $data = null): Response
- {
- if (is_array($msg)) {
- $data = $msg;
- $msg = 'ok';
- }
- return $this->make(-1, $msg, $data);
- }
- public function status($status, $msg, $result = [])
- {
- $status = strtoupper($status);
- if (is_array($msg)) {
- $result = $msg;
- $msg = 'ok';
- }
- return $this->success($msg, compact('status', 'result'));
- }
- /**
- * 处理Json Null Bug字符串
- * @param array|null $data
- * @return array
- */
- public function JsonNull(?array $data) : array {
- foreach ($data as $k=>$v){
- if(is_array($v)) {
- $v = $this->JsonNull($v);
- } else {
- $v = is_null($v) ? '' : $v;
- }
- $data[$k] = $v;
- }
- return $data;
- }
- }
|