HTTP请求回调

@param \swoole_http_request $request 请求对象
@param \swoole_http_response $response 响应对象
17309
public function onRequest($request, $response)
    {
        $this->requestId++;
        $error              = '';
        $httpCode           = 500;
        $logId              = $this->genLogId($request);
        $instance           = null;
        $this->route->handleHttpRequest($request);

        // 构造请求日志对象
        $PGLog            = clone getInstance()->log;
        $PGLog->accessRecord['beginTime'] = microtime(true);
        $PGLog->accessRecord['uri']       = $this->route->getPath() ?: '/';
        $PGLog->logId     = $logId;
        defined('SYSTEM_NAME') && $PGLog->channel = SYSTEM_NAME;
        $PGLog->init();
        $PGLog->pushLog('verb', $this->route->getVerb());
        $PGLog->pushLog('user-agent', $request->header['user-agent'] ?? 'unknown');
        $PGLog->pushLog('remote-addr', self::getRemoteAddr($request));

        do {
            if ($this->route->getPath() == '') {
                $indexFile = $this->route->domainRoot[$this->route->getHost()]['index'] ?? null;
                $response->header('X-Ngx-LogId', $PGLog->logId);
                $httpCode  = $this->sendFile($indexFile, $request, $response);
                $PGLog->pushLog('http-code', $httpCode);
                $PGLog->appendNoticeLog();
                return;
            }

            if ($this->route->getFile()) {
                $response->header('X-Ngx-LogId', $PGLog->logId);
                $httpCode  = $this->sendFile($this->route->getFile(), $request, $response);
                $PGLog->pushLog('http-code', $httpCode);
                $PGLog->appendNoticeLog();
                return;
            }

            $controllerName      = $this->route->getControllerName();
            $controllerClassName = $this->route->getControllerClassName();
            if ($controllerClassName == '') {
                $error    = 'Api not found controller(' . $controllerName . ')';
                $httpCode = 404;
                break;
            }

            $methodPrefix = $this->route->methodPrefix;
            $methodName   = $methodPrefix . $this->route->getMethodName();

            try {
                /**
                 * @var \PG\MSF\Controllers\Controller $instance
                 */
                $instance = $this->objectPool->get($controllerClassName, [$controllerName, $methodName]);
                $instance->__useCount++;
                if (empty($instance->getObjectPool())) {
                    $instance->setObjectPool(AOPFactory::getObjectPool(getInstance()->objectPool, $instance));
                }

                if (!method_exists($instance, $methodName)) {
                    $error    = 'Api not found method(' . $methodName . ')';
                    $httpCode = 404;
                    break;
                }

                $instance->context = $instance->getObjectPool()->get(Context::class, [$this->requestId]);
                // 初始化控制器
                $instance->requestStartTime = microtime(true);

                // 构造请求上下文成员
                $instance->context->setLogId($PGLog->logId);
                $instance->context->setLog($PGLog);
                $instance->context->setObjectPool($instance->getObjectPool());

                /**
                 * @var $input Input
                 */
                $input    = $instance->context->getObjectPool()->get($this->input);
                $input->set($request);
                /**
                 * @var $output Output
                 */
                $output   = $instance->context->getObjectPool()->get($this->output, [$instance]);
                $output->set($request, $response);

                $instance->context->setInput($input);
                $instance->context->setOutput($output);
                $instance->context->setControllerName($controllerName);
                $instance->context->setActionName($methodName);
                $instance->setRequestType(Macro::HTTP_REQUEST);
                $init = $instance->__construct($controllerName, $methodName);

                if ($init instanceof \Generator) {
                    $this->scheduler->start(
                        $init,
                        $instance,
                        function () use ($instance, $methodName) {
                            try {
                                if ($instance->getContext()->getOutput()->__isEnd) {
                                    $instance->destroy();
                                    return false;
                                }

                                $generator = $instance->$methodName(...array_values($this->route->getParams()));
                                if ($generator instanceof \Generator) {
                                    $this->scheduler->taskMap[$instance->context->getRequestId()]->resetRoutine($generator);
                                    $this->scheduler->schedule(
                                        $this->scheduler->taskMap[$instance->context->getRequestId()],
                                        function () use ($instance) {
                                            if (!$instance->getContext()->getOutput()->__isEnd) {
                                                $instance->getContext()->getOutput()->output('Not Implemented', 501);
                                            }
                                            $instance->destroy();
                                        }
                                    );
                                } else {
                                    if (!$instance->getContext()->getOutput()->__isEnd) {
                                        $instance->getContext()->getOutput()->output('Not Implemented', 501);
                                    }
                                    $instance->destroy();
                                }
                            } catch (\Throwable $e) {
                                if (!$instance->getContext()->getOutput()->__isEnd) {
                                    $instance->onExceptionHandle($e);
                                }
                                $instance->destroy();
                            }
                        }
                    );
                } else {
                    $generator = $instance->$methodName(...array_values($this->route->getParams()));
                    if ($generator instanceof \Generator) {
                        $this->scheduler->start(
                            $generator,
                            $instance,
                            function () use ($instance) {
                                if (!$instance->getContext()->getOutput()->__isEnd) {
                                    $instance->getContext()->getOutput()->output('Not Implemented', 501);
                                }
                                $instance->destroy();
                            }
                        );
                    } else {
                        if (!$instance->getContext()->getOutput()->__isEnd) {
                            $instance->getContext()->getOutput()->output('Not Implemented', 501);
                        }
                        $instance->destroy();
                    }
                }

                if ($this->route->getEnableCache() && !$this->route->getRouteCache($this->route->getPath())) {
                    $this->route->setRouteCache(
                        $this->route->getPath(),
                        [$controllerName, $this->route->getMethodName(), $controllerClassName]
                    );
                }
                break;
            } catch (\Throwable $e) {
                $instance->onExceptionHandle($e);
                $instance->destroy();
            }
        } while (0);

        if ($error !== '') {
            if ($instance != null) {
                $instance->destroy();
            }

            $PGLog->pushLog('http-code', $httpCode);
            $PGLog->appendNoticeLog();
            $response->status($httpCode);
            $response->end($error);
        }
    }
