This commit is contained in:
xl
2023-07-12 21:38:27 +08:00
parent 14574e7a6c
commit 18b44b32f2
6 changed files with 312 additions and 397 deletions
+36 -93
View File
@@ -5,12 +5,7 @@ namespace Kiri;
use Closure;
use Exception;
use JetBrains\PhpStorm\Pure;
use Kiri\Core\Help;
use Kiri\Di\Context;
use Kiri\Router\Constrict\Stream;
use Psr\Http\Message\StreamInterface;
use Swoole\Coroutine;
use Swoole\Coroutine\System;
defined('SPLIT_URL') or define('SPLIT_URL', '/(http[s]?:\/\/)?(([\w\-_]+\.)+\w+(:\d+)?)((\/[a-zA-Z0-9\-]+)+[\/]?(\?[a-zA-Z]+=.*)?)?/');
@@ -47,6 +42,7 @@ abstract class ClientAbstracts implements IClient
private string $ca = '';
private int $port = 80;
protected int $num = 0;
private ?array $_responseHeader = [];
@@ -68,7 +64,7 @@ abstract class ClientAbstracts implements IClient
protected ?string $body;
private ?StreamInterface $_data = NULL;
private string|array|null $_data = NULL;
private int $connect_timeout = 1;
@@ -216,9 +212,9 @@ abstract class ClientAbstracts implements IClient
/**
* @param string $path
* @param array $params
* @param array|string $params
*/
public function post(string $path, array $params = []): void
public function post(string $path, array|string $params = []): void
{
$this->request(self::POST, $path, $params);
}
@@ -226,9 +222,9 @@ abstract class ClientAbstracts implements IClient
/**
* @param string $path
* @param array $params
* @param array|string $params
*/
public function put(string $path, array $params = []): void
public function put(string $path, array|string $params = []): void
{
$this->request(self::PUT, $path, $params);
}
@@ -247,9 +243,9 @@ abstract class ClientAbstracts implements IClient
/**
* @param string $path
* @param array $params
* @param array|string $params
*/
public function head(string $path, array $params = []): void
public function head(string $path, array|string $params = []): void
{
$this->request(self::HEAD, $path, $params);
}
@@ -257,36 +253,39 @@ abstract class ClientAbstracts implements IClient
/**
* @param string $path
* @param array $params
* @param array|string $params
*/
public function get(string $path, array $params = []): void
public function get(string $path, array|string $params = []): void
{
if (is_array($params)) {
$params = http_build_query($params);
}
$this->request(self::GET, $path, $params);
}
/**
* @param string $path
* @param array $params
* @param array|string $params
*/
public function option(string $path, array $params = []): void
public function option(string $path, array|string $params = []): void
{
$this->request(self::OPTIONS, $path, $params);
}
/**
* @param string $path
* @param array $params
* @param array|string $params
*/
public function delete(string $path, array $params = []): void
public function delete(string $path, array|string $params = []): void
{
$this->request(self::DELETE, $path, $params);
}
/**
* @param string $path
* @param array $params
* @param array|string $params
*/
public function options(string $path, array $params = []): void
public function options(string $path, array|string $params = []): void
{
$this->request(self::OPTIONS, $path, $params);
@@ -294,9 +293,9 @@ abstract class ClientAbstracts implements IClient
/**
* @param string $path
* @param array $params
* @param array|string $params
*/
public function upload(string $path, array $params = []): void
public function upload(string $path, array|string $params = []): void
{
$this->request(self::UPLOAD, $path, $params);
}
@@ -313,7 +312,7 @@ abstract class ClientAbstracts implements IClient
/**
* @return int
*/
#[Pure] protected function getHostPort(): int
protected function getHostPort(): int
{
if (!empty($this->getPort())) {
return $this->getPort();
@@ -332,7 +331,7 @@ abstract class ClientAbstracts implements IClient
{
$this->host = $host;
if (!preg_match('/(\d{1,3}\.){3}\d{1,3}/', $host)) {
if (Context::inCoroutine()) {
if (class_exists(Coroutine::class) && Coroutine::getCid() > -1) {
$this->host = System::gethostbyname($host);
}
return $this->withAddedHeader('Host', $host);
@@ -535,7 +534,7 @@ abstract class ClientAbstracts implements IClient
/**
* @return int
*/
#[Pure] public function getPort(): int
public function getPort(): int
{
if ($this->isSSL()) {
return 443;
@@ -558,25 +557,19 @@ abstract class ClientAbstracts implements IClient
/**
* @return StreamInterface
* @return string|null
*/
public function getData(): StreamInterface
public function getData(): ?string
{
if (!$this->_data) {
$this->_data = new Stream();
}
return $this->_data;
}
/**
* @param string|StreamInterface $data
* @param string|null $data
* @return ClientAbstracts
*/
public function withBody(string|StreamInterface $data): static
public function withBody(?string $data): static
{
if (is_string($data)) {
$data = new Stream($data);
}
$this->_data = $data;
return $this;
}
@@ -650,68 +643,18 @@ abstract class ClientAbstracts implements IClient
*/
protected function mergeParams($newData): ?string
{
if (!is_string($newData)) {
return $this->toRequest($newData);
if (is_array($newData)) {
return json_encode($newData,JSON_UNESCAPED_UNICODE);
}
return (string)$newData;
}
/**
* @param $data
* @return string
*/
protected function toRequest($data): string
{
if (is_string($data)) {
return $data;
}
$contentType = 'application/x-www-form-urlencoded';
if (isset($this->header['Content-Type'])) {
$contentType = $this->header['Content-Type'];
} else if (isset($this->header['content-type'])) {
$contentType = $this->header['content-type'];
}
if (str_contains($contentType, 'json')) {
return Help::toJson($data);
} else if (str_contains($contentType, 'xml')) {
return Help::toXml($data);
} else {
return http_build_query($data);
}
}
/**
* @param $data
* @param $body
* @return array|string|null
* @throws Exception
*/
protected function resolve($data, $body): array|string|null
{
if (is_array($body)) {
return $body;
}
$type = $data['content-type'] ?? $data['Content-Type'] ?? 'text/html';
if (str_contains($type, 'text/html')) {
return $body;
} else if (str_contains($type, 'json')) {
return json_decode($body, TRUE);
} else if (str_contains($type, 'xml')) {
return Help::xmlToArray($body);
} else if (str_contains($type, 'plain')) {
return Help::toArray($body);
}
return $body;
}
/**
* @return bool
* check isPost Request
*/
#[Pure] protected function isPost(): bool
protected function isPost(): bool
{
return strtolower($this->method) === self::POST;
}
@@ -720,7 +663,7 @@ abstract class ClientAbstracts implements IClient
* @return bool
* check isPost Request
*/
#[Pure] protected function isUpload(): bool
protected function isUpload(): bool
{
return strtolower($this->method) === self::UPLOAD;
}
@@ -731,7 +674,7 @@ abstract class ClientAbstracts implements IClient
*
* check isGet Request
*/
#[Pure] protected function isGet(): bool
protected function isGet(): bool
{
return strtolower($this->method) === self::GET;
}
@@ -742,7 +685,7 @@ abstract class ClientAbstracts implements IClient
* @return array|string
* 将请求参数进行编码
*/
#[Pure] protected function paramEncode($arr): array|string
protected function paramEncode($arr): array|string
{
if (!is_array($arr)) {
return $arr;
@@ -762,7 +705,7 @@ abstract class ClientAbstracts implements IClient
* @param string $string
* @return array
*/
#[Pure] protected function matchHost(string $string): array
protected function matchHost(string $string): array
{
return [$this->host, $this->isSSL(), $string];
}
+4 -25
View File
@@ -10,10 +10,6 @@ declare(strict_types=1);
namespace Kiri;
use Exception;
use Kiri;
use Kiri\Abstracts\Logger;
use Kiri\Di\Context;
use Psr\Log\LoggerInterface;
use Swoole\Coroutine\Http\Client as SwowClient;
/**
@@ -28,11 +24,11 @@ class CoroutineClient extends ClientAbstracts
/**
* @param string $method
* @param $path
* @param array $params
* @param array|string $params
* @return void
* @throws Exception
*/
public function request(string $method, $path, array $params = []): void
public function request(string $method, $path, array|string $params = []): void
{
if (!str_starts_with($path, '/')) {
$path = '/' . $path;
@@ -70,10 +66,6 @@ class CoroutineClient extends ClientAbstracts
$this->execute($url, $data);
} catch (\Throwable $exception) {
Kiri::getDi()->get(Logger::class)->error('rpc', []);
Kiri::getLogger()->error(throwable($exception));
$this->setStatusCode(-1);
$this->setBody(jTraceEx($exception));
}
@@ -89,17 +81,6 @@ class CoroutineClient extends ClientAbstracts
private function execute($path, $data): void
{
$this->client->execute($this->setParams($path, $data));
if ($this->client->statusCode < 1) {
$logger = Kiri::getDi()->get(LoggerInterface::class);
$errMsg = sprintf("%s://%s:%s/%s -> error: %s", $this->isSSL() ? "https" : "http",
$this->getHost(), $this->getPort(), $path, $this->client->errMsg);
if (!empty($data)) {
$errMsg .= print_r($data, true);
}
$logger->error($errMsg);
}
if (in_array($this->client->getStatusCode(), [502, 404])) {
$this->retry($path, $data);
} else {
@@ -118,13 +99,11 @@ class CoroutineClient extends ClientAbstracts
*/
private function retry($path, $data): void
{
if (Context::increment('retry') <= $this->retryNum) {
if (($this->num += 1) <= $this->retryNum) {
sleep($this->retryTimeout);
$this->execute($path, $data);
} else {
Context::remove('retry');
$this->setStatusCode($this->client->statusCode);
$this->setBody($this->client->errMsg);
}
@@ -157,7 +136,7 @@ class CoroutineClient extends ClientAbstracts
*/
private function setParams($path, $data): string
{
$content = $this->getData()->getContents();
$content = $this->getData();
if (!empty($content)) {
$this->client->setData($content);
}
+10 -11
View File
@@ -5,8 +5,6 @@ namespace Kiri;
use Exception;
use JetBrains\PhpStorm\Pure;
use Kiri\Di\Context;
/**
@@ -19,10 +17,10 @@ class CurlClient extends ClientAbstracts
/**
* @param $method
* @param $path
* @param array $params
* @param array|string $params
* @throws Exception
*/
public function request($method, $path, array $params = []): void
public function request($method, $path, array|string $params = []): void
{
if (!str_starts_with($path, '/')) {
$path = '/' . $path;
@@ -53,16 +51,19 @@ class CurlClient extends ClientAbstracts
if ($this->isSSL()) {
$this->curlHandlerSslSet();
}
$contents = $this->getData()->getContents();
$contents = $this->getData();
if (empty($params) && empty($contents)) {
return;
}
if (!empty($contents)) {
curl_setopt($this->client, CURLOPT_POSTFIELDS, $contents);
} else if ($method === self::POST) {
curl_setopt($this->client, CURLOPT_POSTFIELDS, $this->mergeParams($params));
} else if ($method === self::UPLOAD) {
curl_setopt($this->client, CURLOPT_POSTFIELDS, $params);
} else if ($method === self::POST) {
if (is_array($params)) {
$params = http_build_query($params);
}
curl_setopt($this->client, CURLOPT_POSTFIELDS, $params);
}
}
@@ -154,13 +155,11 @@ class CurlClient extends ClientAbstracts
*/
private function retry(): void
{
if (Context::increment('retry') <= $this->retryNum) {
if (($this->num += 1) <= $this->retryNum) {
sleep($this->retryTimeout);
$this->execute();
} else {
Context::remove('retry');
$this->setStatusCode(curl_errno($this->client));
$this->setBody(curl_error($this->client));
}
@@ -220,7 +219,7 @@ class CurlClient extends ClientAbstracts
/**
* @return array
*/
#[Pure] private function parseHeaderMat(): array
private function parseHeaderMat(): array
{
$headers = [];
foreach ($this->getHeader() as $key => $val) {
+18 -20
View File
@@ -5,8 +5,6 @@ namespace Kiri;
use Closure;
use Psr\Http\Message\ResponseInterface;
use Psr\Http\Message\StreamInterface;
interface IClient
{
@@ -14,16 +12,16 @@ interface IClient
/**
* @param string $path
* @param array $params
* @param array|string $params
*/
public function get(string $path, array $params = []): void;
public function get(string $path, array|string $params = []): void;
/**
* @param string $path
* @param array $params
* @param array|string $params
*/
public function post(string $path, array $params = []): void;
public function post(string $path, array|string $params = []): void;
/**
@@ -34,45 +32,45 @@ interface IClient
/**
* @param string $path
* @param array $params
* @param array|string $params
*/
public function delete(string $path, array $params = []): void;
public function delete(string $path, array|string $params = []): void;
/**
* @param string $path
* @param array $params
* @param array|string $params
*/
public function options(string $path, array $params = []): void;
public function options(string $path, array|string $params = []): void;
/**
* @param string $path
* @param array $params
* @param array|string $params
*/
public function upload(string $path, array $params = []): void;
public function upload(string $path, array|string $params = []): void;
/**
* @param string $path
* @param array $params
* @param array|string $params
*/
public function put(string $path, array $params = []): void;
public function put(string $path, array|string $params = []): void;
/**
* @param string $path
* @param array $params
* @param array|string $params
*/
public function head(string $path, array $params = []): void;
public function head(string $path, array|string $params = []): void;
/**
* @param string $method
* @param string $path
* @param array $params
* @param array|string $params
*/
public function request(string $method, string $path, array $params = []): void;
public function request(string $method, string $path, array|string $params = []): void;
/**
@@ -154,10 +152,10 @@ interface IClient
/**
* @param string|StreamInterface $data
* @param string $data
* @return static
*/
public function withBody(string|StreamInterface $data): static;
public function withBody(string $data): static;
/**
+1 -3
View File
@@ -2,8 +2,6 @@
namespace Kiri;
use JetBrains\PhpStorm\Pure;
trait TSwooleClient
{
@@ -11,7 +9,7 @@ trait TSwooleClient
/**
* @return array
*/
#[Pure] private function settings(): array
private function settings(): array
{
$sslCert = $this->getSslCertFile();
$sslKey = $this->getSslKeyFile();
+1 -3
View File
@@ -11,9 +11,7 @@
"require": {
"php": ">=8.0",
"ext-json": "*",
"ext-swoole": "*",
"psr/http-client": "^1.0",
"psr/http-message": "^1.0"
"ext-swoole": "*"
},
"autoload": {
"psr-4": {