This commit is contained in:
as2252258@163.com
2021-07-03 13:05:17 +08:00
parent 1f7403b8c0
commit 2036d4ebd9
+295 -291
View File
@@ -20,6 +20,7 @@ use Snowflake\Core\Json;
use Snowflake\Snowflake; use Snowflake\Snowflake;
use Swoole\Http\Response as SResponse; use Swoole\Http\Response as SResponse;
use Swoole\Http2\Response as S2Response; use Swoole\Http2\Response as S2Response;
use Swoole\WebSocket\Server;
/** /**
* Class Response * Class Response
@@ -28,341 +29,344 @@ use Swoole\Http2\Response as S2Response;
class Response extends HttpService class Response extends HttpService
{ {
const JSON = 'json'; const JSON = 'json';
const XML = 'xml'; const XML = 'xml';
const HTML = 'html'; const HTML = 'html';
/** @var ?string */ /** @var ?string */
public ?string $format = null; public ?string $format = null;
/** @var int */ /** @var int */
public int $statusCode = 200; public int $statusCode = 200;
public ?SResponse $response = null; public ?SResponse $response = null;
public bool $isWebSocket = false; public bool $isWebSocket = false;
public array $headers = []; public array $headers = [];
private float $startTime = 0; private float $startTime = 0;
private array $_format_maps = [ private array $_format_maps = [
self::JSON => JsonFormatter::class, self::JSON => JsonFormatter::class,
self::XML => XmlFormatter::class, self::XML => XmlFormatter::class,
self::HTML => HtmlFormatter::class self::HTML => HtmlFormatter::class
]; ];
public int $fd = 0; public int $fd = 0;
/** /**
* @param $format * @param $format
* @return $this * @return $this
*/ */
public function setFormat($format): static public function setFormat($format): static
{ {
$this->format = $format; $this->format = $format;
return $this; return $this;
} }
/** /**
* 清理无用数据 * 清理无用数据
*/ */
public function clear(): void public function clear(): void
{ {
$this->fd = 0; $this->fd = 0;
$this->isWebSocket = false; $this->isWebSocket = false;
$this->format = null; $this->format = null;
} }
/** /**
* @return string * @return string
*/ */
public function getContentType(): string public function getContentType(): string
{ {
if ($this->format == null || $this->format == static::JSON) { if ($this->format == null || $this->format == static::JSON) {
return 'application/json;charset=utf-8'; return 'application/json;charset=utf-8';
} else if ($this->format == static::XML) { } else if ($this->format == static::XML) {
return 'application/xml;charset=utf-8'; return 'application/xml;charset=utf-8';
} else { } else {
return 'text/html;charset=utf-8'; return 'text/html;charset=utf-8';
} }
} }
/** /**
* @param $content * @param $content
* @return mixed * @return mixed
*/ */
public function toHtml($content): mixed public function toHtml($content): mixed
{ {
$this->format = self::HTML; $this->format = self::HTML;
return $content; return $content;
} }
/** /**
* @param $content * @param $content
* @return mixed * @return mixed
*/ */
public function toJson($content): mixed public function toJson($content): mixed
{ {
$this->format = self::JSON; $this->format = self::JSON;
return $content; return $content;
} }
/** /**
* @param $content * @param $content
* @return mixed * @return mixed
*/ */
public function toXml($content): mixed public function toXml($content): mixed
{ {
$this->format = self::XML; $this->format = self::XML;
return $content; return $content;
} }
/** /**
* @return mixed * @return mixed
* @throws Exception * @throws Exception
*/ */
public function sender(): mixed public function sender(): mixed
{ {
return $this->send(func_get_args()); return $this->send(func_get_args());
} }
/** /**
* @param $key * @param $key
* @param $value * @param $value
* @return Response * @return Response
*/ */
public function addHeader($key, $value): static public function addHeader($key, $value): static
{ {
$this->headers[$key] = $value; $this->headers[$key] = $value;
return $this; return $this;
} }
/** /**
* @return bool * @return bool
*/ */
private function isClient(): bool private function isClient(): bool
{ {
return !($this->response instanceof SResponse) && !($this->response instanceof S2Response); return !($this->response instanceof SResponse) && !($this->response instanceof S2Response);
} }
/** /**
* @param string $context * @param string $context
* @param int $statusCode * @param int $statusCode
* @return bool * @return bool
* @throws Exception * @throws Exception
*/ */
public function send(string $context = '', int $statusCode = 200): mixed public function send(string $context = '', int $statusCode = 200): mixed
{ {
$sendData = $this->parseData($context); $sendData = $this->parseData($context);
$response = Context::getContext('response'); $response = Context::getContext('response');
if ($response instanceof SResponse) { if ($response instanceof SResponse) {
$this->sendData($response, $sendData, $statusCode); $this->sendData($response, $sendData, $statusCode);
} else { } else {
if (!empty(request()->fd)) { if (!empty(request()->fd)) {
return ''; return '';
} }
$this->printResult($sendData); $this->printResult($sendData);
} }
return $sendData; return $sendData;
} }
/** /**
* @param $context * @param $context
* @return mixed * @return mixed
* @throws Exception * @throws Exception
*/ */
private function parseData($context): mixed private function parseData($context): mixed
{ {
if (empty($context)) { if (empty($context)) {
return $context; return $context;
} }
if (isset($this->_format_maps[$this->format])) { if (isset($this->_format_maps[$this->format])) {
$class['class'] = $this->_format_maps[$this->format]; $class['class'] = $this->_format_maps[$this->format];
} else { } else {
$class['class'] = HtmlFormatter::class; $class['class'] = HtmlFormatter::class;
} }
$format = Snowflake::createObject($class); $format = Snowflake::createObject($class);
return $format->send($context)->getData(); return $format->send($context)->getData();
} }
/** /**
* @param $result * @param $result
* @return string * @return string
* @throws Exception * @throws Exception
*/ */
private function printResult($result): string private function printResult($result): string
{ {
$result = Help::toString($result); $result = Help::toString($result);
$string = PHP_EOL . 'Command Result: ' . PHP_EOL . PHP_EOL; $string = PHP_EOL . 'Command Result: ' . PHP_EOL . PHP_EOL;
fire('CONSOLE_END'); fire('CONSOLE_END');
if (str_contains((string)$result, 'Event::rshutdown(): Event::wait()')) { if (str_contains((string)$result, 'Event::rshutdown(): Event::wait()')) {
return (string)$result; return (string)$result;
} }
if (empty($result)) { if (empty($result)) {
$string .= 'success!' . PHP_EOL . PHP_EOL; $string .= 'success!' . PHP_EOL . PHP_EOL;
} else { } else {
$string .= $result . PHP_EOL . PHP_EOL; $string .= $result . PHP_EOL . PHP_EOL;
} }
$string .= 'Command End!' . PHP_EOL . PHP_EOL; $string .= 'Command End!' . PHP_EOL . PHP_EOL;
print_r($string); print_r($string);
return (string)$result; return (string)$result;
} }
/** /**
* @param $response * @param $response
* @param $sendData * @param $sendData
* @param $status * @param $status
* @throws Exception * @throws Exception
*/ */
private function sendData($response, $sendData, $status): void private function sendData($response, $sendData, $status): void
{ {
$server = Snowflake::app()->getSwoole(); $server = Snowflake::app()->getSwoole();
if (!$server->exist($response->fd) || $server->isEstablished($response->fd)) { if (!$server->exist($response->fd)) {
return; return;
} }
if (is_array($sendData)) { if ($server instanceof Server && !$server->isEstablished($response->fd)) {
$sendData = Json::encode($sendData); return;
} }
$this->setHeaders($response, $status)->end($sendData); if (is_array($sendData)) {
} $sendData = Json::encode($sendData);
}
$this->setHeaders($response, $status)->end($sendData);
}
/** /**
* @param SResponse $response * @param SResponse $response
* @param $status * @param $status
* @return SResponse * @return SResponse
*/ */
private function setHeaders(SResponse $response, $status): SResponse private function setHeaders(SResponse $response, $status): SResponse
{ {
$response->status($status); $response->status($status);
$response->header('Content-Type', $this->getContentType()); $response->header('Content-Type', $this->getContentType());
$response->header('Run-Time', $this->getRuntime()); $response->header('Run-Time', $this->getRuntime());
if (empty($this->headers) || !is_array($this->headers)) { if (empty($this->headers) || !is_array($this->headers)) {
return $response; return $response;
} }
foreach ($this->headers as $key => $header) { foreach ($this->headers as $key => $header) {
$response->header($key, $header); $response->header($key, $header);
} }
$this->headers = []; $this->headers = [];
return $response; return $response;
} }
/** /**
* @param $url * @param $url
* @param array $param * @param array $param
* @return int * @return int
*/ */
public function redirect($url, array $param = []): int public function redirect($url, array $param = []): int
{ {
if (!empty($param)) { if (!empty($param)) {
$url .= '?' . http_build_query($param); $url .= '?' . http_build_query($param);
} }
$url = ltrim($url, '/'); $url = ltrim($url, '/');
if (!preg_match('/^http/', $url)) { if (!preg_match('/^http/', $url)) {
$url = '/' . $url; $url = '/' . $url;
} }
return $this->response->redirect($url); return $this->response->redirect($url);
} }
/** /**
* @param null $response * @param null $response
* @return static * @return static
* @throws Exception * @throws Exception
*/ */
public static function create($response = null): static public static function create($response = null): static
{ {
Context::setContext('response', $response); Context::setContext('response', $response);
$ciResponse = Snowflake::getApp('response'); $ciResponse = Snowflake::getApp('response');
$ciResponse->response = $response; $ciResponse->response = $response;
$ciResponse->startTime = microtime(true); $ciResponse->startTime = microtime(true);
$ciResponse->format = self::JSON; $ciResponse->format = self::JSON;
return $ciResponse; return $ciResponse;
} }
/** /**
* @param int $statusCode * @param int $statusCode
* @param string $message * @param string $message
* @return mixed * @return mixed
* @throws Exception * @throws Exception
*/ */
public function close($statusCode = 200, $message = ''): mixed public function close($statusCode = 200, $message = ''): mixed
{ {
return $this->send($message, $statusCode); return $this->send($message, $statusCode);
} }
/** /**
* @param $clientId * @param $clientId
* @param int $statusCode * @param int $statusCode
* @param string $message * @param string $message
* @return mixed * @return mixed
*/ */
public function closeClient($clientId, $statusCode = 200, $message = ''): mixed public function closeClient($clientId, $statusCode = 200, $message = ''): mixed
{ {
$socket = Snowflake::getWebSocket(); $socket = Snowflake::getWebSocket();
if (!$socket->exist($clientId)) { if (!$socket->exist($clientId)) {
return true; return true;
} }
return $socket->close($clientId, true); return $socket->close($clientId, true);
} }
/** /**
* @param string $path * @param string $path
* @param int $offset * @param int $offset
* @param int $limit * @param int $limit
* @param int $sleep * @param int $sleep
* @return string * @return string
*/ */
public function sendFile(string $path, $offset = 0, $limit = 1024000, $sleep = 0): string public function sendFile(string $path, $offset = 0, $limit = 1024000, $sleep = 0): string
{ {
$open = fopen($path, 'r'); $open = fopen($path, 'r');
$stat = fstat($open); $stat = fstat($open);
while ($file = fread($open, $limit)) { while ($file = fread($open, $limit)) {
$this->response->write($file); $this->response->write($file);
fseek($open, $offset); fseek($open, $offset);
if ($sleep > 0) { if ($sleep > 0) {
sleep($sleep); sleep($sleep);
} }
if ($offset >= $stat['size']) { if ($offset >= $stat['size']) {
break; break;
} }
$offset += $limit; $offset += $limit;
} }
$this->response->end(); $this->response->end();
$this->response = null; $this->response = null;
return ''; return '';
} }
/** /**
* @throws Exception * @throws Exception
*/ */
public function sendNotFind() public function sendNotFind()
{ {
$this->format = static::HTML; $this->format = static::HTML;
$this->send('', 404); $this->send('', 404);
} }
/** /**
* @return string * @return string
*/ */
#[Pure] public function getRuntime(): string #[Pure] public function getRuntime(): string
{ {
return sprintf('%.5f', microtime(TRUE) - $this->startTime); return sprintf('%.5f', microtime(TRUE) - $this->startTime);
} }
} }