<?php /** * Created by PhpStorm. * User: snower * Date: 17/3/22 * Time: 下午5:22 */ namespace Common\Middlewares; use Symfony\Component\HttpKernel\Exception\AccessDeniedHttpException; use Illuminate\Http\Response; use Common\ApiException; use Thrift\Exception\TException; use Log; class Serialization { public function handle($request, \Closure $next) { $request_referer_info = parse_url($request->header('Referer')); $request_referer = count($request_referer_info)>1 ? $request_referer_info['scheme'].'://'.$request_referer_info['host'] .(isset($request_referer_info['port']) ? ':'.$request_referer_info['port'] : ''): '*'; if($request->isMethod('OPTIONS')){ if(env('APP_ENV') == 'local'){ return (new Response('', 204)) ->header('Access-Control-Allow-Origin', $request_referer) ->header('Access-Control-Allow-Headers', 'Origin, Content-Type, Cookie, Accept, multipart/form-data, application/json') ->header('Access-Control-Allow-Methods', 'GET, POST, PATCH, PUT, OPTIONS') ->header('Access-Control-Allow-Credentials', 'true'); } } try { $response = $next($request); $data = [ "status" => 0, "msg" => '', "data" => $response->getOriginalContent() ]; if(env('APP_ENV') == 'local') { $response->header('Access-Control-Allow-Origin', $request_referer) ->header('Access-Control-Allow-Credentials', 'true'); } return $response->setContent($data); } catch(AccessDeniedHttpException $e){ Log::info($e); $data = [ "status" => 300, "msg" => '无权限访问', "data" => new \stdClass() ]; }catch (ApiException $e){ Log::info($e); $data = [ "status" => $e->getCode(), "msg" => $e->getMessage(), "data" => new \stdClass() ]; }catch(TException $e){ //RPC调用返回异常 Log::info($e); $data = [ "status" => 500, "msg" => $e->getCode() . ":" . 'RPC调用返回异常', "data" => new \stdClass() ]; }catch(\Exception $e){ Log::info($e); $data = [ "status" => 500, "msg" => $e->getCode() . ":" . $e->getMessage(), "data" => new \stdClass() ]; } $response = new Response($data, 200); if(env('APP_ENV') == 'local') { $response->header('Access-Control-Allow-Origin', $request_referer) ->header('Access-Control-Allow-Credentials', 'true'); } return $response; } }
本文来自博客园,作者:孙龙-程序员,转载请注明原文链接:https://www.cnblogs.com/sunlong88/articles/8944912.html