处理响应
@param Response $response
@since 2.1
772930
protected function processResult(Response $response)
    {
        $content = $response->getContent();
        if (strpos($content, "callback(") === 0) {
            $count = 0;
            $jsonData = preg_replace('/^callback\(\s*(\\{.*\\})\s*\);$/is', '\1', $content, 1, $count);
            if ($count === 1) {
                $response->setContent($jsonData);
            }
        }
    }
756005
protected function logResponse(Response $response)
    {
        $raw_body = (string) $response->getBody();
        $body = json_decode($raw_body, true);
        if ($body === null) {
            // the response body is not in JSON format
            $this->logger->error($raw_body);
        } elseif (isset($body['error'])) {
            if (isset($body['message'])) {
                $this->logger->error($body['message']);
            }
        } else {
            if (isset($body['message'])) {
                $this->logger->info(sprintf('Accepted %s', $body['message']));
            }

            if (isset($body['url'])) {
                $this->logger->info(sprintf('You can see the build on %s', $body['url']));
            }
        }
    }
537817
public function sendByResponse(Response $response)
    {
        $this->sendHeaders($response);
        $this->sendBody($response);
        if (function_exists('fastcgi_finish_request')) {
            fastcgi_finish_request();
        } else {
            static::closeOutputBuffers(0, true);
        }
    }
969658
public function response($response, $context = null)
    {
        $responseMessage = $response->asResponseMessage($context);
        $this->responseMessage($responseMessage);
    }
346708
public function handleResponse(Response $response) : void
    {
        if ($this->id === null) {
            // The request was not associated with an existing session, and no session writes occurred.
            // Sending a session cookie is unnecessary.
            return;
        }

        // Note: we re-send the session cookie even if it was part of the request, to refresh the expiration time.

        $this->writeSessionId($response);
        $this->reset();
    }
843939
public function format($response)
    {
        if (stripos($this->contentType, 'charset') === false) {
            $this->contentType .= '; charset=' . $response->encoding;
        }
        $response->setHeader('Content-Type', $this->contentType);
        if ($response->data !== null) {
            $response->content = $response->data;
        }
    }
724618
public function execute($response) {
        global $CFG, $DB;

        $params = $this->parse_template();
        $contextid = $params['context_id'];
        $itemid = $params['item_id'];
        if ($response->get_request_method() === 'GET') {
            $contenttype = $response->get_accept();
        } else {
            $contenttype = $response->get_content_type();
        }
        // We will receive typeid when working with LTI 1.x, if not then we are in LTI 2.
        $typeid = optional_param('type_id', null, PARAM_ALPHANUM);
        if (is_null($typeid)) {
            if (!$this->check_tool_proxy(null, $response->get_request_data())) {
                $response->set_code(403);
                $response->set_reason("Invalid tool proxy specified.");
                return;
            }
        } else {
            switch ($response->get_request_method()) {
                case self::HTTP_GET:
                    if (!$this->check_type($typeid, $contextid, 'LineItem.item:get', $response->get_request_data())) {
                        $response->set_code(403);
                        $response->set_reason("This resource does not support GET requests.");
                        return;
                    }
                    break;
                case self::HTTP_PUT:
                    if (!$this->check_type($typeid, $contextid, 'LineItem.item:put', $response->get_request_data())) {
                        $response->set_code(403);
                        $response->set_reason("This resource does not support PUT requests.");
                        return;
                    }
                    break;
                case self::HTTP_DELETE:
                    if (!$this->check_type($typeid, $contextid, 'LineItem.item:delete', $response->get_request_data())) {
                        $response->set_code(403);
                        $response->set_reason("This resource does not support DELETE requests.");
                        return;
                    }
                    break;
                default:  // Should not be possible.
                    $response->set_code(405);
                    return;
            }
        }
        if (empty($contextid) || (!empty($contenttype) && !in_array($contenttype, $this->formats))) {
            $response->set_code(400);
            $response->set_reason("Invalid request made.");
            return;
        }
        if (!$DB->record_exists('course', array('id' => $contextid))) {
            $response->set_code(404);
            $response->set_reason("Not Found: Course $contextid doesn't exist.");
            return;
        }
        if (!$DB->record_exists('grade_items', array('id' => $itemid))) {
            $response->set_code(404);
            $response->set_reason("Not Found: Grade item $itemid doesn't exist.");
            return;
        }
        $item = $this->get_service()->get_lineitem($contextid, $itemid, $typeid);
        if ($item === false) {
            $response->set_code(403);
            $response->set_reason("Line item does not exist.");
            return;
        }
        require_once($CFG->libdir.'/gradelib.php');
        switch ($response->get_request_method()) {
            case 'GET':
                $this->get_request($response, $item, $typeid);
                break;
            case 'PUT':
                $json = $this->process_put_request($response->get_request_data(), $item, $typeid);
                $response->set_body($json);
                $response->set_code(200);
                break;
            case 'DELETE':
                $this->process_delete_request($item);
                $response->set_code(204);
                break;
            default:  // Should not be possible.
                $response->set_code(405);
                $response->set_reason("Invalid request method specified.");
                return;
        }
    }
751200
public function extend(IHttpResponse $response) {
        $this->setHeaders(clone($response->getHeaders()));
        $this->setProtocol($response->getProtocol());
        $this->setProtocolVersion($response->getProtocolVersion());
        $this->setStatusCode($response->getStatusCode());
        $this->setContent($response->getContent());
        $this->setCookies(clone($response->getCookies()));

        $this->setDefaultContentType();
    }
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();
    }
192545
private function persistResponse(Response $response)
    {
        $headers = $response->headers->all();
        $headers['X-Status'] = [$response->getStatusCode()];

        return $headers;
    }
1081840
protected function _sendResponse($response)
    {
        if (is_string($response)) {
            echo $response;

            return;
        }

        $emitter = new ResponseEmitter();
        $emitter->emit($response);
    }
684349
public function updateFromResponse(Response $response, $uri = null)
    {
        $this->updateFromSetCookie($response->getHeader('Set-Cookie', false), $uri);
    }
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);
        }
    }
697066
public function send(Response $response = null)
    {
        if ($response) {
            $this->response = $response;
        }
        $this->response->prepare($this->request);
        $this->response->send();

        // If a cacheWrite callback exists execute
        // it now to write the image to the cache
        if (is_callable($this->cacheWrite)) {
            call_user_func_array(
                $this->cacheWrite,
                array($this->cache, $this->getCachePath())
            );
        }
    }
590793
public function onRequest(Request $request, Response $response)
    {
        // Initialize Request and Response and set to RequestContent
        $psr7Request = \Swoft\Http\Message\Server\Request::loadFromSwooleRequest($request);
        $psr7Response = new \Swoft\Http\Message\Server\Response($response);

        /** @var \Swoft\Http\Server\ServerDispatcher $dispatcher */
        $dispatcher = App::getBean('serverDispatcher');
        $dispatcher->dispatch($psr7Request, $psr7Response);
    }
708198
public function resolve(Request $request, Response $response)
    {
        $allowedMethods = $this->matchingRoutes->allowedMethods();
        if (!in_array(Http::OPTIONS, $allowedMethods)) {
            $allowedMethods[] = Http::OPTIONS;
        }

        $response->addHeader('Allow', join(', ', $allowedMethods))
                ->addHeader(
                        'Access-Control-Allow-Methods',
                        join(', ', $allowedMethods)
                );
    }
1122394
public function process(\BearFramework\App\Response $response): void
    {
        $response->content = $this->app->components->process($response->content);
    }