连接开始回调

@param $server
@param $request
972182
public function onOpen(\swoole_websocket_server $server, $request) {
        /* @var $service WebSocketService */
        $service = Ioc::get($this->config[ 'service' ]);
        $user_id = $service->tokenToUserId($request->get);
        if (!$user_id) {
            $server->push($request->fd, json_encode(['msg_type' => 'error', 'code' => '10010', 'msg' => '用户信息错误']));
            $server->close($request->fd);
            return;
        } else {

        }
        //将当前用户在其他连接断掉
        $old_fid = $this->userIdToFid($user_id);
        if ($old_fid) {
            $old = explode("@", $old_fid);
            if ($old[ 0 ] == $this->host_name) {
                $server->push($old[ 1 ], json_encode(['msg_type' => 'error',
                                                      'code' => '10011',
                                                      'msg' => '用户已在其他地方登录']));
                $server->close($old[ 1 ]);
            } else {
                try {
                    //通过集群中的其他服务器推送
                    Http::put('http://' . $old[ 0 ] . ':' . $this->config[ 'port' ] . '/open/close', [], ['fid' =>
                                                                                                              $old[ 1 ],
                                                                                                          'secret' => $this->config[ 'secret' ]]);
                } catch (\Exception $exception) {
                } catch (\Error $exception) {
                }
            }
            Cache::redis()->hDel('fid_#_user_id', $old_fid);
        }
        //清除占用连接的老用户
        $old_user = $this->fidToUserId($this->host_name . "@" . $request->fd);
        Cache::redis()->hDel('user_id_#_fid', $old_user);

        //设置新用户
        Cache::redis()->hSet('user_id_#_fid', $user_id, $this->host_name . "@" . $request->fd);
        Cache::redis()->hSet('fid_#_user_id', $this->host_name . "@" . $request->fd, $user_id);
        Cache::release();
        //1s后发送未读消息
        timer_after(1000, function() use ($user_id) {
            $this->sendToUser($user_id, ['msg_type' => 'login_success',
                                         'code' => '10000',
                                         'msg' => '登录成功']);
            /* @var $service WebSocketService */
            $service = Ioc::get($this->config[ 'service' ]);
            $service->onOpen($user_id);
        });
        Context::release();
    }
93745
public function respond(ServerRequest $request)
    {
        try
        {
            $response = $this->request($request)
                ->finalize()
                ->getResponse();
        }
        catch(\Exception $e)
        {
            if($failRoute = $this->failRoute)
            {
                $response = $this->execute($failRoute, array('exception' => $e, 'request' => $request), $request)
                    ->finalize()
                    ->getResponse();

                $this->failRoute = null;
            }
            else if($this->map->hasFailRoute())
            {
                $response = $this->execute($this->map->getFailRoute(), array('exception' => $e, 'request' => $request), $request)
                    ->finalize()
                    ->getResponse();
            }
            else
            {
                $message = '<pre><h2>['.get_class($e).'] '.$e->getMessage().'</h2>'.PHP_EOL;
                $message .= $e->getTraceAsString();

                $response = Response::createEmptyResponse()
                    ->setStatus(404)
                    ->setBody($message);
            }
        }

        return $response;
    }
1136217
public function process(ServerRequestInterface $request, RequestHandlerInterface $handler): ResponseInterface
    {
        // 获取Response对象
        $response = $handler->handle($request);
        // 获取路由结果
        $result = RequestContext::get('routeResult');
        if(null === $result)
        {
            throw new \RuntimeException('RequestContent not found routeResult');
        }
        // 路由匹配结果是否是[控制器对象, 方法名]
        $isObject = is_array($result['callable']) && isset($result['callable'][0]) && $result['callable'][0] instanceof HttpController;
        if($isObject)
        {
            // 复制一份控制器对象
            $result['callable'][0] = clone $result['callable'][0];
            // 传入Request和Response对象
            $result['callable'][0]->request = $request;
            $result['callable'][0]->response = $response;
        }
        // 执行动作
        $actionResult = call_user_func_array($result['callable'], $this->prepareActionParams($request, $result));
        if($isObject)
        {
            // 获得控制器中的Response
            $response = $result['callable'][0]->response;
        }
        // 视图
        if($actionResult instanceof \Imi\Server\View\Annotation\View)
        {
            // 动作返回的值是@View注解
            $viewAnnotation = $actionResult;
        }
        else if($actionResult instanceof Response)
        {
            $response = $actionResult;
        }
        else
        {
            // 获取对应动作的视图注解
            $viewAnnotation = clone ViewParser::getInstance()->getByCallable($result['callable']);
            if(null !== $viewAnnotation)
            {
                if(is_array($actionResult))
                {
                    // 动作返回值是数组，合并到视图注解
                    $viewAnnotation->data = array_merge($viewAnnotation->data, $actionResult);
                }
                else
                {
                    // 非数组直接赋值
                    $viewAnnotation->data = $actionResult;
                }
            }
        }

        if(isset($viewAnnotation))
        {
            // 视图渲染
            $view = RequestContext::getServerBean('View');
            $response = $view->render($viewAnnotation, $response);
        }

        return $response;
    }