460760
public function modifyResponse(Request $request, Response $response)
    {
        $app = $this->app;
        if (!$this->isEnabled() || $this->isDebugbarRequest()) {
            return $response;
        }

        // Show the Http Response Exception in the Debugbar, when available
        if (isset($response->exception)) {
            $this->addThrowable($response->exception);
        }

        if ($this->shouldCollect('config', false)) {
            try {
                $configCollector = new ConfigCollector();
                $configCollector->setData($app['config']->all());
                $this->addCollector($configCollector);
            } catch (\Exception $e) {
                $this->addThrowable(
                    new Exception(
                        'Cannot add ConfigCollector to Laravel Debugbar: ' . $e->getMessage(),
                        $e->getCode(),
                        $e
                    )
                );
            }
        }

        if ($this->app->bound(SessionManager::class)){

            /** @var \Illuminate\Session\SessionManager $sessionManager */
            $sessionManager = $app->make(SessionManager::class);
            $httpDriver = new SymfonyHttpDriver($sessionManager, $response);
            $this->setHttpDriver($httpDriver);

            if ($this->shouldCollect('session') && ! $this->hasCollector('session')) {
                try {
                    $this->addCollector(new SessionCollector($sessionManager));
                } catch (\Exception $e) {
                    $this->addThrowable(
                        new Exception(
                            'Cannot add SessionCollector to Laravel Debugbar: ' . $e->getMessage(),
                            $e->getCode(),
                            $e
                        )
                    );
                }
            }
        } else {
            $sessionManager = null;
        }

        if ($this->shouldCollect('symfony_request', true) && !$this->hasCollector('request')) {
            try {
                $this->addCollector(new RequestCollector($request, $response, $sessionManager, $this->getCurrentRequestId()));
            } catch (\Exception $e) {
                $this->addThrowable(
                    new Exception(
                        'Cannot add SymfonyRequestCollector to Laravel Debugbar: ' . $e->getMessage(),
                        $e->getCode(),
                        $e
                    )
                );
            }
        }

        if ($app['config']->get('debugbar.clockwork') && ! $this->hasCollector('clockwork')) {

            try {
                $this->addCollector(new ClockworkCollector($request, $response, $sessionManager));
            } catch (\Exception $e) {
                $this->addThrowable(
                    new Exception(
                        'Cannot add ClockworkCollector to Laravel Debugbar: ' . $e->getMessage(),
                        $e->getCode(),
                        $e
                    )
                );
            }

            $this->addClockworkHeaders($response);
        }

        if ($response->isRedirection()) {
            try {
                $this->stackData();
            } catch (\Exception $e) {
                $app['log']->error('Debugbar exception: ' . $e->getMessage());
            }
        } elseif (
            $this->isJsonRequest($request) &&
            $app['config']->get('debugbar.capture_ajax', true)
        ) {
            try {
                $this->sendDataInHeaders(true);

                if ($app['config']->get('debugbar.add_ajax_timing', false)) {
                    $this->addServerTimingHeaders($response);
                }

            } catch (\Exception $e) {
                $app['log']->error('Debugbar exception: ' . $e->getMessage());
            }
        } elseif (
            ($response->headers->has('Content-Type') &&
                strpos($response->headers->get('Content-Type'), 'html') === false)
            || $request->getRequestFormat() !== 'html'
            || $response->getContent() === false
            || $this->isJsonRequest($request)
        ) {
            try {
                // Just collect + store data, don't inject it.
                $this->collect();
            } catch (\Exception $e) {
                $app['log']->error('Debugbar exception: ' . $e->getMessage());
            }
        } elseif ($app['config']->get('debugbar.inject', true)) {
            try {
                $this->injectDebugbar($response);
            } catch (\Exception $e) {
                $app['log']->error('Debugbar exception: ' . $e->getMessage());
            }
        }



        return $response;
    }
