Linsten http server onRequest

@param  \Swoole\Http\Request  $request
@param  \Swoole\Http\Response $response
171800
public function onRequest(Request $request, Response $response)
    {
        // Compat fpm server
        $this->_compatFPM($request);

        // 注入全局变量
        $GLOBALS['__$response'] = $response;

        $response->header('Server', 'ePHP/'. $this->version);

        $filename = APP_PATH . '/public'. $_SERVER['PATH_INFO'];

        // !in_array($extname, ['css', 'js', 'png', 'jpg', 'jpeg', 'gif', 'ico'])
        // Try files, otherwise route to app
        if ( !is_file($filename) ) {
            ob_start();
            (new \ePHP\Core\Application())->run();
            $h = ob_get_clean();

            // Fixed output o byte
            // if (strlen($h) === 0) {
            //     $h = ' ';
            // }

            $response->end($h);
        } else {
            $extname = substr($filename, strrpos($filename, '.') + 1);
            if ( isset( $this->contentType[$extname] ) ) {
                $response->header('Content-Type', $this->contentType[$extname]);
            }
            $response->sendfile($filename);
        }

        // 非调试模式，打印访问日志
        $this->printAccessLog();
    }
794388
public function onRequest(Request $request, Response $response)
    {
        try {
            // 处理 406
            $responder = $this->getResponder();

            if ($responder->getAcceptHandler($request) === null) {
                throw ProtocolException::notAcceptable(
                    $request->getHeaderLine('Accept'),
                    $request->getProtocol()
                );
            }

            $response = $this->handle($request, $response);
        } catch (MiddlewareException $e) {
            // {{ log
            $this->logger->error(
                sprintf('中间件 %s 发生异常', $e->getMiddleware()),
                [
                    'error' => $e->getMessage(),
                    'errno' => $e->getCode()
                ]
            );
            // }}

            $response = $responder(
                $request,
                $response,
                new Payload(
                    500,
                    $e->getMessage()
                )
            );
        } catch (ProtocolException $e) {
            // {{ log
            $this->logger->error(
                sprintf('处理 %s 请求发生异常', strtoupper($e->getProtocol())),
                [
                    'error' => $e->getMessage(),
                    'errno' => $e->getCode(),
                    'uri' => $request->getRequestTarget(),
                ]
            );
            // }}

            $response = $e->makeResponse($request, $response, $responder);
        } catch (Exception $e) {
            // {{ log
            $this->logger->error(
                '系统错误',
                [
                    'error' => $e->getMessage(),
                    'errno' => $e->getCode()
                ]
            );
            // }}

            $response = $responder(
                $request,
                $response,
                new Payload(
                    500,
                    $e->getMessage()
                )
            );
        }

        unset($responder);

        return $response->end();
    }
482555
public function launch(Request $request, Response $response)
    {
        if (count($this->routes) === 0) {
            throw new \RuntimeException("No routes defined");
        }

        $this->uri = $request->httpRequest->getPath();

        if ($this->uri = null) {
            $this->uri = "/";
        }

        $request->on('end', function () use (&$request, &$response) {
            $this->matchRoutes($request, $response);  
        });

        $request->on('error', function ($error) use (&$request, &$response) {
            $this->emit('error', [$request, $response, $error]);
        });

        $request->parseData();
    }
1197861
protected function setUriHeader(Request $request, Response $response)
    {
        $response->headers->set('X-PJAX-URL', $request->getUrl());

        return $this;
    }
