private function handleRequest(React\Http\Request $request, React\Http\Response $response)
 {
     try {
         $container = $this->containerFactory->createContainer();
         /** @var HttpRequestFactory $requestFactory */
         $requestFactory = $container->getByType(HttpRequestFactory::class);
         $requestFactory->setFakeHttpRequest($this->createNetteHttpRequest($request));
         /** @var CliRouter $router */
         $cliRouter = $container->getService('console.router');
         $cliRouter->setIsCli(FALSE);
         /** @var Nette\Application\Application $application */
         $application = $container->getByType(Nette\Application\Application::class);
         array_unshift($application->onError, function () {
             throw new AbortException();
         });
         ob_start();
         $application->run();
         $responseBody = ob_get_contents();
         ob_end_clean();
         $response->writeHead(200, array('Content-Type' => 'text/html; charset=utf-8'));
         $response->end($responseBody);
     } catch (\Exception $e) {
         Debugger::log($e, Debugger::EXCEPTION);
         $response->writeHead(500, array('Content-Type' => 'text/plain'));
         $response->end('Internal Server Error');
     }
 }
示例#2
0
 public function send(Response $response)
 {
     if ($response->isWritable()) {
         $response->writeHead(200, ['Content-type' => $this->content_type]);
         $this->stream->pipe($response);
     }
 }
示例#3
0
 public function __invoke(Request $request, Response $response)
 {
     $sfRequest = SymfonyRequest::create($request->getPath(), $request->getMethod());
     $sfResponse = $this->handle($sfRequest, HttpKernelInterface::MASTER_REQUEST, true);
     $response->writeHead($sfResponse->getStatusCode(), ['Content-Type' => 'text/html']);
     $response->end($sfResponse->getContent());
 }
示例#4
0
 /**
  * It performs the setup of a reactPHP response from a SlimpPHP response
  * object and finishes the communication
  *
  * @param \React\Http\Response $reactResp    ReactPHP native response object
  * @param boolean              $endRequest   If true, response flush will be finished
  *
  * @return void
  */
 public function setReactResponse(\React\Http\Response $reactResp, $endRequest = false)
 {
     $reactResp->writeHead($this->getStatusCode(), $this->getHeaders());
     $reactResp->write($this->getBody());
     if ($endRequest === true) {
         $reactResp->end();
     }
 }
示例#5
0
 /** @test */
 public function writeContinueShouldSendContinueLineBeforeRealHeaders()
 {
     $conn = $this->getMock('React\\Socket\\ConnectionInterface');
     $conn->expects($this->at(3))->method('write')->with("HTTP/1.1 100 Continue\r\n");
     $conn->expects($this->at(4))->method('write')->with($this->stringContains("HTTP/1.1 200 OK\r\n"));
     $response = new Response($conn);
     $response->writeContinue();
     $response->writeHead();
 }
示例#6
0
 /**
  * It performs the setup of a reactPHP response from a SlimpPHP response
  * object and finishes the communication
  *
  * @param \React\Http\Response $reactResp    ReactPHP native response object
  * @param \Slim\Http\Response  $slimResponse SlimPHP native response object
  * @param boolean              $endRequest   If true, response flush will be finished
  *
  * @return void
  */
 static function setReactResponse(\React\Http\Response $reactResp, \Slim\Http\Response $slimResponse, $endRequest = false)
 {
     $headers = static::reduceHeaders($slimResponse->getHeaders());
     $reactResp->writeHead($slimResponse->getStatusCode(), $headers);
     $reactResp->write($slimResponse->getBody());
     if ($endRequest === true) {
         $reactResp->end();
     }
 }
 protected function handleSse(Request $request, Response $response)
 {
     $headers = $request->getHeaders();
     $id = isset($headers['Last-Event-ID']) ? $headers['Last-Event-ID'] : null;
     $response->writeHead(200, array('Content-Type' => 'text/event-stream'));
     $this->channel->connect($response, $id);
     $response->on('close', function () use($response) {
         $this->channel->disconnect($response);
     });
 }
示例#8
0
 public function handleRequest(ConnectionInterface $conn, Request $request, $bodyBuffer)
 {
     $response = new Response($conn);
     $response->on('close', array($request, 'close'));
     if (!$this->listeners('request')) {
         $response->end();
         return;
     }
     $this->emit('request', array($request, $response));
     $request->emit('data', array($bodyBuffer));
 }
