接收 HTTP 请求

@param  \Swoole\Http\Request  $swRequest
@param  \Swoole\Http\Response $swResponse
320221
public function onRequest(SwRequest $swRequest, SwResponse $swResponse)
    {
        $request = Factory::newHttpRequest($swRequest);
        $response = Factory::newHttpResponse($swResponse);

        // {{ log
        $this->get('logger')->info('接收数据', [
            'type' => 'HTTP',
            'method' => $request->getMethod(),
            'uri' => $request->getRequestTarget(),
            'client' => $request->getClientIP()
        ]);
        // }}

        // {{
        $this->callProtocolMethod('onRequest', $request, $response);
        // }}

        unset($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);
    }
537782
public static function handleStatic($swooleRequest, $swooleResponse, string $publicPath)
    {
        $uri = $swooleRequest->server['request_uri'] ?? '';
        $extension = strtok(pathinfo($uri, PATHINFO_EXTENSION), '?');
        $fileName = $publicPath . $uri;

        if ($extension && in_array($extension, static::EXTENSION_BLACKLIST)) {
            return false;
        }

        if (! is_file($fileName) || ! filesize($fileName)) {
            return false;
        }

        $swooleResponse->status(IlluminateResponse::HTTP_OK);
        $swooleResponse->header('Content-Type', MimeType::get($extension));
        $swooleResponse->sendfile($fileName);

        return true;
    }
860479
protected function sendResetLinkResponse(Request $request, $response)
    {
        if ($request->expectsJson()) {
            return response()->json([
                'status' => trans($response)
            ]);
        }
        return back()->with('status', trans($response));
    }
365821
public function send(Request $request)
    {
        $response   = new GetResponse();
        $rpbGetReq  = $this->createRpbMessage($request);
        $rpbGetResp = $this->client->send($rpbGetReq, RiakMessageCodes::GET_REQ, RiakMessageCodes::GET_RESP);

        if ( ! $rpbGetResp instanceof RpbGetResp) {
            return $response;
        }

        if ( ! $rpbGetResp->hasContent()) {
            return $response;
        }

        $response->vClock      = $rpbGetResp->getVclock()->get();
        $response->contentList = $this->createContentList($rpbGetResp->getContentList());

        return $response;
    }
317563
protected function doRequest(RequestInterface $httpRequest)
    {
        $httpRawResponse = $httpRequest->execute();
        $httpStatusCode = $httpRequest->getInfo(CURLINFO_HTTP_CODE);
        $httpRequest->close();

        return $this->buildResponse($httpStatusCode, $httpRawResponse);
    }
724455
protected function sendResetLinkFailedResponse(Request $request, $response)
    {
        if ($request->expectsJson()) {
            return new JsonResponse([
                'message' =>  'The given data was invalid.',
                'errors' => [
                    'email' => trans($response)
                ]
            ], 422);
        }
        return back()->withErrors(
            ['email' => trans($response)]
        );
    }
963744
protected function setDefaultResponseValues(ActionResponseInterface $actionResponse)
    {
        $this->serverRawResponse = $actionResponse->getResponse();
        $this->returnCode        = $this->serverRawResponse->getStatusCode();
        $this->returnMessage     = $this->serverRawResponse->getReasonPhrase();
        $this->requestName       = $actionResponse->getRequestName();
    }
1369548
public function sendRequest(Request $request)
    {

        $result = $this->responseFactory->create();
        $client = $this->httpClientFactory->create();

        $apiData = $request->getApiData();
        $apiUrl = $request->getApiUrl();
        $apiKey = $request->getApiKey();
        $requestMethod = $request->getRequestMethod();

        $requestData = $requestMethod !== "GET" ? json_encode($apiData, JSON_UNESCAPED_SLASHES) : null;

        $client->setUri($apiUrl);

        $client->setConfig(['maxredirects' => 0, 'timeout' => 30]);

        $headers =  [
            'User-Agent'            => 'BoltPay/Magento-'.$this->configHelper->getStoreVersion() . '/' . $this->configHelper->getModuleVersion(),
            'X-Bolt-Plugin-Version' => $this->configHelper->getModuleVersion(),
            'Content-Type'          => 'application/json',
            'Content-Length'        => $requestData ? strlen($requestData) : null,
            'X-Api-Key'             => $apiKey,
            'X-Nonce'               => rand(100000000000, 999999999999)
        ] + (array)$request->getHeaders();

        $request->setHeaders($headers);

        $this->bugsnag->registerCallback(function ($report) use ($request) {
            $report->setMetaData([
                'BOLT API REQUEST' => $request->getData()
            ]);
        });

        $client->setHeaders($headers);

        $responseBody = null;

        try {
            $response     = $client->setRawData($requestData, 'application/json')->request($requestMethod);
            $responseBody = $response->getBody();

            $this->bugsnag->registerCallback(function ($report) use ($response) {
                $report->setMetaData([
                    'BOLT API RESPONSE' => [
                        'headers' => $response->getHeaders(),
                        'body'    => $response->getBody(),
                    ]
                ]);
            });

            $this->bugsnag->registerCallback(function ($report) use ($response) {
                $headers = $response->getHeaders();
                $report->setMetaData([
                    'META DATA' => [
                        'bolt_trace_id' => @$headers[ConfigHelper::BOLT_TRACE_ID_HEADER],
                    ]
                ]);
            });
        } catch (\Exception $e) {
            throw new LocalizedException($this->wrapGatewayError($e->getMessage()));
        }

        if ($request->getStatusOnly() && $response) {
            return $response->getStatus();
        }

        if ($responseBody) {
            $resultFromJSON = json_decode($responseBody);
            $jsonError  = $this->handleJsonParseError();
            if ($jsonError != null) {
                $message = __("JSON Parse Error: " . $jsonError);
                throw new LocalizedException($message);
            }

            if ($this->isResponseError($resultFromJSON)) {
                $message = isset($resultFromJSON->errors[0]->message) ? __($resultFromJSON->errors[0]->message) :  __("Bolt API Error Response");
                throw new LocalizedException($message);
            }

            $result->setResponse($resultFromJSON);
        } else {
            throw new LocalizedException(
                __('Something went wrong in the payment gateway.')
            );
        }
        return $result;
    }