125674
function parseRequest($request)
    {
        $url_info = parse_url($request->meta['uri']);
        $request->meta['path'] = $url_info['path'];
        if (isset($url_info['fragment'])) $request->meta['fragment'] = $url_info['fragment'];
        if (isset($url_info['query']))
        {
            parse_str($url_info['query'], $request->get);
        }
        //POST请求,有http body
        if ($request->meta['method'] === 'POST')
        {
            $this->parser->parseBody($request);
        }
        //解析Cookies
        if (!empty($request->header['Cookie']))
        {
            $this->parser->parseCookie($request);
        }
    }
1108249
public function setRequest(Request $request)
    {
        $this->request = $request;
        $this->context->registerInstance($request);
    }
374783
function onHttpRequest(Swoole\Request $request)
    {
        //新连接
        if (empty($request->post['session_id']))
        {
            if (empty($request->post['type']) or $request->post['type'] != 'connect')
            {
                goto access_deny;
            }
            $this->log("Connect [fd={$request->fd}]");
            $session = $this->createNewSession();
            $response = new Swoole\Response;
            $response->setHeader('Access-Control-Allow-Origin', $this->origin);
            $response->body = json_encode(array('success' => 1, 'session_id' => $session->id));
            return $response;
        }

        if (empty($request->post['type']) or empty($request->post['session_id']) or empty($this->sessions[$request->post['session_id']]))
        {
            access_deny:
            $response = new Swoole\Response;
            $response->setHeader('Connection', 'close');
            $response->setHttpStatus(403);
            $response->body = "<h1>Access Deny.</h1>";
            return $response;
        }

        $session_id = $request->post['session_id'];
        $session = $this->getSession($session_id);

        if ($request->post['type'] == 'pub')
        {
            $response = new Swoole\Response;
            $response->setHeader('Access-Control-Allow-Origin', $this->origin);
            $response->body = json_encode(array('success' => 1, ));
            $this->response($request, $response);
            $this->log("Publish [fd={$request->fd}, session=$session_id]");
            $this->onMessage($session_id, $request->post);
        }
        elseif($request->post['type'] == 'sub')
        {
            $this->wait_requests[$session_id] = $request;
            $this->fd_session_map[$request->fd] = $session_id;
            $this->log("Subscribe [fd={$request->fd}, session=$session_id]");
            if ($session->getMessageCount() > 0)
            {
                $this->sendMessage($session);
            }
        }
        else
        {
            $session = $this->createNewSession();
            $response = new Swoole\Response;
            $response->setHeader('Connection', 'close');
            $response->setHttpStatus(404);
            $response->body = "<h1>Channel Not Found</h1>";
            return $response;
        }
    }
266670
protected function doRequest($request)
    {
        $headers = array();
        foreach ($request->getServer() as $key => $val) {
            $key = strtolower(str_replace('_', '-', $key));
            $contentHeaders = array('content-length' => true, 'content-md5' => true, 'content-type' => true);
            if (0 === strpos($key, 'http-')) {
                $headers[substr($key, 5)] = $val;
            }
            // CONTENT_* are not prefixed with HTTP_
            elseif (isset($contentHeaders[$key])) {
                $headers[$key] = $val;
            }
        }

        $cookies = CookieJar::fromArray(
            $this->getCookieJar()->allRawValues($request->getUri()),
            parse_url($request->getUri(), PHP_URL_HOST)
        );

        $requestOptions = array(
            'cookies' => $cookies,
            'allow_redirects' => false,
            'auth' => $this->auth,
        );

        if (!in_array($request->getMethod(), array('GET', 'HEAD'))) {
            if (null !== $content = $request->getContent()) {
                $requestOptions['body'] = $content;
            } else {
                if ($files = $request->getFiles()) {
                    $requestOptions['multipart'] = [];

                    $this->addPostFields($request->getParameters(), $requestOptions['multipart']);
                    $this->addPostFiles($files, $requestOptions['multipart']);
                } else {
                    $requestOptions['form_params'] = $request->getParameters();
                }
            }
        }

        if (!empty($headers)) {
            $requestOptions['headers'] = $headers;
        }

        $method = $request->getMethod();
        $uri = $request->getUri();

        foreach ($this->headers as $name => $value) {
            $requestOptions['headers'][$name] = $value;
        }

        // Let BrowserKit handle redirects
        try {
            $response = $this->getClient()->request($method, $uri, $requestOptions);
        } catch (RequestException $e) {
            $response = $e->getResponse();
            if (null === $response) {
                throw $e;
            }
        }

        return $this->createResponse($response);
    }