1023112
private function send(Response $response, Request $request = null): \Generator
    {
        \assert($this->client, "The driver has not been setup; call setup first");

        if ($this->lastWrite) {
            yield $this->lastWrite; // Prevent writing another response until the first is finished.
        }

        $shouldClose = false;

        $protocol = $request !== null ? $request->getProtocolVersion() : "1.0";

        $status = $response->getStatus();
        $reason = $response->getReason();

        $headers = $this->filter($response, $protocol, $request ? $request->getHeaderArray("connection") : []);

        $chunked = !isset($headers["content-length"])
            && $protocol === "1.1"
            && $status >= Status::OK;

        if (!empty($headers["connection"])) {
            foreach ($headers["connection"] as $connection) {
                if (\strcasecmp($connection, "close") === 0) {
                    $chunked = false;
                    $shouldClose = true;
                }
            }
        }

        if ($chunked) {
            $headers["transfer-encoding"] = ["chunked"];
        }

        $buffer = "HTTP/{$protocol} {$status} {$reason}\r\n";
        $buffer .= Rfc7230::formatHeaders($headers);
        $buffer .= "\r\n";

        if ($request !== null && $request->getMethod() === "HEAD") {
            ($this->write)($buffer, $shouldClose);
            return;
        }

        $chunk = ""; // Required for the finally, not directly overwritten, even if your IDE says otherwise.
        $body = $response->getBody();
        $streamThreshold = $this->options->getStreamThreshold();

        try {
            while (null !== $chunk = yield $body->read()) {
                if (!($length = \strlen($chunk))) {
                    continue;
                }

                if ($chunked) {
                    $chunk = \sprintf("%x\r\n%s\r\n", $length, $chunk);
                }

                if (\strlen($buffer) < $streamThreshold) {
                    $buffer .= $chunk;
                    continue;
                }

                // Initially the buffer won't be empty and contains the headers.
                // We save a separate write or the headers here.
                $promise = ($this->write)($buffer);

                $buffer = $chunk;
                $chunk = ""; // Don't use null here, because of the finally

                yield $promise;
            }

            if ($buffer !== "" || $chunked || $shouldClose) {
                yield ($this->write)($chunked ? "{$buffer}0\r\n\r\n" : $buffer, $shouldClose);
            }
        } catch (ClientException $exception) {
            return; // Client will be closed in finally.
        } finally {
            if ($chunk !== null) {
                $this->client->close();
            }
        }
    }
1046933
public function postProcess(Request $request, Response $response)
    {
        if (empty($this->allowedOriginHosts) || !$request->hasHeader('HTTP_ORIGIN')) {
            return;
        }

        $originHost = $request->readHeader('HTTP_ORIGIN')->unsecure();
        foreach ($this->allowedOriginHosts as $allowedOriginHost) {
            if (preg_match('~' . $allowedOriginHost . '~', $originHost) === 1) {
                $response->addHeader('Access-Control-Allow-Origin', $originHost);
            }
        }
    }
316197
public function run(ServerRequestInterface $request, ResponseInterface $response)
    {
        $route = $request->getAttribute('route');
        $callback = !empty($route->fn) ? $route->fn : null;

        if (!is_callable($callback)) {
            trigger_error("'fn' property of route shoud be a callable", E_USER_NOTICE);
            return $this->notFound($request, $response);
        }

        return $callback($request, $response);
    }
1157045
public function run(ServerRequestInterface $request, ResponseInterface $response)
    {
        $route = $request->getAttribute('route');        
        $name = !empty($route->controller) ? $route->controller : 'default';
        
        try {
            $controller = call_user_func($this->getFactory(), $name);
        } catch (\Exception $ex) {
            trigger_error($ex->getMessage(), E_USER_NOTICE);
            return $this->notFound($request, $response);
        }

        if (!method_exists($controller, '__invoke')) {
            $class = get_class($controller);
            trigger_error("Can't route to controller '$class': class does not have '__invoke' method", E_USER_NOTICE);
            return $this->notFound($request, $response);
        }
        
        return $controller($request, $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);
    }
892227
protected function handle(ServerRequestInterface $request, ResponseInterface $response): ResponseInterface
    {
        $cors = $this->cors->getCors();
        $cors->setRequest('psr-7', $request);
        $cors->setResponse('psr-7', $response);
        $cors->handle();

        return $cors->getResponse();
    }
890782
public function fireOnReceivedResponse(HttpResponse $response)
    {
        $event = EnumEvent::RESPONSE;
        if (isset($this->listeners[$event]) && is_array($this->listeners[$event]))
        {
            foreach($this->listeners[$event] as $l)
            {
                $l($response);
            }
        }
    }
