Files
kiri-core/http-server/Service/Http.php
T
as2252258@163.com 5e32d9a020 111
2021-08-28 02:14:11 +08:00

103 lines
2.7 KiB
PHP

<?php
namespace Server\Service;
use Exception;
use Http\Exception\RequestException;
use Http\Route\Node;
use Kiri\ToArray;
use Server\Events\OnAfterRequest;
use Server\Message\Stream;
use Server\ResponseInterface;
use Server\SInterface\OnClose;
use Server\SInterface\OnConnect;
use Swoole\Error;
use Swoole\Http\Request;
use Swoole\Http\Response;
use Swoole\Server;
/**
*
*/
class Http extends \Server\Abstracts\Http implements OnClose, OnConnect
{
/**
* @param Server $server
* @param int $fd
*/
public function onConnect(Server $server, int $fd): void
{
// TODO: Implement onConnect() method.
}
/**
* @param Request $request
* @param Response $response
*/
public function onRequest(Request $request, Response $response): void
{
// TODO: Implement onRequest() method.
try {
$node = $this->router->Branch_search(\Server\Constrict\Request::create($request));
if (!($node instanceof Node)) {
throw new RequestException('<h2>HTTP 404 Not Found</h2><hr><i>Powered by Swoole</i>', 404);
}
if (!(($responseData = $node->dispatch()) instanceof ResponseInterface)) {
$responseData = $this->transferToResponse($responseData);
}
} catch (Error | \Throwable $exception) {
$responseData = $this->exceptionHandler->emit($exception, $this->response);
} finally {
$this->responseEmitter->sender($response, $responseData);
$this->eventDispatch->dispatch(new OnAfterRequest());
}
}
/**
* @param $responseData
* @return \Server\ResponseInterface
*/
private function transferToResponse($responseData): ResponseInterface
{
$this->response->withStatus(200);
if (is_object($responseData)) {
if (!($responseData instanceof ToArray)) {
$responseData = get_object_vars($responseData);
} else {
$responseData = $responseData->toArray();
}
}
if (is_array($responseData)) {
return $this->response->withBody(new Stream(json_encode($responseData, JSON_UNESCAPED_UNICODE)))
->withContentType(\Server\Message\Response::CONTENT_TYPE_JSON);
}
return $this->response->withBody(new Stream((string)$responseData));
}
/**
* @param Server $server
* @param int $fd
* @throws Exception
*/
public function onDisconnect(Server $server, int $fd): void
{
}
/**
* @param Server $server
* @param int $fd
* @throws Exception
*/
public function onClose(Server $server, int $fd): void
{
}
}