示例#9
0
 public function handleRequest(React\Http\Request $req, React\Http\Response $res)
 {
     $request = Request::create($req->getPath(), $req->getMethod(), $req->getQuery());
     $response = $this->httpKernel->handle($request);
     $headers = array();
     foreach ($response->headers as $k => $v) {
         $headers[$k] = $v[0];
     }
     $res->writeHead($response->getStatusCode(), $headers);
     $res->end($response->getContent());
 }
示例#10
0
 /**
  * @param Psr7Response
  * @param ReactResponse
  * @return void
  */
 private function emit(Psr7Response $psr7Response, ReactResponse $reactResponse)
 {
     if (!$psr7Response->hasHeader('Content-Type')) {
         $psr7Response = $psr7Response->withHeader('Content-Type', 'text/html');
     }
     $reactResponse->writeHead($psr7Response->getStatusCode(), $psr7Response->getHeaders());
     $body = $psr7Response->getBody();
     $body->rewind();
     $reactResponse->end($body->getContents());
     $body->close();
 }
示例#11
0
 /**
  * @param Response $response
  * @param $sfResponse
  * @throws \Exception
  */
 private function parseSfResponse(Response $response, SymfonyResponse $sfResponse)
 {
     $headers = array_map('current', $sfResponse->headers->allPreserveCase());
     $cookies = array();
     if (session_status() === PHP_SESSION_ACTIVE && !array_key_exists('PHPSESSID', $_COOKIE)) {
         $cookies['PHPSESSID'] = session_id();
     }
     if (count($cookies) > 0) {
         $headers['Set-Cookie'] = $this->serializeCookiesHeader($cookies);
     }
     $response->writeHead($sfResponse->getStatusCode(), $headers);
 }
示例#12
0
 /**
  * Serve the request linked to this ProxyApplication
  *
  * The serve method is used only by Reactavel,
  * It's added to the Application because the methods it needs are protected.
  *
  * @param SymfonyRequest $request
  * @param Response $response
  * @throws \Exception
  */
 public function serve(SymfonyRequest $request, Response $response)
 {
     $innerResponse = $this->dispatch($request);
     if (!$innerResponse instanceof SymfonyResponse) {
         $innerResponse = new SymfonyResponse((string) $innerResponse);
     }
     $response->writeHead($innerResponse->getStatusCode(), $innerResponse->headers->all());
     $response->end($innerResponse->getContent());
     if (count($this->middleware) > 0) {
         $this->callTerminableMiddleware($innerResponse);
     }
 }
示例#13
0
 private function handle(React\Http\Request $request, React\Http\Response $response, $requestHandler)
 {
     $sfRequest = Request::create($request->getPath(), $request->getMethod(), $request->getQuery());
     $output = call_user_func_array($requestHandler, [$sfRequest]);
     if ($output instanceof Response) {
         $response->writeHead($output->getStatusCode(), $output->headers->all());
         $response->end($output->getContent());
     } else {
         $response->writeHead(200, array('Content-Type' => 'text/plain'));
         $response->end($output);
     }
 }
示例#14
0
 public function handleRequest(Request $request, Response $response)
 {
     try {
         $expectedRequest = $this->getExpectedRequest();
         if (true === $this->validateRequest($expectedRequest, $request)) {
             $response->writeHead($expectedRequest->getResponseOption('status'), array('Content-Type' => 'text/html'));
             $response->end('Stubber Basic Application');
         }
     } catch (PrimerException $e) {
         $response->writeHead(418, array('Content-Type' => 'text/html'));
         $response->end('Stubber not primed for this request');
     }
 }
示例#15
0
 /**
  * Sends content for the current web response.
  *
  * @param ReactResponse   $response
  * @param SymfonyResponse $sf_response
  */
 private function sendContent(ReactResponse $response, SymfonyResponse $sf_response)
 {
     if ($sf_response instanceof StreamedResponse || $sf_response instanceof BinaryFileResponse) {
         ob_start(function ($buffer) use($response) {
             $response->write($buffer);
         });
         $sf_response->sendContent();
         ob_get_clean();
         $response->end();
     } else {
         $response->end($sf_response->getContent());
     }
 }