789849
public function send($request)
    {
        $this->request = $request;
        $this->handler = curl_init();
        $tempDir = $this->request->getAttribute('tempDir');
        $cookieFileName = tempnam(null === $tempDir ? sys_get_temp_dir() : $tempDir, '');
        $files = $this->request->getUploadedFiles();
        $body = (string)$this->request->getBody();
        if(isset($files[0]))
        {
            $body = FormDataBuilder::build($body, $files, $boundary);
            $this->request = $this->request = $this->request->withHeader('Content-Type', MediaType::MULTIPART_FORM_DATA . '; boundary=' . $boundary);
        }
        $options = [
            // 请求方法
            CURLOPT_CUSTOMREQUEST   => $this->request->getMethod(),
            // 返回内容
            CURLOPT_RETURNTRANSFER  => true,
            // 返回header
            CURLOPT_HEADER          => true,
            // 发送内容
            CURLOPT_POSTFIELDS      => $body,
            // 保存cookie
            CURLOPT_COOKIEFILE      => $cookieFileName,
            CURLOPT_COOKIEJAR       => $cookieFileName,
            // 自动重定向
            CURLOPT_FOLLOWLOCATION  => $this->request->getAttribute('customLocation', false) ? false : $this->request->getAttribute('followLocation', true),
            // 最大重定向次数
            CURLOPT_MAXREDIRS       => $this->request->getAttribute('maxRedirects', 10),
        ];
        // 自动解压缩支持
        $acceptEncoding = $this->request->getHeaderLine('Accept-Encoding');
        if('' !== $acceptEncoding)
        {
            $options[CURLOPT_ENCODING] = $acceptEncoding;
        }
        else
        {
            $options[CURLOPT_ENCODING] = '';
        }
        curl_setopt_array($this->handler, $options);
        $this->parseSSL();
        $this->parseOptions();
        $this->parseProxy();
        $this->parseHeaders();
        $this->parseCookies();
        $this->parseNetwork();
        $count = 0;
        if([] !== ($queryParams = $this->request->getQueryParams()))
        {
            $this->request = $this->request->withUri($this->request->getUri()->withQuery(http_build_query($queryParams, '', '&')));
        }
        $url = (string)$this->request->getUri();
        do{
            curl_setopt($this->handler, CURLOPT_URL, $url);
            $retry = $this->request->getAttribute('retry', 0);
            for($i = 0; $i <= $retry; ++$i)
            {
                $this->curlResult = curl_exec($this->handler);
                $this->getResponse();
                $statusCode = $this->result->getStatusCode();
                // 状态码为5XX或者0才需要重试
                if(!(0 === $statusCode || (5 === (int)($statusCode/100))))
                {
                    break;
                }
            }
            if($this->request->getAttribute('customLocation', false) && (301 === $statusCode || 302 === $statusCode) && ++$count <= $this->request->getAttribute('maxRedirects', 10))
            {
                // 自己实现重定向
                $url = $this->result->getHeaderLine('location');
            }
            else
            {
                break;
            }
        }while(true);
        // 关闭保存至文件的句柄
        if(null !== $this->saveFileFp)
        {
            fclose($this->saveFileFp);
            $this->saveFileFp = null;
        }
    }
1198739
public function execute($request)
    {
        RequestNotSupportedException::assertSupports($this, $request);

        /** @var PaymentInterface $payment */
        $payment = $request->getSource();

        /** @var OrderInterface $order */
        $params = [
            'payment_id' => $payment->getNumber(),
            'payment_amount' => $payment->getTotalAmount(),
            'payment_currency' => $payment->getCurrencyCode(),
            'project_id' => $this->api['projectId'],
            'customer_id' => $payment->getClientId(),
        ];
        $request->setResult($params);
    }
1071971
public function execute($request): void
    {
        RequestNotSupportedException::assertSupports($this, $request);

        $request->setResult([
            Constants::FIELD_PAID => false,
        ]);
    }