511912
public function onWorkerError(SwServer $server, int $workerId, int $workerPid, int $exitCode)
    {
        $workerType = $server->taskworker ? 'task' : 'worker';

        // {{ log
        $this->get('logger')->info('Worker 进程异常退出', [
            'id' => $workerId,
            'pid' => $workerPid,
            'type' => ucfirst($workerType),
            'exitcode' => $exitCode,
        ]);
        // }}

        unset($workerType);

        $this->callProtocolMethod('onError', $server, $workerId);
    }
1003458
public function listAction(Request $request)
    {
        $query = $this->addOrganizationFilter($request->query->all());

        return new JsonResponse($this->finder->search(
            $this->getClass(),
            $query,
            []
        ));
    }
190735
public function onRequest($swooleRequest, $swooleResponse)
    {
        $this->app->make('events')->dispatch('swoole.request');

        $this->resetOnRequest();
        $sandbox = $this->app->make(Sandbox::class);
        $handleStatic = $this->container->make('config')->get('swoole_http.handle_static_files', true);
        $publicPath = $this->container->make('config')->get('swoole_http.server.public_path', base_path('public'));

        try {
            // handle static file request first
            if ($handleStatic && Request::handleStatic($swooleRequest, $swooleResponse, $publicPath)) {
                return;
            }
            // transform swoole request to illuminate request
            $illuminateRequest = Request::make($swooleRequest)->toIlluminate();

            // set current request to sandbox
            $sandbox->setRequest($illuminateRequest);

            // enable sandbox
            $sandbox->enable();

            // handle request via laravel/lumen's dispatcher
            $illuminateResponse = $sandbox->run($illuminateRequest);

            // send response
            Response::make($illuminateResponse, $swooleResponse)->send();
        } catch (Throwable $e) {
            try {
                $exceptionResponse = $this->app
                    ->make(ExceptionHandler::class)
                    ->render(
                        $illuminateRequest,
                        $this->normalizeException($e)
                    );
                Response::make($exceptionResponse, $swooleResponse)->send();
            } catch (Throwable $e) {
                $this->logServerError($e);
            }
        } finally {
            // disable and recycle sandbox resource
            $sandbox->disable();
        }
    }
238517
public static function createFromRaw(string $rawResponse, string $responseClassName = Response::class): ResponseInterface
    {
        $response = new $responseClassName();

        if (!$response instanceof ResponseInterface) {
            throw new \InvalidArgumentException(sprintf('The given response class name "%s" does not implement the "%s" and cannot be created with this method.', $responseClassName, ResponseInterface::class));
        }

        // see https://tools.ietf.org/html/rfc7230#section-3.5
        $lines = explode(chr(10), $rawResponse);
        $statusLine = array_shift($lines);

        if (substr($statusLine, 0, 5) !== 'HTTP/') {
            throw new \InvalidArgumentException('The given raw HTTP message is not a valid response.', 1335175601);
        }
        list($httpAndVersion, $statusCode, $reasonPhrase) = explode(' ', $statusLine, 3);
        $version = explode('/', $httpAndVersion)[1];
        if (strlen($statusCode) !== 3) {
            // See https://tools.ietf.org/html/rfc7230#section-3.1.2
            throw new \InvalidArgumentException('The given raw HTTP message contains an invalid status code.', 1502981352);
        }
        $response = $response->withStatus((integer)$statusCode, trim($reasonPhrase));
        $response = $response->withProtocolVersion($version);

        $parsingHeader = true;
        $contentLines = [];
        $headers = new Headers();
        foreach ($lines as $line) {
            if ($parsingHeader) {
                if (trim($line) === '') {
                    $parsingHeader = false;
                    continue;
                }
                $headerSeparatorIndex = strpos($line, ':');
                if ($headerSeparatorIndex === false) {
                    throw new \InvalidArgumentException('The given raw HTTP message contains an invalid header.', 1502984804);
                }
                $fieldName = trim(substr($line, 0, $headerSeparatorIndex));
                $fieldValue = trim(substr($line, strlen($fieldName) + 1));
                if (strtoupper(substr($fieldName, 0, 10)) === 'SET-COOKIE') {
                    $cookie = Cookie::createFromRawSetCookieHeader($fieldValue);
                    if ($cookie !== null) {
                        $headers->setCookie($cookie);
                    }
                } else {
                    $headers->set($fieldName, $fieldValue, false);
                }
            } else {
                $contentLines[] = $line;
            }
        }
        if ($parsingHeader === true) {
            throw new \InvalidArgumentException('The given raw HTTP message contains no separating empty line between header and body.', 1502984823);
        }
        $content = implode(chr(10), $contentLines);

        $response->setHeaders($headers);
        $response = $response->withBody(ArgumentsHelper::createContentStreamFromString($content));

        return $response;
    }
