共计 1279 个字符,预计需要花费 4 分钟才能阅读完成。
<?php
namespace App\Http\Middleware;
use Closure;
/**
* 设置一个后置中间件统一返回格式,去除 null 值
*
* Class Response
*/
class Response
{
private $codeDefault = self::SUCCESS;
private $messageDefault = self::SUCCESS_MSG;
private $dataDefault = [];
const SUCCESS = 200;
const WARNING = 300;
const ERROR = 400;
const SUCCESS_MSG = '返回成功';
public function handle($request, Closure $next)
{$response = $next($request);
$response = $this->formatData($response->original);
return response()->json($response);
}
/**
* 格式化数据
*
* @param $response
* @return array
*/
private function formatData($response)
{$response['data'] = $this->isArray($response['data']);
if (isset($response['data'])) {$response['data'] = $this->nullTransform($response['data']);
}
$message = isset($response['message']) ? $response['message'] : $this->messageDefault;
$code = isset($response['code']) ? $response['code'] : $this->codeDefault;
$data = isset($response['data']) ? $response['data'] : $this->dataDefault;
return ['code' => $code, 'message' => $message, 'data' => $data];
}
/**
* 去除 null 值
*
* @param $response
* @return mixed
*/
private function nullTransform($response)
{$response = $this->isArray($response);
array_walk_recursive($response, function (&$val) {if ($val === null) {$val = '';}
});
return $response;
}
/**
* 判断变量是否数组
*
* @param $response
* @return mixed
*/
private function isArray($response)
{if(!is_array($response)){return $response->toArray();
}
return $response;
}
}
正文完