654527
public function execute($request): void
    {
        RequestNotSupportedException::assertSupports($this, $request);

        /** @var PaymentInterface $payment */
        $payment = $request->getSource();
        /** @var OrderInterface $order */
        $order = $payment->getOrder();

        $details = [];
        $details['PAYMENTREQUEST_0_INVNUM'] = $this->invoiceNumberGenerator->generate($order, $payment);
        $details['PAYMENTREQUEST_0_CURRENCYCODE'] = $order->getCurrencyCode();
        $details['PAYMENTREQUEST_0_AMT'] = $this->formatPrice($order->getTotal());
        $details['PAYMENTREQUEST_0_ITEMAMT'] = $this->formatPrice($order->getTotal());

        $m = 0;
        foreach ($order->getItems() as $item) {
            $details['L_PAYMENTREQUEST_0_NAME' . $m] = $item->getVariant()->getProduct()->getName();
            $details['L_PAYMENTREQUEST_0_AMT' . $m] = $this->formatPrice($item->getDiscountedUnitPrice());
            $details['L_PAYMENTREQUEST_0_QTY' . $m] = $item->getQuantity();

            ++$m;
        }

        if (0 !== $taxTotal = $order->getAdjustmentsTotalRecursively(AdjustmentInterface::TAX_ADJUSTMENT)) {
            $details['L_PAYMENTREQUEST_0_NAME' . $m] = 'Tax Total';
            $details['L_PAYMENTREQUEST_0_AMT' . $m] = $this->formatPrice($taxTotal);
            $details['L_PAYMENTREQUEST_0_QTY' . $m] = 1;

            ++$m;
        }

        if (0 !== $promotionTotal = $order->getOrderPromotionTotal()) {
            $details['L_PAYMENTREQUEST_0_NAME' . $m] = 'Discount';
            $details['L_PAYMENTREQUEST_0_AMT' . $m] = $this->formatPrice($promotionTotal);
            $details['L_PAYMENTREQUEST_0_QTY' . $m] = 1;

            ++$m;
        }

        if (0 !== $shippingTotal = $order->getShippingTotal()) {
            $details['L_PAYMENTREQUEST_0_NAME' . $m] = 'Shipping Total';
            $details['L_PAYMENTREQUEST_0_AMT' . $m] = $this->formatPrice($shippingTotal);
            $details['L_PAYMENTREQUEST_0_QTY' . $m] = 1;
        }

        $request->setResult($details);
    }
998848
public function setRequestOnHandler($request)
    {
        if ($this->handlerNeedsRequest()) {
            /** @var NeedRequestInterface $handler */
            $handler = $this->getHandler();
            $handler->setRequest($request);
        }
    }
813246
protected function validate(Request $request)
    {
        $validator = $this->resolveValidator($request);

        if ($validator) {
            $validator->validate($request);
        }
    }
123193
public function setServer($server)
    {
        if (is_a($server,'Cetera\\Server')) {
            $this->_server = $server;
            return $this;
        }
        if (is_int($server)) {
            $this->_server = Server::getById($server);
            return $this;        
        }
    }
1056760
public function parse(Request $request)
    {
        if ($request->has($this->name)) {
            $this->applied = true;
            $value         = $request->input($this->name);
            $operation     = substr($value, 0, 1);
            if ($operation === '!') {
                $this->operation = '!=';
                $this->value     = substr($value, 1);
            } else {
                $this->value = $value;
            }
        }
    }
339796
public function setRequest(Request $request)
    {
        $this->request = $request;

        $this->input = $request->request->all() + $request->query->all();
    }
802583
public function indexAction(Request $request)
    {
        $query = $request->query->get('query');
        $limit = $request->query->get('limit');
        $start = $request->query->get('start');

        $searchProviders = $this->get('search.providers');

        $content = '';
        $content .= '<h3>Registered Search Providers:</h3><table><tr><th>Class</th><th>Resource</th><th>Search key</th></tr>';
        foreach ($searchProviders as $searchProvider) {
            $content .= '<tr>';
            $content .= '<td>'.get_class($searchProvider).'</td>';
            $content .= '<td>'.$searchProvider->getResource().'</td>';
            $content .= '<td>'.$searchProvider->getSearchKey().'</td>';
            $content .= '</tr>';
        }
        $content .= '</table>';

        $content .= '<h3>Search:</h3>';
        $content .= '<form><input name="query" value="'.$query.'"/><input type="submit" value="send" /></form>';

        if ($query) {
            $content .= '<h3>Results:</h3>';
            $search = $this->getContainer()->get('search.search');
            $results = $search->search($query);
            $content .= '<pre>';
            $content .= print_r($results, true);
            $content .= '</pre>';
        }

        return new Response($content);
    }