1045635
public function onSwooleRequest($request, $response)
    {
        if (Start::$testUnity) {
            $server_port = $request->server_port;
        } else {
            $server_port = $this->getServerPort($request->fd);
        }

        $middleware_names = $this->portManager->getMiddlewares($server_port);
        $context = [];
        $path = $request->server['path_info'];
        $middlewares = $this->middlewareManager->create($middleware_names, $context, [$request, $response], true);
        //before
        try {
            $this->middlewareManager->before($middlewares);
            //client_data进行处理
            $route = $this->portManager->getRoute($server_port);
            try {
                $route->handleClientRequest($request);
                $controller_name = $route->getControllerName();
                $method_name = $this->portManager->getMethodPrefix($server_port) . $route->getMethodName();
                $path = $route->getPath();
                if ($route->getMethodName() == ConsulHelp::HEALTH) {//健康检查
                    $response->end('ok');
                } else {
                    $controller_instance = ControllerFactory::getInstance()->getController($controller_name);
                    if ($controller_instance != null) {
                        $controller_instance->setContext($context);
                        $controller_instance->setRequestResponse($request, $response, $controller_name, $method_name, $route->getParams());
                    } else {
                        throw new \Exception('no controller');
                    }
                }
            } catch (\Throwable $e) {
                $route->errorHttpHandle($e, $request, $response);
            }
        } catch (\Exception $e) {
            //被中断
        }
        //after
        try {
            $this->middlewareManager->after($middlewares, $path);
        } catch (\Exception $e) {
            //被中断
        }
        $this->middlewareManager->destory($middlewares);
        if (Start::getDebug()) {
            secho("DEBUG", $context);
        }
        unset($context);
    }