1032561
protected function addJquery(Request $request, Response $response)
    {
        if (!$this->config->get('general/add_jquery', false) &&
            !$this->config->get('theme/add_jquery', false)) {
            return;
        }

        // Check zone to skip expensive regex
        if (Zone::isFrontend($request) === false) {
            return;
        }

        $html = $response->getContent();
        $regex = '/<script(.*)jquery(-latest|-[0-9\.]*)?(\.min)?\.js/';
        if (preg_match($regex, $html)) {
            return;
        }

        $this->add(
            (new JavaScript('js/jquery-2.2.4.min.js', 'bolt'))
                ->setLocation(Target::BEFORE_JS)
        );
    }
343653
public function terminate($request, $response)
    {
        $middlewares = array_merge(
            $this->gatherRouteMiddlewares($request),
            $this->middleware
        );

        foreach ($middlewares as $middleware) {
            list($name, $parameters) = $this->parseMiddleware($middleware);

            $instance = $this->app->make($name);

            if (method_exists($instance, 'terminate')) {
                $instance->terminate($request, $response);
            }
        }

        //$this->app->terminate();
    }
1267913
public function prepareResponse($request, $response)
    {
        if (! $response instanceof SymfonyResponse) {
            $response = new Response($response);
        }

        return $response->prepare($request);
    }
524529
public function renderRequest(Request $request, Response $response, RenderingContext $renderingContext)
    {
        $contentObjectRenderer = new ContentObjectRenderer();
        $content = $contentObjectRenderer->cObjGetSingle('RECORDS', $this->resolveRenderingConfiguration($request, $renderingContext));
        $response->setContent($content);
    }
156720
protected function afterRequest(HTTPRequest $request, HTTPResponse $response)
    {
        $debugbar = DebugBar::getDebugBar();
        if (!$debugbar) {
            return;
        }
        DebugBar::setRequest($request);

        // All queries have been displayed
        if (DebugBar::getShowQueries()) {
            exit();
        }

        $script = DebugBar::renderDebugBar();

        // If the bar is not renderable, return early
        if (!$script) {
            return;
        }

        // Inject init script into the HTML response
        $body = $response->getBody();
        if (strpos($body, '</body>') !== false) {
            if (Requirements::get_write_js_to_body()) {
                $body = str_replace('</body>', $script . '</body>', $body);
            } else {
                // Ensure every js script is properly loaded before firing custom script
                $script = strip_tags($script);
                $script = "window.addEventListener('DOMContentLoaded', function() { $script });";
                $script = '<script type="application/javascript">//<![CDATA[' . "\n" . $script . "\n</script>";
                $body = str_replace('</head>', $script . '</head>', $body);
            }
            $response->setBody($body);
        }

        // Ajax support
        if (Director::is_ajax() && !headers_sent()) {
            if (DebugBar::isAdminUrl() && !DebugBar::config()->get('enabled_in_admin')) {
                return;
            }
            // Skip anything that is not a GET request
            if (!$request->isGET()) {
                return;
            }
            // Always enable in admin because everything is mostly loaded through ajax
            if (DebugBar::config()->get('ajax') || DebugBar::isAdminUrl()) {
                $headers = $debugbar->getDataAsHeaders();

                // Prevent throwing js errors in case header size is too large
                if (is_array($headers)) {
                    $maxHeaderLength = DebugBar::config()->get('max_header_length');
                    $debugbar->sendDataInHeaders(null, 'phpdebugbar', $maxHeaderLength);
                }
            }
        }
    }
441420
public function runBefore(Request $request, Response $response)
    {
        foreach ($this->middlewares as $middleware) {
            if (class_exists($middleware)) {
                $instance = new $middleware($request, $response);
                if ($instance instanceof MiddlewareAbstract) {
                    /* @var $instance MiddlewareAbstract */
                    $instance->onBefore();
                    $this->running[] = $instance;
                }
            }
        }
    }