示例#16
0
 private function handlePublishHttpPost(Request $request, Response $response)
 {
     $bodySnatcher = new BodySnatcher($request);
     $bodySnatcher->promise()->then(function ($body) use($request, $response) {
         try {
             //{"topic": "com.myapp.topic1", "args": ["Hello, world"]}
             $json = json_decode($body);
             if ($json === null) {
                 throw new \Exception("JSON decoding failed: " . json_last_error_msg());
             }
             if (isset($json->topic) && is_scalar($json->topic) && isset($json->args) && is_array($json->args) && $this->getPublisher() !== null) {
                 $json->topic = strtolower($json->topic);
                 if (!Utils::uriIsValid($json->topic)) {
                     throw new \Exception("Invalid URI: " . $json->topic);
                 }
                 $argsKw = isset($json->argsKw) && is_object($json->argsKw) ? $json->argsKw : null;
                 $options = isset($json->options) && is_object($json->options) ? $json->options : null;
                 $this->getSession()->publish($json->topic, $json->args, $argsKw, $options);
             } else {
                 throw new \Exception("Invalid request: " . json_encode($json));
             }
         } catch (\Exception $e) {
             // should shut down everything
             $response->writeHead(400, ['Content-Type' => 'text/plain', 'Connection' => 'close']);
             $response->end("Bad Request: " . $e->getMessage());
             return;
         }
         $response->writeHead(200, ['Content-Type' => 'text/plain', 'Connection' => 'close']);
         $response->end("pub");
     });
 }
示例#17
0
文件: Server.php 项目: tritumRz/rest
 /**
  * Handles the requests
  *
  * @param \React\Http\Request $request Request to handle
  * @param \React\Http\Response $response Prebuilt response object
  */
 public function serverCallback($request, $response)
 {
     // Currently the PHP server is readonly
     if (!in_array(strtoupper($request->getMethod()), array('GET', 'HEAD'))) {
         $response->writeHead(405, array('Content-type' => 'text/plain'));
         $response->end('Writing is currently not supported');
         return;
     }
     $requestPath = $this->sanitizePath($request->getPath());
     $requestPath = substr($requestPath, 5);
     /** @var Request $restRequest */
     $restRequest = new Request($request->getMethod(), $requestPath, $request->getQuery(), $request->getHeaders());
     $path = '' . strtok($requestPath, '/');
     $restRequest->initWithPathAndOriginalPath($path, $path);
     $this->setServerGlobals($request);
     /** @var \Bullet\Response $restResponse */
     $restResponse = NULL;
     ob_start();
     $this->dispatcher->dispatch($restRequest, $restResponse);
     $responseString = ob_get_clean();
     if (!$restResponse) {
         $response->writeHead(200);
         $response->end($responseString);
     } else {
         $response->writeHead($restResponse->status(), $this->getHeadersFromResponse($restResponse));
         $response->end($restResponse->content());
     }
     unset($restRequest);
     unset($restResponse);
 }
示例#18
0
 private function handlePublishHttpPost(Request $request, Response $response)
 {
     $bodySnatcher = new BodySnatcher($request);
     $bodySnatcher->promise()->then(function ($body) use($request, $response) {
         try {
             //{"topic": "com.myapp.topic1", "args": ["Hello, world"]}
             $json = json_decode($body);
             if ($json === null) {
                 $response->writeHead(400, ['Content-Type' => 'text/plain', 'Connection' => 'close']);
                 $response->end("JSON decoding failed: " . json_last_error_msg());
                 return;
             }
             if (isset($json->topic) && isset($json->args) && Utils::uriIsValid($json->topic) && is_array($json->args) && $this->getPublisher() !== null) {
                 $argsKw = isset($json->argsKw) && is_object($json->argsKw) ? $json->argsKw : null;
                 $options = isset($json->options) && is_object($json->options) ? $json->options : null;
                 $this->getSession()->publish($json->topic, $json->args, $argsKw, $options);
             } else {
                 $errors = [];
                 if (!isset($json->topic)) {
                     $errors[] = 'Topic not set';
                 }
                 if (!isset($json->args)) {
                     $errors[] = 'Args not set';
                 }
                 if (!is_array($json->args)) {
                     $errors[] = 'Args is not an array, got ' . gettype($json->args);
                 }
                 if (!Utils::uriIsValid($json->topic)) {
                     $errors[] = 'Topic is not a valid URI';
                 }
                 if (!($this->getPublisher() !== null)) {
                     $errors[] = 'Publisher is not set';
                 }
                 $response->writeHead(400, ['Content-Type' => 'text/plain', 'Connection' => 'close']);
                 $response->end("The following errors occurred:" . PHP_EOL . PHP_EOL . implode(PHP_EOL, $errors));
                 return;
             }
         } catch (\Exception $e) {
             // should shut down everything
             $response->writeHead(400, ['Content-Type' => 'text/plain', 'Connection' => 'close']);
             $response->end("Bad Request: " . $e->getMessage());
             return;
         }
         $response->writeHead(200, ['Content-Type' => 'text/plain', 'Connection' => 'close']);
         $response->end("pub");
     });
 }
 /**
  * @param ResponseInterface $response
  * @param ReactResponse     $reactResponse
  */
 public function reverseTransform(ResponseInterface $response, ReactResponse $reactResponse)
 {
     $body = $response->getBody();
     $body->rewind();
     $headers = array();
     foreach (array_keys($response->getHeaders()) as $name) {
         $headers[$name] = $response->getHeaderLine($name);
     }
     if (!isset($headers['Content-Length']) && $body->getSize() > 0) {
         $headers['Content-Length'] = $body->getSize();
     }
     $reactResponse->writeHead($response->getStatusCode(), $headers);
     while (false === $body->eof()) {
         $reactResponse->write($body->read($this->responseBuffer));
     }
     $reactResponse->end();
 }
