Files
kiri-core/HttpServer/Http/Response.php
T

369 lines
6.9 KiB
PHP
Raw Normal View History

2020-08-31 01:27:08 +08:00
<?php
/**
* Created by PhpStorm.
* User: whwyy
* Date: 2018/4/24 0024
* Time: 19:39
*/
2020-10-29 18:17:25 +08:00
declare(strict_types=1);
2020-08-31 01:27:08 +08:00
namespace HttpServer\Http;
2021-04-23 11:38:29 +08:00
use Exception;
2021-02-20 17:33:28 +08:00
use HttpServer\Abstracts\HttpService;
2020-08-31 01:27:08 +08:00
use HttpServer\Http\Formatter\HtmlFormatter;
use HttpServer\Http\Formatter\JsonFormatter;
use HttpServer\Http\Formatter\XmlFormatter;
2021-03-05 11:57:58 +08:00
use JetBrains\PhpStorm\Pure;
2020-08-31 01:27:08 +08:00
use Snowflake\Core\Help;
2021-04-28 12:11:41 +08:00
use Snowflake\Core\Json;
2020-08-31 01:27:08 +08:00
use Snowflake\Snowflake;
use Swoole\Http\Response as SResponse;
2020-09-16 20:24:37 +08:00
use Swoole\Http2\Response as S2Response;
2020-08-31 01:27:08 +08:00
/**
* Class Response
2020-08-31 12:38:32 +08:00
* @package Snowflake\Snowflake\Http
2020-08-31 01:27:08 +08:00
*/
2021-02-20 17:33:28 +08:00
class Response extends HttpService
2020-08-31 01:27:08 +08:00
{
2021-04-25 18:08:32 +08:00
const JSON = 'json';
const XML = 'xml';
const HTML = 'html';
/** @var ?string */
public ?string $format = null;
/** @var int */
public int $statusCode = 200;
public ?SResponse $response = null;
public bool $isWebSocket = false;
public array $headers = [];
private float $startTime = 0;
private array $_format_maps = [
self::JSON => JsonFormatter::class,
self::XML => XmlFormatter::class,
self::HTML => HtmlFormatter::class
];
public int $fd = 0;
/**
* @param $format
* @return $this
*/
public function setFormat($format): static
{
$this->format = $format;
return $this;
}
/**
* 清理无用数据
*/
public function clear(): void
{
$this->fd = 0;
$this->isWebSocket = false;
$this->format = null;
}
/**
* @return string
*/
public function getContentType(): string
{
if ($this->format == null || $this->format == static::JSON) {
return 'application/json;charset=utf-8';
} else if ($this->format == static::XML) {
return 'application/xml;charset=utf-8';
} else {
return 'text/html;charset=utf-8';
}
}
/**
* @param $content
* @return mixed
*/
public function toHtml($content): mixed
{
$this->format = self::HTML;
return $content;
}
/**
* @param $content
* @return mixed
*/
public function toJson($content): mixed
{
$this->format = self::JSON;
return $content;
}
/**
* @param $content
* @return mixed
*/
public function toXml($content): mixed
{
$this->format = self::XML;
return $content;
}
/**
* @return mixed
* @throws Exception
*/
public function sender(): mixed
{
return $this->send(func_get_args());
}
/**
* @param $key
* @param $value
* @return Response
*/
public function addHeader($key, $value): static
{
$this->headers[$key] = $value;
return $this;
}
/**
* @return bool
*/
private function isClient(): bool
{
return !($this->response instanceof SResponse) && !($this->response instanceof S2Response);
}
/**
* @param string $context
* @param int $statusCode
* @return bool
* @throws Exception
*/
2021-04-27 18:13:27 +08:00
public function send($context = '', $statusCode = 200): mixed
2021-04-25 18:08:32 +08:00
{
$sendData = $this->parseData($context);
2021-04-27 16:50:55 +08:00
$response = Context::getContext('response');
if ($response instanceof SResponse) {
$this->sendData($response, $sendData, $statusCode);
2021-04-25 18:08:32 +08:00
} else {
if (!empty(request()->fd)) {
return '';
}
$this->printResult($sendData);
}
return $sendData;
}
/**
* @param $context
* @return mixed
* @throws Exception
*/
private function parseData($context): mixed
{
2021-04-27 11:38:03 +08:00
if (empty($context)) {
return $context;
}
if (isset($this->_format_maps[$this->format])) {
$class['class'] = $this->_format_maps[$this->format];
} else {
$class['class'] = HtmlFormatter::class;
2021-04-25 18:08:32 +08:00
}
2021-04-27 11:38:03 +08:00
$format = Snowflake::createObject($class);
return $format->send($context)->getData();
2021-04-25 18:08:32 +08:00
}
/**
* @param $result
* @return string
* @throws Exception
*/
private function printResult($result): string
{
$result = Help::toString($result);
$string = PHP_EOL . 'Command Result: ' . PHP_EOL . PHP_EOL;
fire('CONSOLE_END');
if (str_contains((string)$result, 'Event::rshutdown(): Event::wait()')) {
return (string)$result;
}
if (empty($result)) {
$string .= 'success!' . PHP_EOL . PHP_EOL;
} else {
$string .= $result . PHP_EOL . PHP_EOL;
}
$string .= 'Command End!' . PHP_EOL . PHP_EOL;
print_r($string);
return (string)$result;
}
/**
* @param $response
* @param $sendData
* @param $status
* @throws Exception
*/
private function sendData($response, $sendData, $status): void
{
2021-04-27 18:13:27 +08:00
if (!Snowflake::getWebSocket()->exist($response->fd)) {
2021-04-25 18:08:32 +08:00
return;
}
2021-04-28 12:11:41 +08:00
if (is_array($sendData)) {
$sendData = Json::encode($sendData);
}
2021-04-27 18:15:03 +08:00
$this->setHeaders($response, $status)->end($sendData);
2021-04-25 18:08:32 +08:00
}
/**
2021-04-27 17:25:47 +08:00
* @param SResponse $response
2021-04-25 18:08:32 +08:00
* @param $status
2021-04-27 18:15:03 +08:00
* @return SResponse
2021-04-25 18:08:32 +08:00
*/
2021-04-27 18:15:03 +08:00
private function setHeaders(SResponse $response, $status): SResponse
2021-04-25 18:08:32 +08:00
{
$response->status($status);
$response->header('Content-Type', $this->getContentType());
$response->header('Run-Time', $this->getRuntime());
2021-06-08 11:50:05 +08:00
var_dump($this->headers);
2021-04-25 18:08:32 +08:00
if (empty($this->headers) || !is_array($this->headers)) {
2021-04-27 18:15:03 +08:00
return $response;
2021-04-25 18:08:32 +08:00
}
foreach ($this->headers as $key => $header) {
2021-06-08 11:50:05 +08:00
$response->header($key, $header);
2021-04-25 18:08:32 +08:00
}
$this->headers = [];
2021-04-27 18:15:03 +08:00
return $response;
2021-04-25 18:08:32 +08:00
}
/**
* @param $url
* @param array $param
* @return int
*/
public function redirect($url, array $param = []): int
{
if (!empty($param)) {
$url .= '?' . http_build_query($param);
}
$url = ltrim($url, '/');
if (!preg_match('/^http/', $url)) {
$url = '/' . $url;
}
return $this->response->redirect($url);
}
/**
* @param null $response
2021-04-27 16:50:55 +08:00
* @return static
2021-04-27 16:51:23 +08:00
* @throws Exception
2021-04-25 18:08:32 +08:00
*/
public static function create($response = null): static
{
2021-04-27 16:50:55 +08:00
Context::setContext('response', $response);
2021-04-27 16:51:23 +08:00
$ciResponse = Snowflake::getApp('response');
2021-04-25 18:08:32 +08:00
$ciResponse->response = $response;
$ciResponse->startTime = microtime(true);
$ciResponse->format = self::JSON;
return $ciResponse;
}
/**
* @param int $statusCode
* @param string $message
* @return mixed
* @throws Exception
*/
public function close($statusCode = 200, $message = ''): mixed
{
return $this->send($message, $statusCode);
}
/**
* @param $clientId
* @param int $statusCode
* @param string $message
* @return mixed
*/
public function closeClient($clientId, $statusCode = 200, $message = ''): mixed
{
$socket = Snowflake::getWebSocket();
if (!$socket->exist($clientId)) {
return true;
}
return $socket->close($clientId, true);
}
/**
* @param string $path
* @param int $offset
* @param int $limit
* @param int $sleep
* @return string
*/
public function sendFile(string $path, $offset = 0, $limit = 1024000, $sleep = 0): string
{
$open = fopen($path, 'r');
$stat = fstat($open);
while ($file = fread($open, $limit)) {
$this->response->write($file);
fseek($open, $offset);
if ($sleep > 0) {
sleep($sleep);
}
if ($offset >= $stat['size']) {
break;
}
$offset += $limit;
}
$this->response->end();
$this->response = null;
return '';
}
/**
* @throws Exception
*/
public function sendNotFind()
{
$this->format = static::HTML;
$this->send('', 404);
}
/**
* @return string
*/
#[Pure] public function getRuntime(): string
{
return sprintf('%.5f', microtime(TRUE) - $this->startTime);
}
2020-08-31 01:27:08 +08:00
}