AutoResult.php 892 B

12345678910111213141516171819202122232425262728293031323334353637
  1. <?php
  2. namespace app\middleware;
  3. use think\Request;
  4. use think\response\Json;
  5. use app\common\util\Result;
  6. /**
  7. * 自动封装Result 中间件
  8. */
  9. class AutoResult
  10. {
  11. public function handle(Request $request, \Closure $next)
  12. {
  13. $request->withHeader(['Accept' => '*/*']);
  14. /** @var \think\Response */
  15. $response = $next($request);
  16. // 已经是json数据了,不做处理
  17. if ($response instanceof Json) {
  18. return $response;
  19. }
  20. $data = $response->getData();
  21. // 过滤string和空值,如果需要data: string, 需要使用Result::success()
  22. if (is_string($data) || is_null($data)) {
  23. return $response;
  24. }
  25. // 如果已经是Result,转成数组
  26. if ($data instanceof Result) {
  27. return json($data->toArray());
  28. }
  29. return Result::rest($data);
  30. }
  31. }