1286564
public static function parseResponse(Response $response)
    {
        $jsonData = \GuzzleHttp\json_decode($response->getBody(), true);
        //有时候获取好友接口retcode=100003时也可以获取数据，但数据不完整故当做无效返回
        if ($jsonData && 0 == $jsonData['retcode']) {
            //好友基本信息
            $friendDatas = (new Collection($jsonData['result']['friends']))->combine('uin', function ($entity) {
                return $entity;
            })->toArray();
            //markNames
            $markNames = (new Collection($jsonData['result']['marknames']))->combine('uin', function ($entity) {
                return $entity;
            })->toArray();
            //分类
            $categories = (new Collection($jsonData['result']['categories']))->combine('index', function ($entity) {
                return $entity;
            })->toArray();
            //vip信息
            $vipInfos = (new Collection($jsonData['result']['vipinfo']))->combine('u', function ($entity) {
                return $entity;
            })->toArray();
            $friends = [];
            foreach ($jsonData['result']['info'] as $friendData) {
                $uin = $friendData['uin'];
                $friend = [
                    'uin' => $friendData['uin'],
                    'flag' => $friendData['flag'],
                    'face' => $friendData['face'],
                    'nick' => $friendData['nick'],
                    'markName' => isset($markNames[$uin]) ? $markNames[$uin]['markname'] : null,
                    'isVip' => isset($vipInfos[$uin]) ? 1 == $vipInfos[$uin]['is_vip'] : false,
                    'vipLevel' => isset($vipInfos[$uin]) ? $vipInfos[$uin]['vip_level'] : 0,
                ];
                $category = null;
                if (isset($friendDatas[$uin])) {
                    $categoryIndex = $friendDatas[$uin]['categories'];
                    if (0 == $categoryIndex) {
                        $category = Category::createMyFriendCategory();
                    } else {
                        $category = new Category(
                            $categories[$categoryIndex]['name'],
                            $categories[$categoryIndex]['index'],
                            $categories[$categoryIndex]['sort']
                        );
                    }
                }
                $friend['category'] = $category;
                $friends[] = EntityFactory::createEntity(Friend::class, $friend);
            }

            return new EntityCollection($friends);
        }
        throw new ResponseException($jsonData['retcode'], $response);
    }
1306643
public static function onRequest($request, $response) {
		$request = new Request($request);
		$request->setCookieHandler([$response, 'cookie']);
		$response = new Response($response);
		Container::getInstance()
			->get(Dispatcher::class)
			->handleRequest($request, $response);
	}
1337082
public function handle($request, $response)
    {
        // init options, don't place this in __construct, because defaultOptions could be get action name.
        if ($doptions = static::defaultOptions()) {
            $this->options = array_merge($this->options, $doptions);
        }
        
        // start ob, ob_flush() 由具体render()方法根据情况调用
        ob_start();
        
        $this->request  = $request;
        $this->response = $response;
        
        $this->getHandleStack($request);
        
        static::trigger('beforeHandle');
        
        if (!$this->handleStack) {
            return $this->response;
        }
        
        $handler = $this->getHandler();
        if (!$handler instanceof Controller) {
            $handler->request   = $request;
            $handler->response  = $response;
            $handler->module    = $this->module;
            $handler->handleStack = & $this->handleStack;
        }
        
        // call handler stack
        $output = null;
        
        foreach ($this->handleStack as $do) {
            if ($this->isStopped()) {
                if ($res = $this->getError()) {
                    $output = $this->error($res);
                }
                break;
            };
            
            $output = is_callable($do) ? call_user_func_array($do, [$request, $response]) : $handler->$do();
        }
        
        // output handle, must be run
        $this->_outputHandle($output);
        
        static::trigger('afterHandle');
        
        // Return the response
        return $this->response;
    }
1315676
public function postRequest(HTTPRequest $request, HTTPResponse $response = null)
    {
        if ($response &&
            preg_match('/text\/html/', $response->getHeader('Content-Type')) &&
            !preg_match('/^(admin|dev)\//', $request->getURL())
        ) {
            $response->setBody(
                $this->obfuscateEmails($response->getBody())
            );
        }
    }