示例#20
0
 /**
  * End response
  *
  * @return mixed
  */
 public function end()
 {
     if (!$this->contentSend) {
         $this->dispatchHeaders();
         $this->contentSend = true;
     }
     $this->reactResponse->end();
 }
示例#21
0
 protected function onRequest(Request $request, Response $response)
 {
     $this->resolver->request = $request;
     $this->resolver->response = $response;
     $responseStatus = 200;
     $responseData = null;
     try {
         $responseData = $this->dispatcher->dispatch($request->getMethod(), $request->getPath());
     } catch (HttpRouteNotFoundException $e) {
         $responseStatus = 404;
         $responseData = 'Page not found. Try harder';
     } catch (HttpMethodNotAllowedException $e) {
         $responseStatus = 405;
         $responseData = 'Method not allowed. Use force';
     }
     $response->writeHead($responseStatus);
     $response->end($responseData);
 }
示例#22
0
 public function handle(Request $request, Response $response)
 {
     $headers = array_change_key_case($request->getHeaders(), CASE_LOWER);
     // Only enable when the X-Blackfire-Query header is present
     if (!isset($headers['x-blackfire-query'])) {
         return array();
     }
     $probe = new \BlackfireProbe($headers['x-blackfire-query']);
     // Stop if it failed
     if (!$probe->enable()) {
         return array();
     }
     // Stop profiling once the request ends
     $response->on('end', array($probe, 'close'));
     // Return the header
     $header = explode(':', $probe->getResponseLine(), 2);
     return array('x-' . $header[0] => $header[1]);
 }
示例#23
0
文件: Server.php 项目: pkerling/rest
 /**
  * Handles the requests
  *
  * @param \React\Http\Request $request   Request to handle
  * @param \React\Http\Response $response Prebuilt response object
  */
 public function serverCallback($request, $response)
 {
     // Currently the PHP server is readonly
     if (!in_array(strtoupper($request->getMethod()), array('GET', 'HEAD'))) {
         $response->writeHead(405, array('Content-type' => 'text/plain'));
         $response->end('Writing is currently not supported');
         return;
     }
     /** @var \Cundd\Rest\Request $restRequest */
     $restRequest = new \Cundd\Rest\Request($request->getMethod(), $this->sanitizePath($request->getPath()));
     $this->setServerGlobals($request);
     /** @var \Bullet\Response $restResponse */
     $restResponse = NULL;
     ob_start();
     $this->app->dispatch($restRequest, $restResponse);
     ob_end_clean();
     $response->writeHead($restResponse->status(), $this->getHeadersFromResponse($restResponse));
     $response->end($restResponse->content());
     unset($restRequest);
     unset($restResponse);
 }
示例#24
0
 private function send(Response $res, SymfonyResponse $symfonyResponse)
 {
     $headers = $symfonyResponse->headers->allPreserveCase();
     $headers["X-Powered-By"] = "Love";
     $cookies = $symfonyResponse->headers->getCookies();
     if (count($cookies)) {
         $headers["Set-Cookie"] = [];
         foreach ($symfonyResponse->headers->getCookies() as $cookie) {
             $headers["Set-Cookie"][] = (string) $cookie;
         }
     }
     $res->writeHead($symfonyResponse->getStatusCode(), $headers);
     $res->end($symfonyResponse->getContent());
 }
