This commit is contained in:
as2252258@163.com
2021-04-24 16:45:38 +08:00
parent dfa7ebf521
commit b6c0619a2e
+291 -292
View File
@@ -27,340 +27,339 @@ 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
* @param null $response * @param null $response
* @return bool * @return bool
* @throws Exception * @throws Exception
*/ */
public function send($context = '', $statusCode = 200, $response = null): mixed public function send($context = '', $statusCode = 200, $response = null): mixed
{ {
$sendData = $this->parseData($context); $sendData = $this->parseData($context);
if ($response instanceof SResponse) { if ($response instanceof SResponse) {
$this->response = $response; $this->response = $response;
} }
if ($this->response instanceof SResponse) { if ($this->response instanceof SResponse) {
$this->sendData($sendData, $statusCode); $this->sendData($this->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 ($context === null) { if ($context === null) {
return ''; return '';
} }
if (isset($this->_format_maps[$this->format])) { if (isset($this->_format_maps[$this->format])) {
$config['class'] = $this->_format_maps[$this->format]; $config['class'] = $this->_format_maps[$this->format];
} else { } else {
$config['class'] = HtmlFormatter::class; $config['class'] = HtmlFormatter::class;
} }
$formatter = Snowflake::createObject($config); $formatter = Snowflake::createObject($config);
return $formatter->send($context)->getData(); return $formatter->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;
if (!str_contains($result, 'Event::rshutdown(): Event::wait()')) { if (!str_contains($result, 'Event::rshutdown(): Event::wait()')) {
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);
} }
$event = Snowflake::app()->getEvent(); $event = Snowflake::app()->getEvent();
$event->trigger('CONSOLE_END'); $event->trigger('CONSOLE_END');
return $result; return $result;
} }
/** /**
* @param $sendData * @param $sendData
* @param $status * @param $status
* @throws Exception * @throws Exception
*/ */
private function sendData($sendData, $status): void private function sendData($response, $sendData, $status): void
{ {
if (!$this->response->isWritable()) { if (!swoole()->exist($response->fd) || !$response->isWritable()) {
return; return;
} }
$this->setHeaders($status); $this->setHeaders($response, $status);
if (empty($sendData)) { if (empty($sendData)) {
$this->response->end(''); $response->end('');
} else { } else {
$message = '[' . date('Y-m-d H:i:s') . ']' . $sendData . PHP_EOL . PHP_EOL; $message = '[' . date('Y-m-d H:i:s') . ']' . $sendData . PHP_EOL . PHP_EOL;
Snowflake::writeFile(storage('response.log'), $message, FILE_APPEND); Snowflake::writeFile(storage('response.log'), $message, FILE_APPEND);
$this->response->end($sendData); $response->end($sendData);
} }
$this->response = null; }
}
/** /**
* @param $status * @param $status
*/ */
private function setHeaders($status): void private function setHeaders($response, $status): void
{ {
$this->response->status($status); $response->status($status);
$this->response->header('Content-Type', $this->getContentType()); $response->header('Content-Type', $this->getContentType());
$this->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; return;
} }
foreach ($this->headers as $key => $header) { foreach ($this->headers as $key => $header) {
$this->response->header($key, $header, true); $response->header($key, $header, true);
} }
} }
/** /**
* @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 mixed * @return mixed
*/ */
public static function create($response = null): static public static function create($response = null): static
{ {
$ciResponse = new Response(); $ciResponse = new Response();
$ciResponse->response = $response; $ciResponse->response = $response;
$ciResponse->startTime = microtime(true); $ciResponse->startTime = microtime(true);
$ciResponse->format = self::JSON; $ciResponse->format = self::JSON;
Context::setContext('response', $ciResponse); Context::setContext('response', $ciResponse);
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);
} }
} }