| 12345678910111213141516171819202122232425262728293031323334353637 | 
							- <?php
 
- namespace app\middleware;
 
- use think\Request;
 
- use think\response\Json;
 
- use app\common\util\Result;
 
- /**
 
-  * 自动封装Result 中间件
 
-  */
 
- class AutoResult
 
- {
 
-     public function handle(Request $request, \Closure $next)
 
-     {
 
-         $request->withHeader(['Accept' => '*/*']);
 
-         /** @var \think\Response */
 
-         $response = $next($request);
 
-         // 已经是json数据了,不做处理
 
-         if ($response instanceof Json) {
 
-             return $response;
 
-         }
 
-         $data = $response->getData();
 
-         // 过滤string和空值,如果需要data: string, 需要使用Result::success()
 
-         if (is_string($data) || is_null($data)) {
 
-             return $response;
 
-         }
 
-         // 如果已经是Result,转成数组
 
-         if ($data instanceof Result) {
 
-             return json($data->toArray());
 
-         }
 
-         return Result::rest($data);
 
-     }
 
- }
 
 
  |