示例#25
0
 /**
  * main push request/ websocket response loop
  */
 function onRequest(Request $request, Response $response)
 {
     $content = '';
     $headers = $request->getHeaders();
     $contentLength = isset($headers['Content-Length']) ? (int) $headers['Content-Length'] : null;
     // length required, chunked encoding not supported
     if (null === $contentLength) {
         $response->writeHead(411);
         $response->end();
         return;
     }
     $request->on('data', function ($data) use($request, $response, &$content, $contentLength) {
         // read data (may be empty for GET request)
         $content .= $data;
         // handle request after receive
         if (strlen($content) >= $contentLength) {
             $headers = array('Content-Type' => 'application/json');
             try {
                 $data = $this->hub->handlePushMessage($content);
                 $headers['Content-Length'] = strlen($data);
                 if (null === $data) {
                     $response->writeHead(400, $headers);
                     $response->end();
                 } else {
                     $response->writeHead(200, $headers);
                     $response->end($data);
                 }
             } catch (\Exception $exception) {
                 $data = $this->getExceptionAsJson($exception, true);
                 $headers['Content-Length'] = strlen($data);
                 $response->writeHead(500, $headers);
                 // internal server error
                 $response->end($data);
             }
         }
     });
 }
示例#26
0
 /**
  * Send all headers to the response
  */
 public function sendHeaders()
 {
     if ($this->headersSent) {
         return;
     }
     if (!isset($this->headers["Content-Length"])) {
         $this->addHeader("Content-Length", $this->contentLength);
         if (null !== $this->server) {
             $this->addHeader("Server", $this->server);
         }
         if (null !== $this->version) {
             $this->addHeader("Server-Version", $this->version);
         }
         if (!isset($this->headers["Content-Type"])) {
             $this->addHeader("Content-Type", "text/plain");
         }
     }
     $this->httpResponse->writeHead($this->status, $this->headers);
     $this->headersSent = true;
 }
示例#27
0
 public function app(Request $request, Response $response)
 {
     $response->writeHead(200, ['Content-Type' => 'text/plain', 'Access-Control-Allow-Origin' => '*']);
     $body = implode(',', $this->stat['memory']);
     $response->end($body);
 }
示例#28
0
 public function send(Response $response)
 {
     $response->writeHead(204);
     $response->end();
 }
示例#29
0
 /**
  * Manages a request, made to the Http server.
  *
  * @param \React\Http\Request $request
  * @param \React\Http\Response $response
  */
 public function manageRequest($request, $response)
 {
     $requestData = [$request->getHeaders()['Host'] . $request->getPath(), $request->getMethod(), array_merge($request->getQuery(), $request->getPost()), [], $request->getFiles(), []];
     $contentType = isset($request->getHeaders()['Content-Type']) ? $request->getHeaders()['Content-Type'] : 'application/x-www-form-urlencoded';
     if (strtolower($contentType) == 'application/x-www-form-urlencoded') {
         $requestData[] = http_build_query($request->getPost());
     } else {
         $requestData[] = $request->getBody();
     }
     //Creates the Symfony Request from the React Request.
     $sRequest = Request::create(...$requestData);
     /** @var Response $sResponse */
     $sResponse = $this->kernel->handle($sRequest);
     $response->writeHead($sResponse->getStatusCode());
     $response->end($sResponse->getContent());
 }
示例#30
0
 /**
  * Handle request.
  *
  * @param Request  $request
  * @param string   $requestBody
  * @param Response $response
  */
 public function handle(Request $request, $requestBody, Response $response)
 {
     $status = 200;
     $responseBody = '{}';
     try {
         if ($request->getMethod() !== 'POST') {
             throw new HttpException(405);
         }
         if (!array_key_exists($request->getPath(), $this->actions)) {
             throw new HttpException(404);
         }
         $this->logger->info('Request: ' . $request->getPath());
         $responseBody = $this->actions[$request->getPath()]->handleRequest($requestBody, $this->phpcmplr);
     } catch (HttpException $e) {
         $this->logger->notice($e->getMessage(), ['exception' => $e]);
         $status = $e->getStatus();
         $responseBody = json_encode(['error' => $e->getStatus(), 'message' => ResponseCodes::$statusTexts[$e->getStatus()]]);
     } catch (\Exception $e) {
         $this->logger->error($e->getMessage(), ['exception' => $e]);
         $status = 500;
         $responseBody = json_encode(['error' => 500, 'message' => ResponseCodes::$statusTexts[500] . ': ' . $e->getMessage()]);
     } catch (\Error $e) {
         // PHP7
         $this->logger->error($e->getMessage(), ['exception' => $e]);
         $status = 500;
         $responseBody = json_encode(['error' => 500, 'message' => ResponseCodes::$statusTexts[500] . ': ' . $e->getMessage()]);
     }
     $response->writeHead($status, ['Content-Type' => 'application/json', 'Content-Length' => strlen($responseBody)]);
     $response->end($responseBody);
 }