Response.php 6.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185
  1. <?php
  2. namespace App\Base\Middleware;
  3. use Closure;
  4. use Illuminate\Http\Request;
  5. use Illuminate\Support\Facades\Auth;
  6. use Illuminate\Support\Facades\DB;
  7. use Illuminate\Support\Facades\Log;
  8. /**
  9. * 数据返回中间件
  10. * Class Response
  11. * @package App\Base\Middleware\Middleware
  12. */
  13. class Response
  14. {
  15. /**
  16. * @param Request $request
  17. * @param Closure $next
  18. * @return mixed
  19. */
  20. public function handle($request, Closure $next)
  21. {
  22. $curTime = gettimeofday();
  23. $beginTime = $curTime['sec'] * 1000000 + $curTime['usec'];
  24. if (strtolower($request->getMethod()) == 'options') {
  25. $response = new \Illuminate\Http\Response();
  26. $response->withHeaders([
  27. 'Content-Type' => $request->ajax() ? 'application/json; charset:UTF-8' : 'text/html; charset=UTF-8',
  28. 'Access-Control-Allow-Origin' => '*',
  29. 'Access-Control-Allow-Credentials' => 'true',
  30. 'Access-Control-Allow-Methods' => 'PUT, GET, POST, DELETE, OPTIONS',
  31. 'Access-Control-Allow-Headers' => 'Content-Type,token,api-token,X-Requested-With,Language-Set',
  32. 'Access-Control-Expose-Headers' => '*'
  33. ]);
  34. return $response;
  35. }
  36. //去除请求参数左右两边空格
  37. $params = $request->all();
  38. foreach ($params as $key => $value) {
  39. if (!is_array($value)) {
  40. $params[$key] = trim($value);
  41. }
  42. }
  43. $request->replace($params);
  44. if ($this->mTrans($request)) {
  45. DB::beginTransaction();
  46. }
  47. //增加redis的连接判断,默认如果连接错误会抛出异常,这边捕获异常,下次会重新连接
  48. // checkRedisPing();
  49. // DB::enableQueryLog();
  50. //在有auth中间件认证时,包括中间件里也有调用request->user(),但其实是只有调用一次的
  51. $request->attributes->set('_is_check_auth', 1);
  52. $user = $request->user();
  53. $request->attributes->set('_is_check_auth', 0);
  54. $response = $next($request);
  55. if ($response->getStatusCode() == 200 && (!isset($response->exception) || $response->exception == null)) {
  56. if ($this->mTrans($request)) {
  57. DB::commit();
  58. }
  59. if ($request->ajax() && !($response instanceof StreamedResponse)) {
  60. $content = $response->getContent();
  61. $content = json_encode([
  62. 'ret' => 0,
  63. 'msg' => 'success.',
  64. 'data' => ($this->isJson($content) ? json_decode($content, true) : $content)
  65. ], JSON_UNESCAPED_UNICODE);
  66. $response->setContent($content);
  67. }
  68. } elseif ($response->getStatusCode() == 404 && !$request->ajax()) {
  69. //不是ajax请求 跳转到404页面
  70. return response(view("errors.404"), 404);
  71. } else {
  72. if ($this->mTrans($request) || DB::transactionLevel()) {
  73. DB::rollBack();
  74. }
  75. if (!$request->ajax() && !($response instanceof StreamedResponse)) {
  76. $content = json_decode($response->getContent(), true);
  77. $response->setContent($content['msg']??'');
  78. }
  79. }
  80. if (method_exists($response,'withHeaders')) {
  81. $curTime = gettimeofday();
  82. $costTime = ($curTime['sec'] * 1000000 + $curTime['usec']) - $beginTime;
  83. $costTime = $costTime / 1000000.0;
  84. // $this->saveAccessLog($request->method(), $request->path(), $params, $response, $request, $costTime);
  85. $response->withHeaders([
  86. 'Access-Control-Allow-Origin' => '*',
  87. 'Access-Control-Allow-Credentials' => 'true',
  88. 'Access-Control-Allow-Methods' => 'PUT, GET, POST, DELETE, OPTIONS',
  89. 'Access-Control-Allow-Headers' => 'Content-Type,token,api_token,X-Requested-With,Language-Set',
  90. 'Access-Control-Expose-Headers' => '*'
  91. ]);
  92. if ($request->ajax()) {
  93. $response->withHeaders(['Content-Type' => 'application/json; charset:UTF-8']);
  94. } elseif (!$response->headers->get('content-type')) {
  95. $response->withHeaders(['Content-Type' => 'text/html; charset=UTF-8']);
  96. }
  97. $response->withHeaders(['Language' => app('translator')->getLocale()]);
  98. }
  99. DB::disconnect();
  100. return $response;
  101. }
  102. /**
  103. * 是否为json格式的字符串
  104. * @param $string
  105. * @return bool
  106. */
  107. private function isJson($string)
  108. {
  109. json_decode($string);
  110. return (json_last_error() == JSON_ERROR_NONE);
  111. }
  112. /**
  113. * 是否开启事务
  114. * @param Request $request
  115. * @return bool
  116. */
  117. private function mTrans($request)
  118. {
  119. if (/*strtolower($request->method())!='get' && */
  120. config('database.transaction')
  121. ) {
  122. return true;
  123. } else {
  124. return false;
  125. }
  126. }
  127. /**
  128. * 添加访问日志
  129. * @param $response
  130. */
  131. private function saveAccessLog($method, $route, $params, $response, $request, $costTime = 0)
  132. {
  133. try {
  134. $user = Auth::user();
  135. if (!isset($user['id']) || !$user['id']) {
  136. return;
  137. }
  138. // 过滤掉常规路由,主要是定时请求
  139. $route = trim($route, '/');
  140. if (in_array($route, ['notice/news', 'checkLogin'])) {
  141. return;
  142. }
  143. $type = 0;
  144. $serverIp = env('SERVER_IP', ''); // 增加服务器IP,便于快速定位日志
  145. $data = [
  146. 'method' => strtolower($method),
  147. 'route' => '/' . $route, // 屏蔽掉$request->root()
  148. 'params' => $params,
  149. 'status_code' => $response->getStatusCode(),
  150. 'response' => json_decode($response->getContent(), true),
  151. 'error_code' => $response->exception ? $response->exception->getCode() : 0,
  152. 'error_message' => $response->exception ? $response->exception->getMessage() : '',
  153. 'company_id' => $user->company_id ?? '',
  154. 'user_id' => $user->id ?? '',
  155. 'is_marketing' => 0,
  156. 'type' => $type, //值:0为cdp,1为marketing,2为dmp,3为小程序
  157. 'ip' => $request->getClientIp(),
  158. 'date' => date('Y-m-d'),
  159. 'create_time' => date('Y-m-d H:i:s'),
  160. 'cost_time' => $costTime,
  161. 'server_ip' => $serverIp,
  162. ];
  163. // checkRedisPing('es_log');
  164. // $redis = app('redis')->connection('es_log');
  165. // $redis->rpush('queue:api_log', json_encode($data, JSON_UNESCAPED_UNICODE));
  166. } catch (\Exception $e) {
  167. Log::info('es_log:' . print_r($e->getMessage(), true));
  168. }
  169. }
  170. }