882230
public function httpPost(Request $request) : Response
    {
        $response = new Response();
        $response->headers->set('Content-Type', 'application/json');

        $response->setContent(
            $this->sdkEndpoint->index(
                $request->getContent()
            )
        );

        return $response;
    }
841574
private static function getUriFromGlobals(\Swoole\Http\Request $swooleRequest)
    {
        $server = $swooleRequest->server;
        $header = $swooleRequest->header;
        $uri = new Uri();
        $uri = $uri->withScheme(! empty($server['https']) && $server['https'] !== 'off' ? 'https' : 'http');

        $hasPort = false;
        if (isset($server['http_host'])) {
            $hostHeaderParts = explode(':', $server['http_host']);
            $uri = $uri->withHost($hostHeaderParts[0]);
            if (isset($hostHeaderParts[1])) {
                $hasPort = true;
                $uri = $uri->withPort($hostHeaderParts[1]);
            }
        } elseif (isset($server['server_name'])) {
            $uri = $uri->withHost($server['server_name']);
        } elseif (isset($server['server_addr'])) {
            $uri = $uri->withHost($server['server_addr']);
        } elseif (isset($header['host'])) {
            if (\strpos($header['host'], ':')) {
                $hasPort = true;
                list($host, $port) = explode(':', $header['host'], 2);

                if ($port !== '80') {
                    $uri = $uri->withPort($port);
                }
            } else {
                $host = $header['host'];
            }

            $uri = $uri->withHost($host);
        }

        if (! $hasPort && isset($server['server_port'])) {
            $uri = $uri->withPort($server['server_port']);
        }

        $hasQuery = false;
        if (isset($server['request_uri'])) {
            $requestUriParts = explode('?', $server['request_uri']);
            $uri = $uri->withPath($requestUriParts[0]);
            if (isset($requestUriParts[1])) {
                $hasQuery = true;
                $uri = $uri->withQuery($requestUriParts[1]);
            }
        }

        if (! $hasQuery && isset($server['query_string'])) {
            $uri = $uri->withQuery($server['query_string']);
        }

        return $uri;
    }
1171817
public function addCorsHeaders(HTTPRequest $request, HTTPResponse $response)
    {
        $corsConfig = Config::inst()->get(static::class, 'cors');

        // If CORS is disabled don't add the extra headers. Simply return the response untouched.
        if (empty($corsConfig['Enabled'])) {
            return $response;
        }

        // Calculate origin
        $origin = $this->getRequestOrigin($request);

        // Check if valid
        $allowedOrigins = (array)$corsConfig['Allow-Origin'];
        $originAuthorised = $this->validateOrigin($origin, $allowedOrigins);
        if (!$originAuthorised) {
            $this->httpError(403, "Access Forbidden");
        }

        $response->addHeader('Access-Control-Allow-Origin', $origin);
        $response->addHeader('Access-Control-Allow-Headers', $corsConfig['Allow-Headers']);
        $response->addHeader('Access-Control-Allow-Methods', $corsConfig['Allow-Methods']);
        $response->addHeader('Access-Control-Max-Age', $corsConfig['Max-Age']);

        if (isset($corsConfig['Allow-Credentials'])) {
            $response->addHeader('Access-Control-Allow-Credentials', $corsConfig['Allow-Credentials']);
        }

        return $response;
    }
300767
public function sendResponse(WebRequest $request, Response $response, $result)
    {
        $dataType = $request->getHeader('Accept');
        
        switch ($dataType) {
            case 'text/xml':
                $xml = new \SimpleXMLElement('<root/>');
                $this->fillXml($xml, $result);
                
                $result = $xml->asXML();
                if ($result === false) {
                    $result = '';
                }
                
                $response->sendHeader('Content-Type: text/xml');
                $response->setOutput($result);
            break;
            
            case 'application/json':
            default:
                $response->sendHeader('Content-Type: application/json');
                $response->setOutput(json_encode($result));
            break;
        }
    }