Compare commits

...

40 Commits

Author SHA1 Message Date
as2252258 ae3b0c411b Revert "改名"
This reverts commit fdf58326
2022-01-10 11:39:56 +08:00
as2252258 f838795983 e 2022-01-09 13:54:34 +08:00
as2252258 1db430f997 1 2022-01-09 02:44:07 +08:00
as2252258 fdb8816b5e Revert "改名"
This reverts commit fdf58326
2022-01-08 18:49:06 +08:00
as2252258 2623deb63f Revert "改名"
This reverts commit fdf58326
2021-12-28 12:06:53 +08:00
as2252258 98d9cee8b0 改名 2021-12-24 14:53:05 +08:00
as2252258 cec004b670 改名 2021-12-24 14:51:38 +08:00
as2252258 f268b705f7 改名 2021-12-24 14:51:11 +08:00
as2252258 ac279a257a 改名 2021-12-24 14:47:36 +08:00
as2252258 89ba6effeb 改名 2021-12-24 14:47:12 +08:00
as2252258 29e520b412 改名 2021-12-24 14:45:57 +08:00
as2252258 eec7cb7dcc 改名 2021-12-24 14:45:20 +08:00
as2252258 6c71437e9e 改名 2021-12-24 14:39:21 +08:00
as2252258 33fc0ae396 改名 2021-12-24 14:38:26 +08:00
as2252258 23f85ef5f0 改名 2021-12-24 14:32:49 +08:00
as2252258 372dbbb424 改名 2021-12-24 14:31:41 +08:00
as2252258 d07dbf1c8d 改名 2021-12-24 14:31:14 +08:00
as2252258 6ffe1af6d2 改名 2021-12-24 14:29:48 +08:00
as2252258 ca7a4494d8 改名 2021-12-24 14:23:28 +08:00
as2252258 4f99ec5756 改名 2021-12-24 14:19:20 +08:00
as2252258 1d1b36155a 改名 2021-12-24 14:17:01 +08:00
as2252258 00da068b53 改名 2021-12-24 14:16:07 +08:00
as2252258 08793bcf76 改名 2021-12-24 14:14:09 +08:00
as2252258 f5ae86c3d2 改名 2021-12-24 14:13:34 +08:00
as2252258 4856e76e6f 改名 2021-12-24 11:54:30 +08:00
as2252258 09dc2b4980 改名 2021-12-24 11:52:29 +08:00
as2252258 510daa1bb6 改名 2021-12-24 11:51:05 +08:00
as2252258 4dc1120aaf 改名 2021-12-24 11:50:45 +08:00
as2252258 9076b65080 改名 2021-12-24 11:50:17 +08:00
as2252258 adf09f5695 改名 2021-12-24 11:49:23 +08:00
as2252258 06290f5c9b 改名 2021-12-24 11:46:07 +08:00
as2252258 196cb42e6e 改名 2021-12-24 11:44:08 +08:00
as2252258 a0f197d98d 改名 2021-12-24 11:42:58 +08:00
as2252258 c2d5ab5e1b 改名 2021-12-24 11:38:15 +08:00
as2252258 597cacd191 改名 2021-12-24 11:34:29 +08:00
as2252258 f48b6bd5d2 改名 2021-12-23 18:01:07 +08:00
as2252258 2baeb20b8d 1 2021-12-12 04:14:22 +08:00
as2252258 8d685b93e2 1 2021-12-12 04:10:15 +08:00
as2252258 90cada46c4 1 2021-12-12 04:07:34 +08:00
as2252258 0f5d277532 1 2021-12-12 04:06:37 +08:00
11 changed files with 1710 additions and 1698 deletions
+177
View File
@@ -0,0 +1,177 @@
<?php
/**
* Created by PhpStorm.
* User: whwyy
* Date: 2018/5/24 0024
* Time: 11:34
*/
declare(strict_types=1);
namespace Kiri;
use Exception;
use Kiri\Message\Stream;
use Kiri\Abstracts\Logger;
use Swoole\Client as SwowClient;
/**
* Class Client
* @package Kiri\Kiri\Http
*/
class AsyncClient extends ClientAbstracts
{
use TSwooleClient;
/**
* @param string $method
* @param $path
* @param array $params
* @return void
* @throws Exception
*/
public function request(string $method, $path, array $params = []): void
{
$this->withMethod($method)
->coroutine(
$this->matchHost($path),
$this->paramEncode($params)
);
}
/**
* @param $path
* @return $this
*/
public function withCAInfo($path): static
{
return $this;
}
/**
* @param $url
* @param array|string $data
* @throws Exception 使用swoole协程方式请求
*/
private function coroutine($url, array|string $data = []): void
{
try {
$this->generate_client($data, ...$url);
} catch (\Throwable $exception) {
Kiri::getDi()->get(Logger::class)->error('rpc', [$exception]);
$this->setStatusCode(-1);
$this->setBody(jTraceEx($exception));
}
}
/**
* @param $data
* @param $host
* @param $isHttps
* @param $path
* @throws Exception
*/
private function generate_client($data, $host, $isHttps, $path): void
{
$this->client = new SwowClient(SWOOLE_TCP, FALSE);
if (!$this->client->connect($host, $this->getPort())) {
throw new Exception('链接失败');
}
if ($isHttps || $this->isSSL()) {
$this->client->enableSSL();
}
$this->client->set(array_merge($this->settings(), ['open_http_protocol' => true]));
if (!empty($this->getAgent())) {
$this->withAddedHeader('User-Agent', $this->getAgent());
}
$path = $this->setParams($path, $data);
$this->withAddedHeader('Accept', ' text/html,application/xhtml+xml,application/json,application/xml;q=0.9,image/avif,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.9');
// $this->withAddedHeader('Accept-Encoding', 'gzip');
$this->withAddedHeader('Content-Length', $this->getData()->getSize());
$this->execute($path, $this->getData()->getContents());
}
/**
* @param string $path
* @param string $content
* @return void
*/
private function execute(string $path, string $content)
{
$array = [];
$array[] = strtoupper($this->getMethod()) . ' ' . $path . ' HTTP/1.1';
if (!empty($this->getHeader())) {
foreach ($this->getHeader() as $key => $value) {
$array[] = sprintf('%s: %s', $key, $value);
}
}
$this->client->send(implode("\r\n", $array) . "\r\n\r\n" . $content);
$receive = $this->client->recv();
[$header, $body] = explode("\r\n\r\n", $receive);
$header = explode("\r\n", $header);
$status = array_shift($header);
$this->setStatusCode(intval(explode(' ', $status)[1]));
$this->parseResponseHeaders($header);
$this->setBody($body);
}
private function chunked()
{
}
/**
* @param array $headers
* @return void
*/
private function parseResponseHeaders(array $headers)
{
$array = [];
foreach ($headers as $header) {
[$key, $value] = explode(': ', $header);
$array[$key] = trim($value);
}
$this->setResponseHeader($array);
}
/**
* @param $path
* @param $data
* @return string
*/
private function setParams($path, $data): string
{
if ($this->isGet()) {
if (!empty($data)) $path .= '?' . $data;
} else {
$data = $this->mergeParams($data);
if (!empty($data)) {
$this->withBody(new Stream($data));
}
}
return $path;
}
/**
*
*/
public function close(): void
{
$this->client->close();
}
}
+43 -43
View File
@@ -1,43 +1,43 @@
<?php <?php
namespace Http\Client; namespace Kiri;
use Kiri\Context; use Kiri\Context;
/** /**
* @mixin CoroutineClient|Curl * @mixin CoroutineClient|CurlClient
*/ */
class Client class Client
{ {
private CoroutineClient|Curl|AsyncClient $abstracts; private CoroutineClient|CurlClient|AsyncClient $abstracts;
/** /**
* @param string $host * @param string $host
* @param int $port * @param int $port
* @param bool $isSsl * @param bool $isSsl
*/ */
public function __construct(string $host, int $port, bool $isSsl = false) public function __construct(string $host, int $port, bool $isSsl = false)
{ {
if (Context::inCoroutine()) { if (Context::inCoroutine()) {
$this->abstracts = new CoroutineClient($host, $port, $isSsl); $this->abstracts = new CoroutineClient($host, $port, $isSsl);
} else { } else {
$this->abstracts = new AsyncClient($host, $port, $isSsl); $this->abstracts = new CurlClient($host, $port, $isSsl);
} }
} }
/** /**
* @param string $name * @param string $name
* @param array $arguments * @param array $arguments
* @return mixed * @return mixed
*/ */
public function __call(string $name, array $arguments) public function __call(string $name, array $arguments)
{ {
return $this->abstracts->{$name}(...$arguments); return $this->abstracts->{$name}(...$arguments);
} }
} }
File diff suppressed because it is too large Load Diff
+129 -129
View File
@@ -1,129 +1,129 @@
<?php <?php
/** /**
* Created by PhpStorm. * Created by PhpStorm.
* User: whwyy * User: whwyy
* Date: 2018/5/24 0024 * Date: 2018/5/24 0024
* Time: 11:34 * Time: 11:34
*/ */
declare(strict_types=1); declare(strict_types=1);
namespace Http\Client; namespace Kiri;
use Exception; use Exception;
use JetBrains\PhpStorm\Pure; use JetBrains\PhpStorm\Pure;
use Kiri\Abstracts\Logger; use Kiri\Abstracts\Logger;
use Kiri\Kiri; use Kiri\Kiri;
use Swoole\Coroutine\Http\Client as SwowClient; use Swoole\Coroutine\Http\Client as SwowClient;
/** /**
* Class Client * Class Client
* @package Kiri\Kiri\Http * @package Kiri\Kiri\Http
*/ */
class CoroutineClient extends ClientAbstracts class CoroutineClient extends ClientAbstracts
{ {
use TSwooleClient; use TSwooleClient;
/** /**
* @param string $method * @param string $method
* @param $path * @param $path
* @param array $params * @param array $params
* @return void * @return void
* @throws Exception * @throws Exception
*/ */
public function request(string $method, $path, array $params = []): void public function request(string $method, $path, array $params = []): void
{ {
$this->withMethod($method) $this->withMethod($method)
->coroutine( ->coroutine(
$this->matchHost($path), $this->matchHost($path),
$this->paramEncode($params) $this->paramEncode($params)
); );
} }
/** /**
* @param $path * @param $path
* @return $this * @return $this
*/ */
public function withCAInfo($path): static public function withCAInfo($path): static
{ {
return $this; return $this;
} }
/** /**
* @param $url * @param $url
* @param array|string $data * @param array|string $data
* @throws Exception 使用swoole协程方式请求 * @throws Exception 使用swoole协程方式请求
*/ */
private function coroutine($url, array|string $data = []): void private function coroutine($url, array|string $data = []): void
{ {
try { try {
$this->generate_client($data, ...$url); $this->generate_client($data, ...$url);
if ($this->client->statusCode < 0) { if ($this->client->statusCode < 0) {
throw new Exception($this->client->errMsg); throw new Exception($this->client->errMsg);
} }
$this->setStatusCode($this->client->getStatusCode()); $this->setStatusCode($this->client->getStatusCode());
$this->setBody($this->client->getBody()); $this->setBody($this->client->getBody());
$this->setResponseHeader($this->client->headers); $this->setResponseHeader($this->client->headers);
} catch (\Throwable $exception) { } catch (\Throwable $exception) {
Kiri::getDi()->get(Logger::class)->error('rpc', [$exception]); Kiri::getDi()->get(Logger::class)->error('rpc', [$exception]);
$this->setStatusCode(-1); $this->setStatusCode(-1);
$this->setBody(jTraceEx($exception)); $this->setBody(jTraceEx($exception));
} }
} }
/** /**
* @param $data * @param $data
* @param $host * @param $host
* @param $isHttps * @param $isHttps
* @param $path * @param $path
*/ */
private function generate_client($data, $host, $isHttps, $path): void private function generate_client($data, $host, $isHttps, $path): void
{ {
if ($isHttps || $this->isSSL()) { if ($isHttps || $this->isSSL()) {
$this->client = new SwowClient($host, 443, true); $this->client = new SwowClient($host, 443, true);
} else { } else {
$this->client = new SwowClient($host, $this->getPort(), false); $this->client = new SwowClient($host, $this->getPort(), false);
} }
$this->client->set($this->settings()); $this->client->set($this->settings());
if (!empty($this->getAgent())) { if (!empty($this->getAgent())) {
$this->withAddedHeader('User-Agent', $this->getAgent()); $this->withAddedHeader('User-Agent', $this->getAgent());
} }
$this->client->setHeaders($this->getHeader()); $this->client->setHeaders($this->getHeader());
$this->client->setMethod(strtoupper($this->getMethod())); $this->client->setMethod(strtoupper($this->getMethod()));
$this->client->execute($this->setParams($path, $data)); $this->client->execute($this->setParams($path, $data));
} }
/** /**
* @param $path * @param $path
* @param $data * @param $data
* @return string * @return string
*/ */
private function setParams($path, $data): string private function setParams($path, $data): string
{ {
$content = $this->getData()->getContents(); $content = $this->getData()->getContents();
if (!empty($content)) { if (!empty($content)) {
$this->client->setData($content); $this->client->setData($content);
} }
if ($this->isGet()) { if ($this->isGet()) {
if (!empty($data)) $path .= '?' . $data; if (!empty($data)) $path .= '?' . $data;
} else { } else {
$data = $this->mergeParams($data); $data = $this->mergeParams($data);
if (!empty($data)) { if (!empty($data)) {
$this->client->setData($data); $this->client->setData($data);
} }
} }
return $path; return $path;
} }
/** /**
* *
*/ */
public function close(): void public function close(): void
{ {
$this->client->close(); $this->client->close();
} }
} }
+208 -211
View File
@@ -1,211 +1,208 @@
<?php <?php
declare(strict_types=1); declare(strict_types=1);
namespace Http\Client; namespace Kiri;
use Exception; use Exception;
use Http\Message\Response; use Kiri\Message\Response;
use Http\Message\Stream; use Kiri\Message\Stream;
use JetBrains\PhpStorm\Pure; use JetBrains\PhpStorm\Pure;
use Psr\Http\Message\ResponseInterface; use Psr\Http\Message\ResponseInterface;
/** /**
* Class Curl * Class CurlClient
* @package Http\Handler\Client * @package Http\Handler\Client
*/ */
class Curl extends ClientAbstracts class CurlClient extends ClientAbstracts
{ {
/** /**
* @param $method * @param $method
* @param $path * @param $path
* @param array $params * @param array $params
* @throws Exception * @throws Exception
*/ */
public function request($method, $path, array $params = []): void public function request($method, $path, array $params = []): void
{ {
if ($method == self::GET) { if ($method == self::GET) {
$path = $this->joinGetParams($path, $params); $path = $this->joinGetParams($path, $params);
} }
$this->getCurlHandler($path, $method, $params); $this->getCurlHandler($path, $method, $params);
$this->execute(); $this->execute();
} }
/** /**
* @param $path * @param $path
* @param $method * @param $method
* @param $params * @param $params
* @throws Exception * @throws Exception
*/ */
private function getCurlHandler($path, $method, $params): void private function getCurlHandler($path, $method, $params): void
{ {
[$host, $isHttps, $path] = $this->matchHost($path); [$host, $isHttps, $path] = $this->matchHost($path);
$host = $isHttps ? 'https://' . $host : 'http://' . $host; $host = $isHttps ? 'https://' . $host : 'http://' . $host;
if ($this->getPort() != 443 && $this->getPort() != 80) { if ($this->getPort() != 443 && $this->getPort() != 80) {
$host .= ':' . $this->getPort(); $host .= ':' . $this->getPort();
} }
$this->do(curl_init($host . $path), $host . $path, $method); $this->do(curl_init($host . $path), $host . $path, $method);
if ($isHttps !== FALSE) { if ($isHttps !== FALSE) {
$this->curlHandlerSslSet(); $this->curlHandlerSslSet();
} }
$contents = $this->getData()->getContents(); $contents = $this->getData()->getContents();
if (empty($params) && empty($contents)) { if (empty($params) && empty($contents)) {
return; return;
} }
if (!empty($contents)) { if (!empty($contents)) {
curl_setopt($this->client, CURLOPT_POSTFIELDS, $contents); curl_setopt($this->client, CURLOPT_POSTFIELDS, $contents);
} else if ($method === self::POST) { } else if ($method === self::POST) {
curl_setopt($this->client, CURLOPT_POSTFIELDS, $this->mergeParams($params)); curl_setopt($this->client, CURLOPT_POSTFIELDS, $this->mergeParams($params));
} else if ($method === self::UPLOAD) { } else if ($method === self::UPLOAD) {
curl_setopt($this->client, CURLOPT_POSTFIELDS, $params); curl_setopt($this->client, CURLOPT_POSTFIELDS, $params);
} }
} }
/** /**
* @return void * @return void
* @throws Exception * @throws Exception
*/ */
private function curlHandlerSslSet(): void private function curlHandlerSslSet(): void
{ {
curl_setopt($this->client, CURLOPT_SSL_VERIFYPEER, $this->getVerifyPeer()); if (!empty($this->getSslKeyFile()) && file_exists($this->getSslKeyFile())) {
curl_setopt($this->client, CURLOPT_VERBOSE, TRUE); curl_setopt($this->client, CURLOPT_SSLKEY, $this->getSslKeyFile());
// curl_setopt($this->client, CURLOPT_SSL_VERIFYHOST, $this->getVerifyPeer()); }
if (!empty($this->getSslKeyFile()) && file_exists($this->getSslKeyFile())) { if (!empty($this->getSslCertFile()) && file_exists($this->getSslCertFile())) {
curl_setopt($this->client, CURLOPT_SSLKEY, $this->getSslKeyFile()); curl_setopt($this->client, CURLOPT_SSLCERT, $this->getSslCertFile());
} }
if (!empty($this->getSslCertFile()) && file_exists($this->getSslCertFile())) { }
curl_setopt($this->client, CURLOPT_SSLCERT, $this->getSslCertFile());
}
} /**
* @param $resource
* @param $path
/** * @param $method
* @param $resource * @throws Exception
* @param $path */
* @param $method private function do($resource, $path, $method): void
* @throws Exception {
*/ curl_setopt($resource, CURLOPT_URL, $path);
private function do($resource, $path, $method): void curl_setopt($resource, CURLOPT_TIMEOUT, $this->getTimeout()); // 超时设置
{ curl_setopt($resource, CURLOPT_CONNECTTIMEOUT, $this->getConnectTimeout()); // 超时设置
curl_setopt($resource, CURLOPT_URL, $path); curl_setopt($resource, CURLOPT_HEADER, TRUE);
curl_setopt($resource, CURLOPT_TIMEOUT, $this->getTimeout()); // 超时设置 curl_setopt($resource, CURLOPT_FAILONERROR, TRUE);
curl_setopt($resource, CURLOPT_CONNECTTIMEOUT, $this->getConnectTimeout()); // 超时设置 curl_setopt($resource, CURLOPT_HTTPHEADER, $this->parseHeaderMat());
curl_setopt($resource, CURLOPT_HEADER, TRUE); if (defined('CURLOPT_SSL_FALSESTART')) {
curl_setopt($resource, CURLOPT_FAILONERROR, TRUE); curl_setopt($resource, CURLOPT_SSL_FALSESTART, TRUE);
curl_setopt($resource, CURLOPT_HTTPHEADER, $this->parseHeaderMat()); }
if (defined('CURLOPT_SSL_FALSESTART')) { curl_setopt($resource, CURLOPT_FORBID_REUSE, FALSE);
curl_setopt($resource, CURLOPT_SSL_FALSESTART, TRUE); curl_setopt($resource, CURLOPT_FRESH_CONNECT, FALSE);
} if (!empty($this->getAgent())) {
curl_setopt($resource, CURLOPT_FORBID_REUSE, FALSE); curl_setopt($resource, CURLOPT_USERAGENT, $this->getAgent());
curl_setopt($resource, CURLOPT_FRESH_CONNECT, FALSE); }
if (!empty($this->getAgent())) { curl_setopt($resource, CURLOPT_NOBODY, FALSE);
curl_setopt($resource, CURLOPT_USERAGENT, $this->getAgent()); curl_setopt($resource, CURLOPT_RETURNTRANSFER, TRUE);//返回内容
} curl_setopt($resource, CURLOPT_FOLLOWLOCATION, TRUE);// 跟踪重定向
curl_setopt($resource, CURLOPT_NOBODY, FALSE); curl_setopt($resource, CURLOPT_ENCODING, 'gzip,deflate');
curl_setopt($resource, CURLOPT_RETURNTRANSFER, TRUE);//返回内容 if ($method === self::POST || $method == self::UPLOAD) {
curl_setopt($resource, CURLOPT_FOLLOWLOCATION, TRUE);// 跟踪重定向 curl_setopt($resource, CURLOPT_POST, 1);
curl_setopt($resource, CURLOPT_ENCODING, 'gzip,deflate'); }
if ($method === self::POST || $method == self::UPLOAD) { curl_setopt($resource, CURLOPT_CUSTOMREQUEST, strtoupper($method));
curl_setopt($resource, CURLOPT_POST, 1); $this->client = $resource;
} if (!empty($this->caPath)) {
curl_setopt($resource, CURLOPT_CUSTOMREQUEST, strtoupper($method)); curl_setopt($this->client,CURLOPT_CAINFO, $this->caPath);
$this->client = $resource; }
if (!empty($this->caPath)) { }
curl_setopt($this->client,CURLOPT_CAINFO, $this->caPath);
}
} private string $caPath = '';
private string $caPath = ''; /**
* @param $path
* @return $this
/** */
* @param $path public function withCAInfo($path): static
* @return $this {
*/ $this->caPath = $path;
public function withCAInfo($path): static return $this;
{ }
$this->caPath = $path;
return $this;
} /**
* @throws Exception
*/
/** private function execute(): void
* @throws Exception {
*/ $output = curl_exec($this->client);
private function execute(): void if ($output === FALSE) {
{ $this->setStatusCode(curl_errno($this->client));
$output = curl_exec($this->client); $this->setBody(curl_error($this->client));
if ($output === FALSE) { } else {
$this->setStatusCode(curl_errno($this->client)); $this->explode($output);
$this->setBody(curl_error($this->client)); }
} else { }
$this->explode($output);
}
} /**
*
*/
/** public function close(): void
* {
*/ curl_close($this->client);
public function close(): void }
{
curl_close($this->client);
} /**
* @param $output
* @return void
/** * @throws Exception
* @param $output */
* @return void private function explode($output): void
* @throws Exception {
*/ [$header, $body] = explode("\r\n\r\n", $output, 2);
private function explode($output): void if ($header == 'HTTP/1.1 100 Continue') {
{ [$header, $body] = explode("\r\n\r\n", $body, 2);
[$header, $body] = explode("\r\n\r\n", $output, 2); }
if ($header == 'HTTP/1.1 100 Continue') {
[$header, $body] = explode("\r\n\r\n", $body, 2); $header = explode("\r\n", $header);
} $status = explode(' ', array_shift($header));
$header = explode("\r\n", $header); $this->setStatusCode(intval($status[1]));
$status = explode(' ', array_shift($header)); $this->setBody($body);
$this->setResponseHeader($header);
$this->setStatusCode(intval($status[1])); }
$this->setBody($body);
$this->setResponseHeader($header); /**
} * @param $headers
* @return array
/** */
* @param $headers private function headerFormat($headers): array
* @return array {
*/ $_tmp = [];
private function headerFormat($headers): array foreach ($headers as $val) {
{ $trim = explode(': ', trim($val));
$_tmp = [];
foreach ($headers as $val) { $_tmp[strtolower($trim[0])] = [$trim[1] ?? ''];
$trim = explode(': ', trim($val)); }
return $_tmp;
$_tmp[strtolower($trim[0])] = [$trim[1] ?? '']; }
}
return $_tmp;
} /**
* @return array
*/
/** #[Pure] private function parseHeaderMat(): array
* @return array {
*/ $headers = [];
#[Pure] private function parseHeaderMat(): array foreach ($this->getHeader() as $key => $val) {
{ $headers[$key] = $key . ': ' . $val;
$headers = []; }
foreach ($this->getHeader() as $key => $val) { return array_values($headers);
$headers[$key] = $key . ': ' . $val; }
} }
return array_values($headers);
}
}
+109 -109
View File
@@ -1,109 +1,109 @@
<?php <?php
declare(strict_types=1); declare(strict_types=1);
namespace Http\Client; namespace Kiri;
use Exception; use Exception;
/** /**
* Class HttpParse * Class HttpParse
* @package BeReborn\Http * @package BeReborn\Http
*/ */
class HttpParse class HttpParse
{ {
/** /**
* @param mixed ...$object * @param mixed ...$object
* @return string * @return string
*/ */
private static function getKey(...$object): string private static function getKey(...$object): string
{ {
$first = ''; $first = '';
$tp = []; $tp = [];
foreach ($object as $key => $value) { foreach ($object as $key => $value) {
if ($value === null) { if ($value === null) {
continue; continue;
} }
if (is_array($value)) { if (is_array($value)) {
$value = key($value); $value = key($value);
} }
if ($first === '') { if ($first === '') {
$first = $value; $first = $value;
} else { } else {
$tp[] = $value; $tp[] = $value;
} }
} }
$key = $first . '[' . implode('][', $tp) . ']'; $key = $first . '[' . implode('][', $tp) . ']';
if (count($tp) < 1) { if (count($tp) < 1) {
$key = $first; $key = $first;
} }
return $key; return $key;
} }
/** /**
* @param $data * @param $data
* @return string * @return string
* @throws Exception * @throws Exception
*/ */
public static function parse($data): string public static function parse($data): string
{ {
$tmp = []; $tmp = [];
if (is_string($data)) { if (is_string($data)) {
return $data; return $data;
} }
foreach ($data as $key => $datum) { foreach ($data as $key => $datum) {
if ($datum === null) { if ($datum === null) {
continue; continue;
} }
$tmp[] = static::ifElse($key, $datum); $tmp[] = static::ifElse($key, $datum);
} }
return implode('&', $tmp); return implode('&', $tmp);
} }
/** /**
* @param $t * @param $t
* @param $qt * @param $qt
* @return string * @return string
* @throws Exception * @throws Exception
*/ */
private static function ifElse($t, $qt): string private static function ifElse($t, $qt): string
{ {
if (is_numeric($qt)) { if (is_numeric($qt)) {
return $t . '=' . $qt; return $t . '=' . $qt;
} }
if (is_string($qt)) { if (is_string($qt)) {
$string = $t . '=' . urlencode($qt); $string = $t . '=' . urlencode($qt);
} else { } else {
$string = static::encode($t, $qt); $string = static::encode($t, $qt);
} }
return $string; return $string;
} }
/** /**
* @param mixed ...$object * @param mixed ...$object
* @return string * @return string
* @throws Exception * @throws Exception
*/ */
private static function encode(...$object): string private static function encode(...$object): string
{ {
$ret = []; $ret = [];
$data = $object[count($object) - 1]; $data = $object[count($object) - 1];
$key = static::getKey(...$object); $key = static::getKey(...$object);
foreach ($data as $s => $datum) { foreach ($data as $s => $datum) {
if (is_array($datum)) { if (is_array($datum)) {
$object[count($object) - 1] = $s; $object[count($object) - 1] = $s;
$object[] = $datum; $object[] = $datum;
$string = static::encode(...$object); $string = static::encode(...$object);
} else { } else {
if (is_object($datum)) { if (is_object($datum)) {
throw new Exception('Http body con\'t object.'); throw new Exception('Http body con\'t object.');
} }
$string = $key . '=' . urlencode($datum); $string = $key . '=' . urlencode($datum);
} }
$ret[] = $string; $ret[] = $string;
} }
return implode('&', $ret); return implode('&', $ret);
} }
} }
+181 -181
View File
@@ -1,181 +1,181 @@
<?php <?php
namespace Http\Client; namespace Kiri;
use Closure; use Closure;
use Psr\Http\Message\ResponseInterface; use Psr\Http\Message\ResponseInterface;
use Psr\Http\Message\StreamInterface; use Psr\Http\Message\StreamInterface;
interface IClient interface IClient
{ {
/** /**
* @param string $path * @param string $path
* @param array $params * @param array $params
*/ */
public function get(string $path, array $params = []): void; public function get(string $path, array $params = []): void;
/** /**
* @param string $path * @param string $path
* @param array $params * @param array $params
*/ */
public function post(string $path, array $params = []): void; public function post(string $path, array $params = []): void;
/** /**
* *
*/ */
public function close(): void; public function close(): void;
/** /**
* @param string $path * @param string $path
* @param array $params * @param array $params
*/ */
public function delete(string $path, array $params = []): void; public function delete(string $path, array $params = []): void;
/** /**
* @param string $path * @param string $path
* @param array $params * @param array $params
*/ */
public function options(string $path, array $params = []): void; public function options(string $path, array $params = []): void;
/** /**
* @param string $path * @param string $path
* @param array $params * @param array $params
*/ */
public function upload(string $path, array $params = []): void; public function upload(string $path, array $params = []): void;
/** /**
* @param string $path * @param string $path
* @param array $params * @param array $params
*/ */
public function put(string $path, array $params = []): void; public function put(string $path, array $params = []): void;
/** /**
* @param string $path * @param string $path
* @param array $params * @param array $params
*/ */
public function head(string $path, array $params = []): void; public function head(string $path, array $params = []): void;
/** /**
* @param string $method * @param string $method
* @param string $path * @param string $path
* @param array $params * @param array $params
*/ */
public function request(string $method, string $path, array $params = []): void; public function request(string $method, string $path, array $params = []): void;
/** /**
* @param array $header * @param array $header
* @return static * @return static
*/ */
public function withHeader(array $header): static; public function withHeader(array $header): static;
/** /**
* @param array $header * @param array $header
* @return static * @return static
*/ */
public function withHeaders(array $header): static; public function withHeaders(array $header): static;
/** /**
* @param string $key * @param string $key
* @param string $value * @param string $value
* @return static * @return static
*/ */
public function withAddedHeader(string $key, string $value): static; public function withAddedHeader(string $key, string $value): static;
/** /**
* @param int $value * @param int $value
* @return static * @return static
*/ */
public function withTimeout(int $value): static; public function withTimeout(int $value): static;
/** /**
* @param Closure|null $value * @param Closure|null $value
* @return static * @return static
*/ */
public function withCallback(?Closure $value): static; public function withCallback(?Closure $value): static;
/** /**
* @param string $value * @param string $value
* @return static * @return static
*/ */
public function withMethod(string $value): static; public function withMethod(string $value): static;
/** /**
* @param bool $isSSL * @param bool $isSSL
* @return static * @return static
*/ */
public function withIsSSL(bool $isSSL): static; public function withIsSSL(bool $isSSL): static;
/** /**
* @param string $agent * @param string $agent
* @return static * @return static
*/ */
public function withAgent(string $agent): static; public function withAgent(string $agent): static;
/** /**
* @param string $ssl_cert_file * @param string $ssl_cert_file
* @return static * @return static
*/ */
public function withSslCertFile(string $ssl_cert_file): static; public function withSslCertFile(string $ssl_cert_file): static;
/** /**
* @param string $ssl_key_file * @param string $ssl_key_file
* @return static * @return static
*/ */
public function withSslKeyFile(string $ssl_key_file): static; public function withSslKeyFile(string $ssl_key_file): static;
/** /**
* @param string $ssl_key_file * @param string $ssl_key_file
* @return static * @return static
*/ */
public function withCa(string $ssl_key_file): static; public function withCa(string $ssl_key_file): static;
/** /**
* @param string|StreamInterface $data * @param string|StreamInterface $data
* @return static * @return static
*/ */
public function withBody(string|StreamInterface $data): static; public function withBody(string|StreamInterface $data): static;
/** /**
* @param int $connect_timeout * @param int $connect_timeout
* @return static * @return static
*/ */
public function withConnectTimeout(int $connect_timeout): static; public function withConnectTimeout(int $connect_timeout): static;
/** /**
* @param string $contentType * @param string $contentType
* @return static * @return static
*/ */
public function withContentType(string $contentType): static; public function withContentType(string $contentType): static;
/** /**
* @return mixed * @return mixed
*/ */
public function getBody(): mixed; public function getBody(): mixed;
} }
+21 -21
View File
@@ -1,21 +1,21 @@
MIT License MIT License
Copyright (c) 2021 向林 Copyright (c) 2021 向林
Permission is hereby granted, free of charge, to any person obtaining a copy Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions: furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software. copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE. SOFTWARE.
+38 -38
View File
@@ -1,38 +1,38 @@
<?php <?php
namespace Http\Client; namespace Kiri;
use JetBrains\PhpStorm\Pure; use JetBrains\PhpStorm\Pure;
trait TSwooleClient trait TSwooleClient
{ {
/** /**
* @return array * @return array
*/ */
#[Pure] private function settings(): array #[Pure] private function settings(): array
{ {
$sslCert = $this->getSslCertFile(); $sslCert = $this->getSslCertFile();
$sslKey = $this->getSslKeyFile(); $sslKey = $this->getSslKeyFile();
$sslCa = $this->getCa(); $sslCa = $this->getCa();
$params = []; $params = [];
if ($this->getConnectTimeout() > 0) { if ($this->getConnectTimeout() > 0) {
$params['timeout'] = $this->getConnectTimeout(); $params['timeout'] = $this->getConnectTimeout();
} }
if (empty($sslCert) || empty($sslKey) || empty($sslCa)) { if (empty($sslCert) || empty($sslKey) || empty($sslCa)) {
return $params; return $params;
} }
$params['ssl_host_name'] = $this->getHost(); $params['ssl_host_name'] = $this->getHost();
$params['ssl_cert_file'] = $this->getSslCertFile(); $params['ssl_cert_file'] = $this->getSslCertFile();
$params['ssl_key_file'] = $this->getSslKeyFile(); $params['ssl_key_file'] = $this->getSslKeyFile();
$params['ssl_verify_peer'] = TRUE; $params['ssl_verify_peer'] = TRUE;
$params['ssl_cafile'] = $sslCa; $params['ssl_cafile'] = $sslCa;
return $params; return $params;
} }
} }
+25 -26
View File
@@ -1,26 +1,25 @@
{ {
"name": "game-worker/kiri-client", "name": "game-worker/kiri-client",
"description": "db", "description": "db",
"authors": [ "authors": [
{ {
"name": "XiangLin", "name": "XiangLin",
"email": "as2252258@163.com" "email": "as2252258@163.com"
} }
], ],
"license": "MIT", "license": "MIT",
"require": { "require": {
"php": ">=8.0", "php": ">=8.0",
"ext-json": "*", "ext-json": "*",
"ext-redis": "*", "ext-swoole": "*",
"ext-swoole": "*", "psr/http-client": "^1.0",
"psr/http-client": "^1.0", "psr/http-message": "^1.0"
"psr/http-message": "^1.0" },
}, "autoload": {
"autoload": { "psr-4": {
"psr-4": { "Kiri\\": "./"
"Http\\Client\\": "src/" }
} },
}, "require-dev": {
"require-dev": { }
} }
}
-161
View File
@@ -1,161 +0,0 @@
<?php
/**
* Created by PhpStorm.
* User: whwyy
* Date: 2018/5/24 0024
* Time: 11:34
*/
declare(strict_types=1);
namespace Http\Client;
use Exception;
use Http\Message\Stream;
use Kiri\Abstracts\Logger;
use Kiri\Kiri;
use Swoole\Client as SwowClient;
/**
* Class Client
* @package Kiri\Kiri\Http
*/
class AsyncClient extends ClientAbstracts
{
use TSwooleClient;
/**
* @param string $method
* @param $path
* @param array $params
* @return void
* @throws Exception
*/
public function request(string $method, $path, array $params = []): void
{
$this->withMethod($method)
->coroutine(
$this->matchHost($path),
$this->paramEncode($params)
);
}
/**
* @param $path
* @return $this
*/
public function withCAInfo($path): static
{
return $this;
}
/**
* @param $url
* @param array|string $data
* @throws Exception 使用swoole协程方式请求
*/
private function coroutine($url, array|string $data = []): void
{
try {
$this->generate_client($data, ...$url);
} catch (\Throwable $exception) {
Kiri::getDi()->get(Logger::class)->error('rpc', [$exception]);
$this->setStatusCode(-1);
$this->setBody(jTraceEx($exception));
}
}
/**
* @param $data
* @param $host
* @param $isHttps
* @param $path
* @throws Exception
*/
private function generate_client($data, $host, $isHttps, $path): void
{
$this->client = new SwowClient(SWOOLE_TCP, FALSE);
if (!$this->client->connect($host, $this->getPort())) {
throw new Exception('链接失败');
}
if ($isHttps || $this->isSSL()) {
$this->client->enableSSL();
}
$this->client->set($this->settings());
if (!empty($this->getAgent())) {
$this->withAddedHeader('User-Agent', $this->getAgent());
} else {
$this->withAddedHeader('User-Agent', ' Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/96.0.4664.93 Safari/537.36');
}
$path = $this->setParams($path, $data);
$this->withAddedHeader('Accept', ' text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.9');
$this->withAddedHeader('Accept-Encoding', 'gzip, deflate');
$this->withAddedHeader('Content-Length', $this->getData()->getSize());
$this->execute($path, $this->getData()->getContents());
}
/**
* @param string $path
* @param string $content
* @return void
*/
private function execute(string $path, string $content)
{
$array = [];
$array[] = strtoupper($this->getMethod()) . ' ' . $path . ' HTTP/1.1';
if (!empty($this->getHeader())) {
foreach ($this->getHeader() as $key => $value) {
$array[] = sprintf('%s: %s', $key, $value);
}
}
$array = implode("\r\n", $array) . "\r\n\r\n";
$this->client->send($array . $content);
$revice = $this->client->recv();
[$header, $body] = explode("\r\n\r\n", $revice);
$header = explode("\r\n", $header);
$status = array_shift($header);
$this->setBody($body);
$this->setStatusCode(intval(explode(' ', $status)[1]));
$this->setResponseHeader($header);
}
/**
* @param $path
* @param $data
* @return string
*/
private function setParams($path, $data): string
{
if ($this->isGet()) {
if (!empty($data)) $path .= '?' . $data;
} else {
$data = $this->mergeParams($data);
if (!empty($data)) {
$this->withBody(new Stream($data));
}
}
return $path;
}
/**
*
*/
public function close(): void
{
$this->client->close();
}
}