957285
function doStaticRequest(Swoole\Request $request, Swoole\Response $response)
    {
        $path = explode('/', trim($request->meta['path'], '/'));
        //扩展名
        $request->ext_name = $ext_name = Swoole\Upload::getFileExt($request->meta['path']);
        /* 检测是否拒绝访问 */
        if (isset($this->deny_dir[$path[0]]))
        {
            $this->httpError(403, $response, "服务器拒绝了您的访问({$request->meta['path']})");
            return true;
        }
        /* 是否静态目录 */
        elseif (isset($this->static_dir[$path[0]]) or isset($this->static_ext[$ext_name]))
        {
            return $this->processStatic($request, $response);
        }
        return false;
    }
435925
private function matchRoutes(Request $request, Response $response)
    {
        $stack  = [];
        $path   = $request->httpRequest->getPath();
        $method = $request->httpRequest->getMethod();

        foreach ($this->routes as $route) {
            if (!$route->match($path, $method)) {
                continue;
            }

            $methodArgs = $route->getArgs($path);
            $request->setData($methodArgs);

            $route->on('error', function (...$args) {
                $this->emit('error', $args);
            });

            $stack[] = function (...$params) use ($route) {
                $route->run(...$params);
            };
        }

        if (count($stack) == 0) {
            $this->emit('NotFound', array($request, $response));
            return;
        }

        $this->runStack($stack, $request, $response);
    }
522552
private function checkCsrf(Request $request, Response $response)
    {
        if (!$this->session->has($request, self::CSRF_KEY)) {
            return $this->errorResponse($request, $response, self::EXCEPTION_MISSING_IN_SESSION);
        }

        $data = $request->getParsedBody();

        if (!isset($data[self::CSRF_KEY])) {
            return $this->errorResponse($request, $response, self::EXCEPTION_MISSING_IN_BODY);
        }

        if ($this->session->get($request, self::CSRF_KEY) !== $data[self::CSRF_KEY]) {
            return $this->errorResponse($request, $response, self::EXCEPTION_IS_NOT_SAME);
        }

        return null;
    }
878321
public function handleResponse(Request $request, Response $response)
    {
        if ($response->getStatusCode() == 422) {
            $errors = $response->getOriginalContent()['validation_errors'];

            throw new HttpResponseException(
                redirect()->back()->withInput($request->input())->withErrors($errors)
            );
        }

        if ($response->getStatusCode() == 403) {
            abort(403);
        }

        return $response->isNotFound() ? abort(404) : $response->getOriginalContent();
    }
571186
public function set(&$request, &$response = null)
    {
        $this->request  = $request;
        $this->response = $response;
        return $this;
    }
414952
public function init($request, $response)
    {
        $this->request = $request;
        $this->response = $response;

        $this->c()->set('request', $request);
        $this->c()->set('response', $response);
    }
1290348
protected function setUriHeader(Response $response, Request $request)
    {
        $response->header('X-PJAX-URL', $request->getRequestUri());

        return $this;
    }
1311
function afterResponse(Swoole\Request $request, Swoole\Response $response)
    {
        if ($request->isWebSocket())
        {
            $conn = array('header' => $request->header, 'time' => time());
            $this->connections[$request->fd] = $conn;

            if (count($this->connections) > $this->max_connect)
            {
                $this->cleanConnection();
            }

            $this->onWsConnect($request->fd, $request);
        }
        parent::afterResponse($request, $response);
    }
1020804
public function resolve(Request $request, Response $response)
    {
        return $response->methodNotAllowed(
                $request->method(),
                $this->allowedMethods
        );
    }
726538
public function decorateResponse(Request $request, Response $response)
    {
        if ($request->headers->has(self::ORIGIN_REQUEST_HEADER)) {
            $request->headers->set('referer', $request->headers->get(self::ORIGIN_REQUEST_HEADER));
        }

        $this->setTurbolinksLocationHeaderFromSession($request, $response);

        if ($response->isRedirect() && $response->headers->has(self::ORIGIN_RESPONSE_HEADER)) {
            $this->redirectTo($request, $response);
        }

        $this->modifyStatusCode($request, $response);
    }