<?php<liu21st@gmail.com>
namespace think\swoole;
use Swoole\Http\Request;
use Swoole\Http\Response;
use think\App;
use think\Error;
use think\exception\HttpException;
class Application extends App
{
public function swoole(Request $request, Response $response)
{
try {
ob_start();
$this->beginTime = microtime(true);
$this->beginMem = memory_get_usage();
$this->delete('think\Request');
$this->cookie->setResponse($response);
$_COOKIE = $request->cookie ?: [];
$_GET = $request->get ?: [];
$_POST = $request->post ?: [];
$_FILES = $request->files ?: [];
$_SERVER = array_change_key_case($request->server, CASE_UPPER);
$this->request->withHeader($request->header)
->withServer($_SERVER)
->withGet($_GET)
->withPost($_POST)
->withCookie($_COOKIE)
->withInput($request->rawContent())
->withFiles($_FILES)
->setBaseUrl($request->server['request_uri'])
->setUrl($request->server['request_uri'] . (!empty($request->server['query_string']) ? '&' . $request->server['query_string'] : ''))
->setHost($request->header['host'])
->setPathinfo(ltrim($request->server['path_info'], '/'));
$this->route->setRequest($this->request);
$resp = $this->run();
$resp->send();
$content = ob_get_clean();
$status = $resp->getCode();
if ($this->env->get('app_trace', $this->config->get('app_trace'))) {
$this->debug->inject($resp, $content);
}
$response->status($status);
foreach ($resp->getHeader() as $key => $val) {
$response->header($key, $val);
}
$response->end($content);
} catch (HttpException $e) {
$this->exception($response, $e);
} catch (\Exception $e) {
$this->exception($response, $e);
} catch (\Throwable $e) {
$this->exception($response, $e);
}
}
protected function exception($response, $e)
{
if ($e instanceof \Exception) {
$handler = Error::getExceptionHandler();
$handler->report($e);
$resp = $handler->render($e);
$content = $resp->getContent();
$code = $resp->getCode();
$response->status($code);
$response->end($content);
} else {
$response->status(500);
$response->end($e->getMessage());
}
throw $e;
}
}