改名
This commit is contained in:
@@ -0,0 +1,13 @@
|
||||
<?php
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace Http\Handler\Abstracts;
|
||||
|
||||
|
||||
|
||||
use Swoole\Coroutine;
|
||||
|
||||
abstract class BaseContext
|
||||
{
|
||||
protected static array $pool = [];
|
||||
}
|
||||
@@ -3,7 +3,6 @@
|
||||
namespace Http\Handler\Abstracts;
|
||||
|
||||
use Closure;
|
||||
use Kiri\Kiri;
|
||||
|
||||
class HandlerManager
|
||||
{
|
||||
@@ -43,4 +42,20 @@ class HandlerManager
|
||||
return $array;
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* @return array
|
||||
*/
|
||||
public static function dump(): array
|
||||
{
|
||||
$array = [];
|
||||
foreach (static::$handlers as $path => $handlers) {
|
||||
$array[] = [
|
||||
'path' => $path,
|
||||
'method' => implode(',', array_keys($handlers))
|
||||
];
|
||||
}
|
||||
return $array;
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
@@ -0,0 +1,52 @@
|
||||
<?php
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace Http\Handler\Abstracts;
|
||||
|
||||
|
||||
use Exception;
|
||||
use Kiri\Abstracts\Component;
|
||||
use Kiri\Kiri;
|
||||
|
||||
|
||||
/**
|
||||
* Class HttpService
|
||||
* @package Http\Abstracts
|
||||
*/
|
||||
abstract class HttpService extends Component
|
||||
{
|
||||
|
||||
|
||||
/**
|
||||
* @param $message
|
||||
* @param string $category
|
||||
* @throws Exception
|
||||
*/
|
||||
protected function write($message, string $category = 'app')
|
||||
{
|
||||
$logger = Kiri::app()->getLogger();
|
||||
$logger->write($message, $category);
|
||||
}
|
||||
|
||||
/**
|
||||
* @param $name
|
||||
* @return mixed
|
||||
* @throws Exception
|
||||
*/
|
||||
public function __get($name): mixed
|
||||
{
|
||||
if (method_exists($this, $name)) {
|
||||
return $this->{$name}();
|
||||
}
|
||||
$handler = 'get' . ucfirst($name);
|
||||
if (method_exists($this, $handler)) {
|
||||
return $this->{$handler}();
|
||||
}
|
||||
if (property_exists($this, $name)) {
|
||||
return $this->$name;
|
||||
}
|
||||
$message = sprintf('method %s::%s not exists.', static::class, $name);
|
||||
throw new Exception($message);
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,79 @@
|
||||
<?php
|
||||
|
||||
|
||||
namespace Http\Handler\Abstracts;
|
||||
|
||||
|
||||
use Closure;
|
||||
use Kiri\Abstracts\BaseObject;
|
||||
|
||||
|
||||
/**
|
||||
* Class MiddlewareManager
|
||||
* @package Http\Route
|
||||
*/
|
||||
class MiddlewareManager extends BaseObject
|
||||
{
|
||||
|
||||
private static array $_middlewares = [];
|
||||
|
||||
|
||||
/**
|
||||
* @param $class
|
||||
* @param $method
|
||||
* @param array|string $middlewares
|
||||
* @return bool
|
||||
*/
|
||||
public static function add($class, $method, array|string $middlewares): bool
|
||||
{
|
||||
if (is_object($class)) {
|
||||
$class = $class::class;
|
||||
}
|
||||
if (!isset(static::$_middlewares[$class . '::' . $method])) {
|
||||
static::$_middlewares[$class . '::' . $method] = [];
|
||||
}
|
||||
if (is_string($middlewares) && !in_array($middlewares, static::$_middlewares[$class . '::' . $method])) {
|
||||
static::$_middlewares[$class . '::' . $method][] = $middlewares;
|
||||
} else {
|
||||
foreach ($middlewares as $middleware) {
|
||||
if (in_array($middleware, static::$_middlewares[$class . '::' . $method])) {
|
||||
continue;
|
||||
}
|
||||
static::$_middlewares[$class . '::' . $method][] = $middleware;
|
||||
}
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* @param $handler
|
||||
* @return mixed
|
||||
*/
|
||||
public static function get($handler): mixed
|
||||
{
|
||||
if ($handler instanceof Closure) {
|
||||
return null;
|
||||
}
|
||||
[$class, $method] = [$handler[0], $handler[1]];
|
||||
if (!static::hasMiddleware($class, $method)) {
|
||||
return null;
|
||||
}
|
||||
return static::$_middlewares[$class . '::' . $method];
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* @param $class
|
||||
* @param $method
|
||||
* @return bool
|
||||
*/
|
||||
public static function hasMiddleware($class, $method): bool
|
||||
{
|
||||
if (is_object($class)) {
|
||||
$class = $class::class;
|
||||
}
|
||||
return isset(static::$_middlewares[$class . '::' . $method]);
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,25 @@
|
||||
<?php
|
||||
declare(strict_types=1);
|
||||
|
||||
|
||||
namespace Http\Handler;
|
||||
|
||||
|
||||
/**
|
||||
* Interface AuthIdentity
|
||||
* @package Kiri\Kiri\Http
|
||||
*/
|
||||
interface AuthIdentity
|
||||
{
|
||||
|
||||
|
||||
public function getIdentity();
|
||||
|
||||
|
||||
/**
|
||||
* @return string|int
|
||||
* 获取唯一识别码
|
||||
*/
|
||||
public function getUniqueId(): string|int;
|
||||
|
||||
}
|
||||
@@ -0,0 +1,148 @@
|
||||
<?php
|
||||
/**
|
||||
* Created by PhpStorm.
|
||||
* User: whwyy
|
||||
* Date: 2018/5/24 0024
|
||||
* Time: 11:34
|
||||
*/
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace Http\Client;
|
||||
|
||||
use Exception;
|
||||
use JetBrains\PhpStorm\Pure;
|
||||
use Swoole\Coroutine\Http\Client as SClient;
|
||||
|
||||
/**
|
||||
* Class Client
|
||||
* @package Kiri\Kiri\Http
|
||||
*/
|
||||
class Client extends ClientAbstracts
|
||||
{
|
||||
|
||||
/**
|
||||
* @param string $method
|
||||
* @param $path
|
||||
* @param array $params
|
||||
* @return array|string|Result
|
||||
* @throws Exception
|
||||
*/
|
||||
public function request(string $method, $path, array $params = []): array|string|Result
|
||||
{
|
||||
return $this->setMethod($method)
|
||||
->coroutine(
|
||||
$this->matchHost($path),
|
||||
$this->paramEncode($params)
|
||||
);
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* @param $url
|
||||
* @param array|string $data
|
||||
* @return array|string|Result
|
||||
* @throws Exception 使用swoole协程方式请求
|
||||
*/
|
||||
private function coroutine($url, array|string $data = []): array|string|Result
|
||||
{
|
||||
try {
|
||||
$client = $this->generate_client($data, ...$url);
|
||||
$this->setData('');
|
||||
if ($client->statusCode < 0) {
|
||||
throw new Exception($client->errMsg);
|
||||
}
|
||||
$body = $this->resolve($client->getHeaders(), $client->body);
|
||||
if (in_array($client->getStatusCode(), [200, 201])) {
|
||||
return $this->structure($body, $data, $client->getHeaders());
|
||||
}
|
||||
if (is_string($body)) {
|
||||
$message = 'Request error code ' . $client->getStatusCode();
|
||||
} else {
|
||||
$message = $this->searchMessageByData($body);
|
||||
}
|
||||
return $this->fail($client->getStatusCode(), $message, $body, $client->getHeaders());
|
||||
} catch (\Throwable $exception) {
|
||||
$this->addError($exception, 'rpc');
|
||||
return $this->fail(500, $exception->getMessage(), [
|
||||
'file' => $exception->getFile(),
|
||||
'line' => $exception->getLine()
|
||||
], []);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* @param $data
|
||||
* @param $host
|
||||
* @param $isHttps
|
||||
* @param $path
|
||||
* @return SClient
|
||||
*/
|
||||
private function generate_client($data, $host, $isHttps, $path): SClient
|
||||
{
|
||||
if ($isHttps || $this->isSSL()) {
|
||||
$client = new SClient($host, 443, true);
|
||||
} else {
|
||||
$client = new SClient($host, $this->getPort(), false);
|
||||
}
|
||||
$client->set($this->settings());
|
||||
if (!empty($this->getAgent())) {
|
||||
$this->addHeader('User-Agent', $this->getAgent());
|
||||
}
|
||||
$client->setHeaders($this->getHeader());
|
||||
$client->setMethod(strtoupper($this->getMethod()));
|
||||
$client->execute($this->setParams($client, $path, $data));
|
||||
$client->close();
|
||||
return $client;
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* @param SClient $client
|
||||
* @param $path
|
||||
* @param $data
|
||||
* @return string
|
||||
*/
|
||||
private function setParams(SClient $client, $path, $data): string
|
||||
{
|
||||
if ($this->isGet()) {
|
||||
if (!empty($data)) $path .= '?' . $data;
|
||||
if (!empty($this->getData())) {
|
||||
$client->setData($this->getData());
|
||||
}
|
||||
} else {
|
||||
if (!empty($this->getData())) {
|
||||
$client->setData($this->getData());
|
||||
} else {
|
||||
$client->setData($this->mergeParams($data));
|
||||
}
|
||||
}
|
||||
return $path;
|
||||
}
|
||||
|
||||
/**
|
||||
* @return array
|
||||
*/
|
||||
#[Pure] private function settings(): array
|
||||
{
|
||||
$sslCert = $this->getSslCertFile();
|
||||
$sslKey = $this->getSslKeyFile();
|
||||
$sslCa = $this->getCa();
|
||||
|
||||
$params = [];
|
||||
if ($this->getConnectTimeout() > 0) {
|
||||
$params['timeout'] = $this->getConnectTimeout();
|
||||
}
|
||||
if (empty($sslCert) || empty($sslKey) || empty($sslCa)) {
|
||||
return $params;
|
||||
}
|
||||
|
||||
$params['ssl_host_name'] = $this->getHost();
|
||||
$params['ssl_cert_file'] = $this->getSslCertFile();
|
||||
$params['ssl_key_file'] = $this->getSslKeyFile();
|
||||
$params['ssl_verify_peer'] = true;
|
||||
$params['ssl_cafile'] = $sslCa;
|
||||
|
||||
return $params;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,806 @@
|
||||
<?php
|
||||
|
||||
|
||||
namespace Http\Client;
|
||||
|
||||
|
||||
use Closure;
|
||||
use JetBrains\PhpStorm\Pure;
|
||||
use Kiri\Abstracts\Component;
|
||||
use Kiri\Core\Help;
|
||||
use Swoole\Coroutine\System;
|
||||
|
||||
defined('SPLIT_URL') or define('SPLIT_URL', '/(http[s]?:\/\/)?(([\w\-_]+\.)+\w+(:\d+)?)((\/[a-zA-Z0-9\-]+)+[\/]?(\?[a-zA-Z]+=.*)?)?/');
|
||||
|
||||
|
||||
/**
|
||||
* Class ClientAbstracts
|
||||
* @package Http\Client
|
||||
*/
|
||||
abstract class ClientAbstracts extends Component implements IClient
|
||||
{
|
||||
|
||||
const POST = 'post';
|
||||
const UPLOAD = 'upload';
|
||||
const GET = 'get';
|
||||
const DELETE = 'delete';
|
||||
const OPTIONS = 'options';
|
||||
const HEAD = 'head';
|
||||
const PUT = 'put';
|
||||
|
||||
private string $host = '';
|
||||
|
||||
private array $header = [];
|
||||
|
||||
private int $timeout = 0;
|
||||
|
||||
private ?Closure $callback = null;
|
||||
private string $method = 'get';
|
||||
|
||||
private bool $isSSL = false;
|
||||
private string $agent = '';
|
||||
private string $errorCodeField = '';
|
||||
private string $errorMsgField = '';
|
||||
private bool $use_swoole = false;
|
||||
|
||||
private string $ssl_cert_file = '';
|
||||
private string $ssl_key_file = '';
|
||||
private string $ca = '';
|
||||
private int $port = 80;
|
||||
|
||||
/** @var string $_message 错误信息 */
|
||||
private string $_message = '';
|
||||
private string $_data = '';
|
||||
|
||||
private int $connect_timeout = 1;
|
||||
|
||||
|
||||
/**
|
||||
* @return static
|
||||
*/
|
||||
#[Pure] public static function NewRequest(): static
|
||||
{
|
||||
return new static();
|
||||
}
|
||||
|
||||
|
||||
protected function cleanData(): void
|
||||
{
|
||||
$this->_data = '';
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* @param string $path
|
||||
* @param array $params
|
||||
* @return array|int|string|Result
|
||||
*/
|
||||
public function post(string $path, array $params = []): array|int|string|Result
|
||||
{
|
||||
return $this->request(self::POST, $path, $params);
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* @param string $path
|
||||
* @param array $params
|
||||
* @return array|int|string|Result
|
||||
*/
|
||||
public function put(string $path, array $params = []): array|int|string|Result
|
||||
{
|
||||
return $this->request(self::PUT, $path, $params);
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* @param string $contentType
|
||||
*/
|
||||
public function setContentType(string $contentType): void
|
||||
{
|
||||
$this->header['Content-Type'] = $contentType;
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* @param string $path
|
||||
* @param array $params
|
||||
* @return array|int|string|Result
|
||||
*/
|
||||
public function head(string $path, array $params = []): array|int|string|Result
|
||||
{
|
||||
return $this->request(self::HEAD, $path, $params);
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* @param string $path
|
||||
* @param array $params
|
||||
* @return array|int|string|Result
|
||||
*/
|
||||
public function get(string $path, array $params = []): array|int|string|Result
|
||||
{
|
||||
return $this->request(self::GET, $path, $params);
|
||||
}
|
||||
|
||||
/**
|
||||
* @param string $path
|
||||
* @param array $params
|
||||
* @return array|int|string|Result
|
||||
*/
|
||||
public function option(string $path, array $params = []): array|int|string|Result
|
||||
{
|
||||
return $this->request(self::OPTIONS, $path, $params);
|
||||
}
|
||||
|
||||
/**
|
||||
* @param string $path
|
||||
* @param array $params
|
||||
* @return array|int|string|Result
|
||||
*/
|
||||
public function delete(string $path, array $params = []): array|int|string|Result
|
||||
{
|
||||
return $this->request(self::DELETE, $path, $params);
|
||||
}
|
||||
|
||||
/**
|
||||
* @param string $path
|
||||
* @param array $params
|
||||
* @return array|int|string|Result
|
||||
*/
|
||||
public function options(string $path, array $params = []): array|int|string|Result
|
||||
{
|
||||
return $this->request(self::OPTIONS, $path, $params);
|
||||
|
||||
}
|
||||
|
||||
/**
|
||||
* @param string $path
|
||||
* @param array $params
|
||||
* @return array|int|string|Result
|
||||
*/
|
||||
public function upload(string $path, array $params = []): array|int|string|Result
|
||||
{
|
||||
return $this->request(self::UPLOAD, $path, $params);
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* @return string
|
||||
*/
|
||||
public function getHost(): string
|
||||
{
|
||||
return $this->host;
|
||||
}
|
||||
|
||||
/**
|
||||
* @return int
|
||||
*/
|
||||
protected function getHostPort(): int
|
||||
{
|
||||
if (!empty($this->getPort())) {
|
||||
return $this->getPort();
|
||||
}
|
||||
$port = 80;
|
||||
if ($this->isSSL()) $port = 443;
|
||||
return $port;
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* @param string $host
|
||||
*/
|
||||
public function setHost(string $host): void
|
||||
{
|
||||
$this->host = $host;
|
||||
if ($this->use_swoole) {
|
||||
$this->host = System::gethostbyname($host);
|
||||
}
|
||||
$this->addHeader('Host', $host);
|
||||
}
|
||||
|
||||
/**
|
||||
* @return array
|
||||
*/
|
||||
public function getHeader(): array
|
||||
{
|
||||
return $this->header;
|
||||
}
|
||||
|
||||
/**
|
||||
* @param array $header
|
||||
*/
|
||||
public function setHeader(array $header): void
|
||||
{
|
||||
$this->header = $header;
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* @param array $header
|
||||
* @return array
|
||||
*/
|
||||
public function setHeaders(array $header): array
|
||||
{
|
||||
if (empty($header)) {
|
||||
return [];
|
||||
}
|
||||
foreach ($header as $key => $val) {
|
||||
$this->header[$key] = $val;
|
||||
}
|
||||
return $this->header;
|
||||
}
|
||||
|
||||
/**
|
||||
* @param $key
|
||||
* @param $value
|
||||
*/
|
||||
public function addHeader($key, $value): void
|
||||
{
|
||||
$this->header[$key] = $value;
|
||||
}
|
||||
|
||||
/**
|
||||
* @return int
|
||||
*/
|
||||
public function getTimeout(): int
|
||||
{
|
||||
return $this->timeout;
|
||||
}
|
||||
|
||||
/**
|
||||
* @param int $value
|
||||
*/
|
||||
public function setTimeout(int $value): void
|
||||
{
|
||||
$this->timeout = $value;
|
||||
}
|
||||
|
||||
/**
|
||||
* @return Closure|null
|
||||
*/
|
||||
public function getCallback(): ?Closure
|
||||
{
|
||||
return $this->callback;
|
||||
}
|
||||
|
||||
/**
|
||||
* @param Closure|null $value
|
||||
*/
|
||||
public function setCallback(?Closure $value): void
|
||||
{
|
||||
$this->callback = $value;
|
||||
}
|
||||
|
||||
/**
|
||||
* @return string
|
||||
*/
|
||||
public function getMethod(): string
|
||||
{
|
||||
return $this->method;
|
||||
}
|
||||
|
||||
/**
|
||||
* @param string $value
|
||||
* @return static
|
||||
*/
|
||||
public function setMethod(string $value): static
|
||||
{
|
||||
$this->method = $value;
|
||||
return $this;
|
||||
}
|
||||
|
||||
/**
|
||||
* @return bool
|
||||
*/
|
||||
public function isSSL(): bool
|
||||
{
|
||||
return $this->isSSL;
|
||||
}
|
||||
|
||||
/**
|
||||
* @param bool $isSSL
|
||||
*/
|
||||
public function setIsSSL(bool $isSSL): void
|
||||
{
|
||||
$this->isSSL = $isSSL;
|
||||
}
|
||||
|
||||
/**
|
||||
* @return string
|
||||
*/
|
||||
public function getAgent(): string
|
||||
{
|
||||
return $this->agent;
|
||||
}
|
||||
|
||||
/**
|
||||
* @param string $agent
|
||||
*/
|
||||
public function setAgent(string $agent): void
|
||||
{
|
||||
$this->agent = $agent;
|
||||
}
|
||||
|
||||
/**
|
||||
* @return string
|
||||
*/
|
||||
public function getErrorCodeField(): string
|
||||
{
|
||||
return $this->errorCodeField;
|
||||
}
|
||||
|
||||
/**
|
||||
* @param string $errorCodeField
|
||||
*/
|
||||
public function setErrorCodeField(string $errorCodeField): void
|
||||
{
|
||||
$this->errorCodeField = $errorCodeField;
|
||||
}
|
||||
|
||||
/**
|
||||
* @return string
|
||||
*/
|
||||
public function getErrorMsgField(): string
|
||||
{
|
||||
return $this->errorMsgField;
|
||||
}
|
||||
|
||||
/**
|
||||
* @param string $errorMsgField
|
||||
*/
|
||||
public function setErrorMsgField(string $errorMsgField): void
|
||||
{
|
||||
$this->errorMsgField = $errorMsgField;
|
||||
}
|
||||
|
||||
/**
|
||||
* @return bool
|
||||
*/
|
||||
public function isUseSwoole(): bool
|
||||
{
|
||||
return $this->use_swoole;
|
||||
}
|
||||
|
||||
/**
|
||||
* @param bool $use_swoole
|
||||
*/
|
||||
public function setUseSwoole(bool $use_swoole): void
|
||||
{
|
||||
$this->use_swoole = $use_swoole;
|
||||
}
|
||||
|
||||
/**
|
||||
* @return string
|
||||
*/
|
||||
public function getSslCertFile(): string
|
||||
{
|
||||
return $this->ssl_cert_file;
|
||||
}
|
||||
|
||||
/**
|
||||
* @param string $ssl_cert_file
|
||||
*/
|
||||
public function setSslCertFile(string $ssl_cert_file): void
|
||||
{
|
||||
$this->ssl_cert_file = $ssl_cert_file;
|
||||
}
|
||||
|
||||
/**
|
||||
* @return string
|
||||
*/
|
||||
public function getSslKeyFile(): string
|
||||
{
|
||||
return $this->ssl_key_file;
|
||||
}
|
||||
|
||||
/**
|
||||
* @param string $ssl_key_file
|
||||
*/
|
||||
public function setSslKeyFile(string $ssl_key_file): void
|
||||
{
|
||||
$this->ssl_key_file = $ssl_key_file;
|
||||
}
|
||||
|
||||
/**
|
||||
* @return string
|
||||
*/
|
||||
public function getCa(): string
|
||||
{
|
||||
return $this->ca;
|
||||
}
|
||||
|
||||
/**
|
||||
* @param string $ssl_key_file
|
||||
*/
|
||||
public function setCa(string $ssl_key_file): void
|
||||
{
|
||||
$this->ca = $ssl_key_file;
|
||||
}
|
||||
|
||||
/**
|
||||
* @return int
|
||||
*/
|
||||
public function getPort(): int
|
||||
{
|
||||
if ($this->isSSL()) {
|
||||
return 443;
|
||||
}
|
||||
if (empty($this->port)) {
|
||||
return 80;
|
||||
}
|
||||
return $this->port;
|
||||
}
|
||||
|
||||
/**
|
||||
* @param int $port
|
||||
*/
|
||||
public function setPort(int $port): void
|
||||
{
|
||||
$this->port = $port;
|
||||
}
|
||||
|
||||
/**
|
||||
* @return string
|
||||
*/
|
||||
public function getMessage(): string
|
||||
{
|
||||
return $this->_message;
|
||||
}
|
||||
|
||||
/**
|
||||
* @param string $message
|
||||
*/
|
||||
public function setMessage(string $message): void
|
||||
{
|
||||
$this->_message = $message;
|
||||
}
|
||||
|
||||
/**
|
||||
* @return string
|
||||
*/
|
||||
public function getData(): string
|
||||
{
|
||||
return $this->_data;
|
||||
}
|
||||
|
||||
/**
|
||||
* @param string $data
|
||||
*/
|
||||
public function setData(string $data): void
|
||||
{
|
||||
$this->_data = $data;
|
||||
}
|
||||
|
||||
/**
|
||||
* @return int
|
||||
*/
|
||||
public function getConnectTimeout(): int
|
||||
{
|
||||
return $this->connect_timeout;
|
||||
}
|
||||
|
||||
/**
|
||||
* @param int $connect_timeout
|
||||
*/
|
||||
public function setConnectTimeout(int $connect_timeout): void
|
||||
{
|
||||
$this->connect_timeout = $connect_timeout;
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* @param $host
|
||||
* @return string|string[]
|
||||
*/
|
||||
protected function replaceHost($host): array|string
|
||||
{
|
||||
if ($this->isHttp($host)) {
|
||||
return str_replace('http://', '', $host);
|
||||
}
|
||||
if ($this->isHttps($host)) {
|
||||
return str_replace('https://', '', $host);
|
||||
}
|
||||
return $host;
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* @param $url
|
||||
* @return false|int
|
||||
*/
|
||||
protected function checkIsIp($url): bool|int
|
||||
{
|
||||
return preg_match('/\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}/', $url);
|
||||
}
|
||||
|
||||
/**
|
||||
* @param $url
|
||||
* @return bool
|
||||
*/
|
||||
#[Pure] protected function isHttp($url): bool
|
||||
{
|
||||
return str_starts_with($url, 'http://');
|
||||
}
|
||||
|
||||
/**
|
||||
* @param $url
|
||||
* @return bool
|
||||
*/
|
||||
#[Pure] protected function isHttps($url): bool
|
||||
{
|
||||
return str_starts_with($url, 'https://');
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* @param $newData
|
||||
* @return string
|
||||
*/
|
||||
protected function mergeParams($newData): string
|
||||
{
|
||||
if (!is_string($newData)) {
|
||||
return $this->toRequest($newData);
|
||||
}
|
||||
return $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
|
||||
*/
|
||||
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;
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* @param $body
|
||||
* @param $_data
|
||||
* @param array $header
|
||||
* @param int $statusCode
|
||||
* @return mixed 构建返回体
|
||||
* 构建返回体
|
||||
*/
|
||||
protected function structure($body, $_data, $header = [], $statusCode = 200): mixed
|
||||
{
|
||||
if ($this->callback instanceof Closure) {
|
||||
$result = call_user_func($this->callback, $body, $_data, $header);
|
||||
} else {
|
||||
$result = $this->parseResult($body, $header, $statusCode);
|
||||
}
|
||||
return $result;
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* @param $body
|
||||
* @param $header
|
||||
* @param $statusCode
|
||||
* @return Result
|
||||
*/
|
||||
private function parseResult($body, $header, $statusCode): Result
|
||||
{
|
||||
if (is_string($body)) {
|
||||
$result['code'] = 0;
|
||||
$result['message'] = '';
|
||||
} else {
|
||||
$result['code'] = $body[$this->errorCodeField] ?? 0;
|
||||
$result['message'] = $this->searchMessageByData($body);
|
||||
}
|
||||
$result['data'] = $body;
|
||||
$result['header'] = $header;
|
||||
$result['httpStatus'] = $statusCode;
|
||||
return new Result($result);
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* @param $body
|
||||
* @return mixed
|
||||
*/
|
||||
protected function searchMessageByData($body): mixed
|
||||
{
|
||||
$parent = [];
|
||||
if (empty($this->errorMsgField)) {
|
||||
return 'system success.';
|
||||
}
|
||||
$explode = explode('.', $this->errorMsgField);
|
||||
if (!isset($body[$explode[0]])) {
|
||||
return 'system success.';
|
||||
}
|
||||
foreach ($explode as $item) {
|
||||
if (empty($item)) {
|
||||
continue;
|
||||
}
|
||||
if (empty($parent)) {
|
||||
$parent = $body[$item];
|
||||
continue;
|
||||
}
|
||||
if (is_string($parent) || !isset($parent[$item])) {
|
||||
break;
|
||||
}
|
||||
$parent = $parent[$item];
|
||||
}
|
||||
return !empty($parent) ? $parent : 'system success.';
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* @return bool
|
||||
* check isPost Request
|
||||
*/
|
||||
#[Pure] public function isPost(): bool
|
||||
{
|
||||
return strtolower($this->method) === self::POST;
|
||||
}
|
||||
|
||||
/**
|
||||
* @return bool
|
||||
* check isPost Request
|
||||
*/
|
||||
#[Pure] public function isUpload(): bool
|
||||
{
|
||||
return strtolower($this->method) === self::UPLOAD;
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* @return bool
|
||||
*
|
||||
* check isGet Request
|
||||
*/
|
||||
#[Pure] public function isGet(): bool
|
||||
{
|
||||
return strtolower($this->method) === self::GET;
|
||||
}
|
||||
|
||||
/**
|
||||
* @param $arr
|
||||
*
|
||||
* @return array|string
|
||||
* 将请求参数进行编码
|
||||
*/
|
||||
#[Pure] protected function paramEncode($arr): array|string
|
||||
{
|
||||
if (!is_array($arr)) {
|
||||
return $arr;
|
||||
}
|
||||
$_tmp = [];
|
||||
foreach ($arr as $Key => $val) {
|
||||
$_tmp[$Key] = $val;
|
||||
}
|
||||
if ($this->isGet()) {
|
||||
return http_build_query($_tmp);
|
||||
}
|
||||
return $_tmp;
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* @param string $string
|
||||
* @return array
|
||||
*/
|
||||
protected function matchHost(string $string): array
|
||||
{
|
||||
if (($parse = isUrl($string, true)) === false) {
|
||||
return $this->defaultString($string);
|
||||
}
|
||||
[$isHttps, $domain, $port, $path] = $parse;
|
||||
if (str_contains($domain, ':' . $port)) {
|
||||
$domain = str_replace(':' . $port, '', $domain);
|
||||
}
|
||||
$this->port = $isHttps ? 443 : $this->port;
|
||||
if (isIp($domain)) {
|
||||
$this->host = $domain;
|
||||
} else if ($this->isUseSwoole()) {
|
||||
$this->host = System::gethostbyname($domain) ?? $domain;
|
||||
} else {
|
||||
$this->host = $domain;
|
||||
}
|
||||
$this->header['Host'] = $domain;
|
||||
if (!str_starts_with($path, '/')) {
|
||||
$path = '/' . $path;
|
||||
}
|
||||
return [$this->host, $isHttps, $path];
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* @param $string
|
||||
* @return array
|
||||
*/
|
||||
private function defaultString($string): array
|
||||
{
|
||||
$host = $this->getHost();
|
||||
if ($string == '/') {
|
||||
$string = '';
|
||||
} else if (strpos($string, '/') !== 0) {
|
||||
$string = '/' . $string;
|
||||
}
|
||||
return [$host, $this->isSSL(), $string];
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* @param $path
|
||||
* @param $params
|
||||
* @return string
|
||||
*/
|
||||
#[Pure] protected function joinGetParams($path, $params): string
|
||||
{
|
||||
if (empty($params)) {
|
||||
return $path;
|
||||
}
|
||||
if (!is_string($params)) {
|
||||
$params = http_build_query($params);
|
||||
}
|
||||
if (str_contains($path, '?')) {
|
||||
[$path, $getParams] = explode('?', $path);
|
||||
}
|
||||
if (!isset($getParams) || empty($getParams)) {
|
||||
return $path . '?' . $params;
|
||||
}
|
||||
return $path . '?' . $params . '&' . $getParams;
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* @param $code
|
||||
* @param $message
|
||||
* @param $data
|
||||
* @param $header
|
||||
* @return Result
|
||||
*/
|
||||
protected function fail($code, $message, $data = [], $header = []): Result
|
||||
{
|
||||
return new Result([
|
||||
'code' => $code,
|
||||
'message' => $message,
|
||||
'data' => $data,
|
||||
'header' => $header,
|
||||
]);
|
||||
}
|
||||
|
||||
|
||||
}
|
||||
@@ -0,0 +1,224 @@
|
||||
<?php
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace Http\Client;
|
||||
|
||||
|
||||
use CurlHandle;
|
||||
use Exception;
|
||||
use JetBrains\PhpStorm\Pure;
|
||||
|
||||
|
||||
/**
|
||||
* Class Curl
|
||||
* @package Http\Client
|
||||
*/
|
||||
class Curl extends ClientAbstracts
|
||||
{
|
||||
|
||||
/**
|
||||
* @param $method
|
||||
* @param $path
|
||||
* @param array $params
|
||||
* @return Result|array|string
|
||||
* @throws Exception
|
||||
*/
|
||||
public function request($method, $path, array $params = []): Result|array|string
|
||||
{
|
||||
if ($method == self::GET) {
|
||||
$path = $this->joinGetParams($path, $params);
|
||||
}
|
||||
return $this->execute($this->getCurlHandler($path, $method, $params));
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* @param $path
|
||||
* @param $method
|
||||
* @param $params
|
||||
* @return CurlHandle
|
||||
* @throws Exception
|
||||
*/
|
||||
private function getCurlHandler($path, $method, $params): CurlHandle
|
||||
{
|
||||
[$host, $isHttps, $path] = $this->matchHost($path);
|
||||
|
||||
$host = $isHttps ? 'https://' . $host : 'http://' . $host;
|
||||
if ($this->getPort() != 443 && $this->getPort() != 80) {
|
||||
$host .= ':' . $this->getPort();
|
||||
}
|
||||
|
||||
$resource = $this->do(curl_init($host . $path), $host . $path, $method);
|
||||
if ($isHttps !== false) {
|
||||
$this->curlHandlerSslSet($resource);
|
||||
}
|
||||
if (empty($params) && empty($this->getData())) {
|
||||
return $resource;
|
||||
}
|
||||
|
||||
if (!empty($this->getData())) {
|
||||
curl_setopt($resource, CURLOPT_POSTFIELDS, $this->getData());
|
||||
} else if ($method === self::POST) {
|
||||
curl_setopt($resource, CURLOPT_POSTFIELDS, $this->mergeParams($params));
|
||||
} else if ($method === self::UPLOAD) {
|
||||
curl_setopt($resource, CURLOPT_POSTFIELDS, $params);
|
||||
}
|
||||
return $resource;
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* @param $resource
|
||||
* @return void
|
||||
* @throws Exception
|
||||
*/
|
||||
private function curlHandlerSslSet($resource): void
|
||||
{
|
||||
if (!empty($this->ssl_key)) {
|
||||
if (!file_exists($this->ssl_key)) {
|
||||
throw new Exception('SSL protocol certificate not found.');
|
||||
}
|
||||
curl_setopt($resource, CURLOPT_SSLKEY, $this->getSslKeyFile());
|
||||
}
|
||||
if (!empty($this->ssl_cert)) {
|
||||
if (!!file_exists($this->ssl_cert)) {
|
||||
throw new Exception('SSL protocol certificate not found.');
|
||||
}
|
||||
curl_setopt($resource, CURLOPT_SSLCERT, $this->getSslCertFile());
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* @param $resource
|
||||
* @param $path
|
||||
* @param $method
|
||||
* @return CurlHandle
|
||||
* @throws Exception
|
||||
*/
|
||||
private function do($resource, $path, $method): CurlHandle
|
||||
{
|
||||
curl_setopt($resource, CURLOPT_URL, $path);
|
||||
curl_setopt($resource, CURLOPT_TIMEOUT, $this->getTimeout()); // 超时设置
|
||||
curl_setopt($resource, CURLOPT_CONNECTTIMEOUT, $this->getConnectTimeout()); // 超时设置
|
||||
|
||||
curl_setopt($resource, CURLOPT_HEADER, true);
|
||||
curl_setopt($resource, CURLOPT_FAILONERROR, true);
|
||||
|
||||
curl_setopt($resource, CURLOPT_HTTPHEADER, $this->parseHeaderMat());
|
||||
if (defined('CURLOPT_SSL_FALSESTART')) {
|
||||
curl_setopt($resource, CURLOPT_SSL_FALSESTART, true);
|
||||
}
|
||||
curl_setopt($resource, CURLOPT_FORBID_REUSE, false);
|
||||
curl_setopt($resource, CURLOPT_FRESH_CONNECT, false);
|
||||
|
||||
if (!empty($this->getAgent())) {
|
||||
curl_setopt($resource, CURLOPT_USERAGENT, $this->getAgent());
|
||||
}
|
||||
|
||||
curl_setopt($resource, CURLOPT_NOBODY, FALSE);
|
||||
curl_setopt($resource, CURLOPT_RETURNTRANSFER, TRUE);//返回内容
|
||||
curl_setopt($resource, CURLOPT_FOLLOWLOCATION, TRUE);// 跟踪重定向
|
||||
curl_setopt($resource, CURLOPT_ENCODING, 'gzip,deflate');
|
||||
if ($method === self::POST || $method == self::UPLOAD) {
|
||||
curl_setopt($resource, CURLOPT_POST, 1);
|
||||
}
|
||||
curl_setopt($resource, CURLOPT_CUSTOMREQUEST, strtoupper($method));
|
||||
|
||||
return $resource;
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* @param $curl
|
||||
* @return Result|bool|array|string
|
||||
* @throws Exception
|
||||
*/
|
||||
private function execute($curl): Result|bool|array|string
|
||||
{
|
||||
$output = curl_exec($curl);
|
||||
if ($output === false) {
|
||||
$response = $this->fail(400, curl_error($curl));
|
||||
} else {
|
||||
$response = $this->parseResponse($curl, $output);
|
||||
}
|
||||
$this->cleanData();
|
||||
return $response;
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* @param $curl
|
||||
* @param $output
|
||||
* @param array $params
|
||||
* @return mixed
|
||||
* @throws Exception
|
||||
*/
|
||||
private function parseResponse($curl, $output, array $params = []): mixed
|
||||
{
|
||||
curl_close($curl);
|
||||
if ($output === FALSE) {
|
||||
return $this->fail(500, $output);
|
||||
}
|
||||
[$header, $body, $status] = $this->explode($output);
|
||||
if ($status != 200 && $status != 201) {
|
||||
$data = $this->fail($status, $body, [], $header);
|
||||
} else {
|
||||
$data = $this->structure($body, $params, $header);
|
||||
}
|
||||
return $data;
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* @param $output
|
||||
* @return array
|
||||
* @throws Exception
|
||||
*/
|
||||
private function explode($output): array
|
||||
{
|
||||
if (empty($output) || !str_contains($output, "\r\n\r\n")) {
|
||||
throw new Exception('Get data null.');
|
||||
}
|
||||
|
||||
[$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 = (int)explode(' ', trim($header[0]))[1];
|
||||
$header = $this->headerFormat($header);
|
||||
|
||||
return [$header, $this->resolve($header, $body), $status];
|
||||
}
|
||||
|
||||
/**
|
||||
* @param $headers
|
||||
* @return array
|
||||
*/
|
||||
private function headerFormat($headers): array
|
||||
{
|
||||
$_tmp = [];
|
||||
foreach ($headers as $val) {
|
||||
$trim = explode(': ', trim($val));
|
||||
|
||||
$_tmp[strtolower($trim[0])] = $trim[1] ?? '';
|
||||
}
|
||||
return $_tmp;
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* @return array
|
||||
*/
|
||||
#[Pure] private function parseHeaderMat(): array
|
||||
{
|
||||
$headers = [];
|
||||
foreach ($this->getHeader() as $key => $val) {
|
||||
$headers[$key] = $key . ': ' . $val;
|
||||
}
|
||||
return array_values($headers);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,64 @@
|
||||
<?php
|
||||
|
||||
|
||||
namespace Http\Client;
|
||||
|
||||
|
||||
use JetBrains\PhpStorm\Pure;
|
||||
use Kiri\Abstracts\Component;
|
||||
use ReflectionException;
|
||||
use Swoole\Coroutine;
|
||||
|
||||
/**
|
||||
* Class ClientDriver
|
||||
* @package Http\Client
|
||||
* @mixin Client
|
||||
*/
|
||||
class HttpClient extends Component
|
||||
{
|
||||
|
||||
/**
|
||||
* @return IClient
|
||||
*/
|
||||
public static function NewRequest(): IClient
|
||||
{
|
||||
if (Coroutine::getCid() > -1) {
|
||||
return Client::NewRequest();
|
||||
}
|
||||
return Curl::NewRequest();
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* @return Curl
|
||||
*/
|
||||
#[Pure] public function getCurl(): Curl
|
||||
{
|
||||
return Curl::NewRequest();
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* @return Client
|
||||
*/
|
||||
#[Pure] public function getCoroutine(): Client
|
||||
{
|
||||
return Client::NewRequest();
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* @param string $name
|
||||
* @param array $arguments
|
||||
* @return void
|
||||
*/
|
||||
public function __call(string $name, array $arguments)
|
||||
{
|
||||
if (!method_exists($this, $name)) {
|
||||
return static::NewRequest()->{$name}(...$arguments);
|
||||
}
|
||||
return $this->{$name}(...$arguments);
|
||||
}
|
||||
|
||||
|
||||
}
|
||||
@@ -0,0 +1,109 @@
|
||||
<?php
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace Http\Client;
|
||||
|
||||
use Exception;
|
||||
|
||||
/**
|
||||
* Class HttpParse
|
||||
* @package BeReborn\Http
|
||||
*/
|
||||
class HttpParse
|
||||
{
|
||||
/**
|
||||
* @param mixed ...$object
|
||||
* @return string
|
||||
*/
|
||||
private static function getKey(...$object): string
|
||||
{
|
||||
$first = '';
|
||||
$tp = [];
|
||||
foreach ($object as $key => $value) {
|
||||
if ($value === null) {
|
||||
continue;
|
||||
}
|
||||
if (is_array($value)) {
|
||||
$value = key($value);
|
||||
}
|
||||
if ($first === '') {
|
||||
$first = $value;
|
||||
} else {
|
||||
$tp[] = $value;
|
||||
}
|
||||
}
|
||||
$key = $first . '[' . implode('][', $tp) . ']';
|
||||
if (count($tp) < 1) {
|
||||
$key = $first;
|
||||
}
|
||||
return $key;
|
||||
}
|
||||
|
||||
/**
|
||||
* @param $data
|
||||
* @return string
|
||||
* @throws Exception
|
||||
*/
|
||||
public static function parse($data): string
|
||||
{
|
||||
$tmp = [];
|
||||
if (is_string($data)) {
|
||||
return $data;
|
||||
}
|
||||
foreach ($data as $key => $datum) {
|
||||
if ($datum === null) {
|
||||
continue;
|
||||
}
|
||||
$tmp[] = static::ifElse($key, $datum);
|
||||
}
|
||||
return implode('&', $tmp);
|
||||
}
|
||||
|
||||
/**
|
||||
* @param $t
|
||||
* @param $qt
|
||||
* @return string
|
||||
* @throws Exception
|
||||
*/
|
||||
private static function ifElse($t, $qt): string
|
||||
{
|
||||
if (is_numeric($qt)) {
|
||||
return $t . '=' . $qt;
|
||||
}
|
||||
if (is_string($qt)) {
|
||||
$string = $t . '=' . urlencode($qt);
|
||||
} else {
|
||||
$string = static::encode($t, $qt);
|
||||
}
|
||||
return $string;
|
||||
}
|
||||
|
||||
/**
|
||||
* @param mixed ...$object
|
||||
* @return string
|
||||
* @throws Exception
|
||||
*/
|
||||
private static function encode(...$object): string
|
||||
{
|
||||
$ret = [];
|
||||
|
||||
$data = $object[count($object) - 1];
|
||||
$key = static::getKey(...$object);
|
||||
foreach ($data as $s => $datum) {
|
||||
if (is_array($datum)) {
|
||||
$object[count($object) - 1] = $s;
|
||||
$object[] = $datum;
|
||||
$string = static::encode(...$object);
|
||||
} else {
|
||||
if (is_object($datum)) {
|
||||
throw new Exception('Http body con\'t object.');
|
||||
}
|
||||
$string = $key . '=' . urlencode($datum);
|
||||
}
|
||||
$ret[] = $string;
|
||||
}
|
||||
return implode('&', $ret);
|
||||
}
|
||||
|
||||
|
||||
}
|
||||
@@ -0,0 +1,217 @@
|
||||
<?php
|
||||
|
||||
|
||||
namespace Http\Client;
|
||||
|
||||
|
||||
use Closure;
|
||||
|
||||
interface IClient
|
||||
{
|
||||
|
||||
|
||||
/**
|
||||
* @param string $path
|
||||
* @param array $params
|
||||
* @return array|Result|int|string
|
||||
*/
|
||||
public function get(string $path, array $params = []): Result|int|array|string;
|
||||
|
||||
|
||||
/**
|
||||
* @param string $path
|
||||
* @param array $params
|
||||
* @return array|Result|int|string
|
||||
*/
|
||||
public function post(string $path, array $params = []): Result|int|array|string;
|
||||
|
||||
|
||||
/**
|
||||
* @param string $path
|
||||
* @param array $params
|
||||
* @return array|Result|int|string
|
||||
*/
|
||||
public function delete(string $path, array $params = []): Result|int|array|string;
|
||||
|
||||
|
||||
/**
|
||||
* @param string $path
|
||||
* @param array $params
|
||||
* @return array|Result|int|string
|
||||
*/
|
||||
public function options(string $path, array $params = []): Result|int|array|string;
|
||||
|
||||
|
||||
/**
|
||||
* @param string $path
|
||||
* @param array $params
|
||||
* @return array|Result|int|string
|
||||
*/
|
||||
public function upload(string $path, array $params = []): Result|int|array|string;
|
||||
|
||||
|
||||
/**
|
||||
* @param string $path
|
||||
* @param array $params
|
||||
* @return array|Result|int|string
|
||||
*/
|
||||
public function put(string $path, array $params = []): Result|int|array|string;
|
||||
|
||||
|
||||
/**
|
||||
* @param string $path
|
||||
* @param array $params
|
||||
* @return array|Result|int|string
|
||||
*/
|
||||
public function head(string $path, array $params = []): Result|int|array|string;
|
||||
|
||||
|
||||
/**
|
||||
* @param string $method
|
||||
* @param string $path
|
||||
* @param array $params
|
||||
* @return array|Result|int|string
|
||||
*/
|
||||
public function request(string $method, string $path, array $params = []): Result|array|int|string;
|
||||
|
||||
|
||||
/**
|
||||
* @param string $host
|
||||
* @return mixed
|
||||
*/
|
||||
public function setHost(string $host): void;
|
||||
|
||||
|
||||
/**
|
||||
* @param array $header
|
||||
* @return mixed
|
||||
*/
|
||||
public function setHeader(array $header): void;
|
||||
|
||||
|
||||
/**
|
||||
* @param array $header
|
||||
* @return mixed
|
||||
*/
|
||||
public function setHeaders(array $header): array;
|
||||
|
||||
|
||||
/**
|
||||
* @param string $key
|
||||
* @param string $value
|
||||
* @return mixed
|
||||
*/
|
||||
public function addHeader(string $key, string $value): void;
|
||||
|
||||
|
||||
/**
|
||||
* @param int $value
|
||||
* @return mixed
|
||||
*/
|
||||
public function setTimeout(int $value): void;
|
||||
|
||||
|
||||
/**
|
||||
* @param Closure|null $value
|
||||
* @return mixed
|
||||
*/
|
||||
public function setCallback(?Closure $value): void;
|
||||
|
||||
|
||||
/**
|
||||
* @param string $value
|
||||
* @return static
|
||||
*/
|
||||
public function setMethod(string $value): static;
|
||||
|
||||
|
||||
/**
|
||||
* @param bool $isSSL
|
||||
* @return mixed
|
||||
*/
|
||||
public function setIsSSL(bool $isSSL): void;
|
||||
|
||||
|
||||
/**
|
||||
* @param string $agent
|
||||
* @return mixed
|
||||
*/
|
||||
public function setAgent(string $agent): void;
|
||||
|
||||
|
||||
/**
|
||||
* @param string $errorCodeField
|
||||
* @return mixed
|
||||
*/
|
||||
public function setErrorCodeField(string $errorCodeField): void;
|
||||
|
||||
|
||||
/**
|
||||
* @param string $errorMsgField
|
||||
* @return mixed
|
||||
*/
|
||||
public function setErrorMsgField(string $errorMsgField): void;
|
||||
|
||||
|
||||
/**
|
||||
* @param bool $use_swoole
|
||||
* @return mixed
|
||||
*/
|
||||
public function setUseSwoole(bool $use_swoole): void;
|
||||
|
||||
|
||||
/**
|
||||
* @param string $ssl_cert_file
|
||||
* @return mixed
|
||||
*/
|
||||
public function setSslCertFile(string $ssl_cert_file): void;
|
||||
|
||||
|
||||
/**
|
||||
* @param string $ssl_key_file
|
||||
* @return mixed
|
||||
*/
|
||||
public function setSslKeyFile(string $ssl_key_file): void;
|
||||
|
||||
|
||||
/**
|
||||
* @param string $ssl_key_file
|
||||
* @return mixed
|
||||
*/
|
||||
public function setCa(string $ssl_key_file): void;
|
||||
|
||||
|
||||
/**
|
||||
* @param int $port
|
||||
* @return mixed
|
||||
*/
|
||||
public function setPort(int $port): void;
|
||||
|
||||
|
||||
/**
|
||||
* @param string $message
|
||||
* @return mixed
|
||||
*/
|
||||
public function setMessage(string $message): void;
|
||||
|
||||
|
||||
/**
|
||||
* @param string $data
|
||||
* @return mixed
|
||||
*/
|
||||
public function setData(string $data): void;
|
||||
|
||||
|
||||
/**
|
||||
* @param int $connect_timeout
|
||||
* @return mixed
|
||||
*/
|
||||
public function setConnectTimeout(int $connect_timeout): void;
|
||||
|
||||
|
||||
/**
|
||||
* @param string $contentType
|
||||
* @return mixed
|
||||
*/
|
||||
public function setContentType(string $contentType): void;
|
||||
}
|
||||
@@ -0,0 +1,175 @@
|
||||
<?php
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace Http\Client;
|
||||
|
||||
use Exception;
|
||||
use JetBrains\PhpStorm\Pure;
|
||||
|
||||
|
||||
/**
|
||||
* Class Result
|
||||
*
|
||||
* @package app\components
|
||||
*
|
||||
* @property $code
|
||||
* @property $message
|
||||
* @property $count
|
||||
* @property $data
|
||||
*/
|
||||
class Result
|
||||
{
|
||||
public int|string $code;
|
||||
public string $message;
|
||||
public int $count = 0;
|
||||
|
||||
public mixed $data;
|
||||
public ?array $header;
|
||||
public int $httpStatus = 200;
|
||||
|
||||
public int $startTime = 0;
|
||||
public int $requestTime = 0;
|
||||
public float $runTime = 0;
|
||||
|
||||
|
||||
/**
|
||||
* Result constructor.
|
||||
* @param array $data
|
||||
*/
|
||||
public function __construct(array $data)
|
||||
{
|
||||
$this->setAssignment($data);
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* @param $data
|
||||
* @return $this
|
||||
*/
|
||||
public function setAssignment($data): static
|
||||
{
|
||||
foreach ($data as $key => $val) {
|
||||
if (!property_exists($this, $key)) {
|
||||
continue;
|
||||
}
|
||||
$this->$key = $val;
|
||||
}
|
||||
return $this;
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* @param $name
|
||||
* @return mixed
|
||||
*/
|
||||
public function __get($name): mixed
|
||||
{
|
||||
return $this->$name;
|
||||
}
|
||||
|
||||
/**
|
||||
* @param $name
|
||||
* @param $value
|
||||
*/
|
||||
public function __set($name, $value)
|
||||
{
|
||||
$this->$name = $value;
|
||||
}
|
||||
|
||||
/**
|
||||
* @return array
|
||||
*/
|
||||
public function getHeaders(): array
|
||||
{
|
||||
$_tmp = [];
|
||||
if (!is_array($this->header)) {
|
||||
return $_tmp;
|
||||
}
|
||||
foreach ($this->header as $key => $val) {
|
||||
if ($key == 0) {
|
||||
$_tmp['pro'] = $val;
|
||||
} else {
|
||||
if (str_contains($val, ': ')) {
|
||||
$trim = explode(': ', $val);
|
||||
|
||||
$_tmp[strtolower($trim[0])] = $trim[1];
|
||||
} else {
|
||||
$_tmp[$key] = $val;
|
||||
}
|
||||
}
|
||||
}
|
||||
return $_tmp;
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* @return array
|
||||
*/
|
||||
public function getTime(): array
|
||||
{
|
||||
return [
|
||||
'startTime' => $this->startTime,
|
||||
'requestTime' => $this->requestTime,
|
||||
'runTime' => $this->runTime,
|
||||
];
|
||||
}
|
||||
|
||||
/**
|
||||
* @param $key
|
||||
* @param $data
|
||||
* @return $this
|
||||
* @throws Exception
|
||||
*/
|
||||
public function setAttr($key, $data): static
|
||||
{
|
||||
if (!property_exists($this, $key)) {
|
||||
throw new Exception('未查找到相应对象属性');
|
||||
}
|
||||
$this->$key = $data;
|
||||
return $this;
|
||||
}
|
||||
|
||||
/**
|
||||
* @param int $status
|
||||
* @return bool
|
||||
*/
|
||||
#[Pure] public function isResultsOK(int $status = 0): bool
|
||||
{
|
||||
if (!$this->httpIsOk()) {
|
||||
return false;
|
||||
}
|
||||
return $this->code === $status;
|
||||
}
|
||||
|
||||
/**
|
||||
* @return bool
|
||||
*/
|
||||
public function httpIsOk(): bool
|
||||
{
|
||||
return in_array($this->httpStatus, [100, 101, 200, 201, 202, 203, 204, 205, 206]);
|
||||
}
|
||||
|
||||
/**
|
||||
* @return mixed
|
||||
*/
|
||||
public function getBody(): mixed
|
||||
{
|
||||
return $this->data;
|
||||
}
|
||||
|
||||
/**
|
||||
* @return string
|
||||
*/
|
||||
public function getMessage(): string
|
||||
{
|
||||
return $this->message;
|
||||
}
|
||||
|
||||
/**
|
||||
* @return string|int
|
||||
*/
|
||||
public function getCode(): string|int
|
||||
{
|
||||
return $this->code;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,189 @@
|
||||
<?php
|
||||
|
||||
|
||||
namespace Http\Handler;
|
||||
|
||||
use Http\Handler\Abstracts\BaseContext;
|
||||
use Swoole\Coroutine;
|
||||
|
||||
/**
|
||||
* Class Context
|
||||
* @package Yoc\http
|
||||
*/
|
||||
class Context extends BaseContext
|
||||
{
|
||||
|
||||
protected static array $_contents = [];
|
||||
|
||||
|
||||
/**
|
||||
* @param $id
|
||||
* @param $context
|
||||
* @param null $coroutineId
|
||||
* @return mixed
|
||||
*/
|
||||
public static function setContext($id, $context, $coroutineId = null): mixed
|
||||
{
|
||||
if (Coroutine::getCid() === -1) {
|
||||
return static::$_contents[$id] = $context;
|
||||
}
|
||||
return Coroutine::getContext($coroutineId)[$id] = $context;
|
||||
}
|
||||
|
||||
/**
|
||||
* @param $id
|
||||
* @param int $value
|
||||
* @param null $coroutineId
|
||||
* @return bool|int
|
||||
*/
|
||||
public static function increment($id, int $value = 1, $coroutineId = null): bool|int
|
||||
{
|
||||
if (!isset(Coroutine::getContext($coroutineId)[$id])) {
|
||||
Coroutine::getContext($coroutineId)[$id] = 0;
|
||||
}
|
||||
return Coroutine::getContext($coroutineId)[$id] += $value;
|
||||
}
|
||||
|
||||
/**
|
||||
* @param $id
|
||||
* @param int $value
|
||||
* @param null $coroutineId
|
||||
* @return bool|int
|
||||
*/
|
||||
public static function decrement($id, int $value = 1, $coroutineId = null): bool|int
|
||||
{
|
||||
if (!isset(Coroutine::getContext($coroutineId)[$id])) {
|
||||
Coroutine::getContext($coroutineId)[$id] = 0;
|
||||
}
|
||||
return Coroutine::getContext($coroutineId)[$id] -= $value;
|
||||
}
|
||||
|
||||
/**
|
||||
* @param $id
|
||||
* @param null $default
|
||||
* @param null $coroutineId
|
||||
* @return mixed
|
||||
*/
|
||||
public static function getContext($id, $default = null, $coroutineId = null): mixed
|
||||
{
|
||||
if (Coroutine::getCid() === -1) {
|
||||
return static::loadByStatic($id, $default);
|
||||
}
|
||||
return static::loadByContext($id, $default, $coroutineId);
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* @param $id
|
||||
* @param null $default
|
||||
* @param null $coroutineId
|
||||
* @return mixed
|
||||
*/
|
||||
private static function loadByContext($id, $default = null, $coroutineId = null): mixed
|
||||
{
|
||||
return Coroutine::getContext($coroutineId)[$id] ?? $default;
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* @param $id
|
||||
* @param null $default
|
||||
* @return mixed
|
||||
*/
|
||||
private static function loadByStatic($id, $default = null): mixed
|
||||
{
|
||||
return static::$_contents[$id] ?? $default;
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* @param null $coroutineId
|
||||
* @return mixed
|
||||
*/
|
||||
public static function getAllContext($coroutineId = null): mixed
|
||||
{
|
||||
if (Coroutine::getCid() === -1) {
|
||||
return Coroutine::getContext($coroutineId) ?? [];
|
||||
} else {
|
||||
return static::$_contents ?? [];
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* @param string $id
|
||||
* @param null $coroutineId
|
||||
*/
|
||||
public static function remove(string $id, $coroutineId = null)
|
||||
{
|
||||
if (!static::hasContext($id, $coroutineId)) {
|
||||
return;
|
||||
}
|
||||
if (Coroutine::getCid() === -1) {
|
||||
unset(static::$_contents[$id]);
|
||||
} else {
|
||||
unset(Coroutine::getContext($coroutineId)[$id]);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* @param $id
|
||||
* @param null $key
|
||||
* @param null $coroutineId
|
||||
* @return bool
|
||||
*/
|
||||
public static function hasContext($id, $key = null, $coroutineId = null): bool
|
||||
{
|
||||
if (Coroutine::getCid() === -1) {
|
||||
return static::searchByStatic($id, $key);
|
||||
}
|
||||
return static::searchByCoroutine($id, $key, $coroutineId);
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* @param $id
|
||||
* @param null $key
|
||||
* @return bool
|
||||
*/
|
||||
private static function searchByStatic($id, $key = null): bool
|
||||
{
|
||||
if (!isset(static::$_contents[$id])) {
|
||||
return false;
|
||||
}
|
||||
if (!empty($key) && !isset(static::$_contents[$id][$key])) {
|
||||
return false;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* @param $id
|
||||
* @param null $key
|
||||
* @param null $coroutineId
|
||||
* @return bool
|
||||
*/
|
||||
private static function searchByCoroutine($id, $key = null, $coroutineId = null): bool
|
||||
{
|
||||
if (!isset(Coroutine::getContext($coroutineId)[$id])) {
|
||||
return false;
|
||||
}
|
||||
if ($key !== null) {
|
||||
return isset((Coroutine::getContext($coroutineId)[$id] ?? [])[$key]);
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* @return bool
|
||||
*/
|
||||
public static function inCoroutine(): bool
|
||||
{
|
||||
return Coroutine::getCid() !== -1;
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
|
||||
|
||||
@@ -0,0 +1,61 @@
|
||||
<?php
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace Http;
|
||||
|
||||
|
||||
use Annotation\Inject;
|
||||
use JetBrains\PhpStorm\Pure;
|
||||
use Kiri\Application;
|
||||
use Kiri\Di\ContainerInterface;
|
||||
use Psr\Log\LoggerInterface;
|
||||
use Server\Constrict\RequestInterface;
|
||||
use Server\Constrict\ResponseInterface;
|
||||
|
||||
/**
|
||||
* Class WebController
|
||||
* @package Kiri\Kiri\Web
|
||||
*/
|
||||
class Controller
|
||||
{
|
||||
|
||||
|
||||
/**
|
||||
* inject di container
|
||||
*
|
||||
* @var ContainerInterface|null
|
||||
*/
|
||||
#[Inject(ContainerInterface::class)]
|
||||
public ?ContainerInterface $container = null;
|
||||
|
||||
|
||||
/**
|
||||
* inject request
|
||||
*
|
||||
* @var RequestInterface|null
|
||||
*/
|
||||
#[Inject(RequestInterface::class)]
|
||||
public ?RequestInterface $request = null;
|
||||
|
||||
|
||||
/**
|
||||
* inject response
|
||||
*
|
||||
* @var ResponseInterface|null
|
||||
*/
|
||||
#[Inject(ResponseInterface::class)]
|
||||
public ?ResponseInterface $response = null;
|
||||
|
||||
|
||||
|
||||
/**
|
||||
* inject logger
|
||||
*
|
||||
* @var LoggerInterface
|
||||
*/
|
||||
#[Inject(LoggerInterface::class)]
|
||||
public LoggerInterface $logger;
|
||||
|
||||
|
||||
|
||||
}
|
||||
@@ -3,6 +3,7 @@
|
||||
namespace Http\Handler;
|
||||
|
||||
use Http\Handler\Abstracts\Middleware;
|
||||
use Http\Message\ServerRequest;
|
||||
use Psr\Http\Message\ResponseInterface;
|
||||
use Psr\Http\Message\ServerRequestInterface;
|
||||
use Psr\Http\Server\RequestHandlerInterface;
|
||||
@@ -12,7 +13,7 @@ class CoreMiddleware extends Middleware
|
||||
|
||||
|
||||
/**
|
||||
* @param ServerRequestInterface $request
|
||||
* @param ServerRequest $request
|
||||
* @param RequestHandlerInterface $handler
|
||||
* @return ResponseInterface
|
||||
* @throws \Exception
|
||||
@@ -21,7 +22,9 @@ class CoreMiddleware extends Middleware
|
||||
{
|
||||
// TODO: Implement process() method.
|
||||
|
||||
|
||||
\response()->withAccessControlAllowOrigin('*')
|
||||
->withAccessControlRequestMethod($request->getAccessControlRequestMethod())
|
||||
->withAccessControlAllowHeaders($request->getAccessControlAllowHeaders());
|
||||
|
||||
return $handler->handle($request);
|
||||
}
|
||||
|
||||
@@ -0,0 +1,50 @@
|
||||
<?php
|
||||
|
||||
namespace Http\Handler\Formatter;
|
||||
|
||||
use Exception;
|
||||
use Http\Handler\Abstracts\HttpService;
|
||||
use Swoole\Http\Response;
|
||||
|
||||
|
||||
/**
|
||||
*
|
||||
*/
|
||||
class FileFormatter extends HttpService implements IFormatter
|
||||
{
|
||||
|
||||
public mixed $data;
|
||||
|
||||
/** @var Response */
|
||||
public Response $status;
|
||||
|
||||
public array $header = [];
|
||||
|
||||
/**
|
||||
* @param $context
|
||||
* @return $this
|
||||
* @throws Exception
|
||||
*/
|
||||
public function send($context): static
|
||||
{
|
||||
$this->data = $context;
|
||||
return $this;
|
||||
}
|
||||
|
||||
/**
|
||||
* @return mixed
|
||||
*/
|
||||
public function getData(): mixed
|
||||
{
|
||||
$data = $this->data;
|
||||
$this->clear();
|
||||
return $data;
|
||||
}
|
||||
|
||||
|
||||
public function clear(): void
|
||||
{
|
||||
$this->data = null;
|
||||
unset($this->data);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,61 @@
|
||||
<?php
|
||||
/**
|
||||
* Created by PhpStorm.
|
||||
* User: whwyy
|
||||
* Date: 2018/4/8 0008
|
||||
* Time: 17:51
|
||||
*/
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace Http\Handler\Formatter;
|
||||
|
||||
|
||||
use Exception;
|
||||
use Http\Handler\Abstracts\HttpService;
|
||||
use Kiri\Core\Json;
|
||||
use Swoole\Http\Response;
|
||||
|
||||
/**
|
||||
* Class HtmlFormatter
|
||||
* @package Kiri\Kiri\Http\Formatter
|
||||
*/
|
||||
class HtmlFormatter extends HttpService implements IFormatter
|
||||
{
|
||||
|
||||
public mixed $data;
|
||||
|
||||
/** @var Response */
|
||||
public Response $status;
|
||||
|
||||
public array $header = [];
|
||||
|
||||
/**
|
||||
* @param $context
|
||||
* @return $this
|
||||
* @throws Exception
|
||||
*/
|
||||
public function send($context): static
|
||||
{
|
||||
if (!is_string($context)) {
|
||||
$context = Json::encode($context);
|
||||
}
|
||||
$this->data = $context;
|
||||
return $this;
|
||||
}
|
||||
|
||||
/**
|
||||
* @return mixed
|
||||
*/
|
||||
public function getData(): mixed
|
||||
{
|
||||
$data = $this->data;
|
||||
$this->clear();
|
||||
return $data;
|
||||
}
|
||||
|
||||
public function clear(): void
|
||||
{
|
||||
$this->data = null;
|
||||
unset($this->data);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,33 @@
|
||||
<?php
|
||||
declare(strict_types=1);
|
||||
/**
|
||||
* Created by PhpStorm.
|
||||
* User: whwyy
|
||||
* Date: 2018/4/8 0008
|
||||
* Time: 17:29
|
||||
*/
|
||||
|
||||
namespace Http\Handler\Formatter;
|
||||
|
||||
|
||||
/**
|
||||
* Interface IFormatter
|
||||
* @package Kiri\Kiri\Http\Formatter
|
||||
*/
|
||||
interface IFormatter
|
||||
{
|
||||
|
||||
/**
|
||||
* @param $context
|
||||
* @return static
|
||||
*/
|
||||
public function send($context): static;
|
||||
|
||||
|
||||
/**
|
||||
* @return mixed
|
||||
*/
|
||||
public function getData(): mixed;
|
||||
|
||||
public function clear(): void;
|
||||
}
|
||||
@@ -0,0 +1,55 @@
|
||||
<?php
|
||||
/**
|
||||
* Created by PhpStorm.
|
||||
* User: whwyy
|
||||
* Date: 2018/4/8 0008
|
||||
* Time: 17:18
|
||||
*/
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace Http\Handler\Formatter;
|
||||
|
||||
use Http\Handler\Abstracts\HttpService;
|
||||
|
||||
/**
|
||||
* Class JsonFormatter
|
||||
* @package Kiri\Kiri\Http\Formatter
|
||||
*/
|
||||
class JsonFormatter extends HttpService implements IFormatter
|
||||
{
|
||||
public mixed $data;
|
||||
|
||||
public int $status = 200;
|
||||
|
||||
public array $header = [];
|
||||
|
||||
/**
|
||||
* @param $context
|
||||
* @return JsonFormatter
|
||||
*/
|
||||
public function send($context): static
|
||||
{
|
||||
if (!is_string($context)) {
|
||||
$context = json_encode($context);
|
||||
}
|
||||
$this->data = $context;
|
||||
return $this;
|
||||
}
|
||||
|
||||
/**
|
||||
* @return mixed
|
||||
*/
|
||||
public function getData(): mixed
|
||||
{
|
||||
$data = $this->data;
|
||||
$this->clear();
|
||||
return $data;
|
||||
}
|
||||
|
||||
|
||||
public function clear(): void
|
||||
{
|
||||
$this->data = null;
|
||||
unset($this->data);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,89 @@
|
||||
<?php
|
||||
/**
|
||||
* Created by PhpStorm.
|
||||
* User: whwyy
|
||||
* Date: 2018/4/8 0008
|
||||
* Time: 17:29
|
||||
*/
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace Http\Handler\Formatter;
|
||||
|
||||
|
||||
use Exception;
|
||||
use Http\Handler\Abstracts\HttpService;
|
||||
use SimpleXMLElement;
|
||||
use Swoole\Http\Response;
|
||||
|
||||
|
||||
/**
|
||||
* Class XmlFormatter
|
||||
* @package Kiri\Kiri\Http\Formatter
|
||||
*/
|
||||
class XmlFormatter extends HttpService implements IFormatter
|
||||
{
|
||||
|
||||
public ?string $data = '';
|
||||
|
||||
/** @var Response */
|
||||
public Response $status;
|
||||
|
||||
public array $header = [];
|
||||
|
||||
/**
|
||||
* @param $context
|
||||
* @return $this
|
||||
* @throws Exception
|
||||
*/
|
||||
public function send($context): static
|
||||
{
|
||||
if (!is_string($context)) {
|
||||
// TODO: Implement send() method.
|
||||
$dom = new SimpleXMLElement('<xml/>');
|
||||
|
||||
$this->toXml($dom, $context);
|
||||
|
||||
$this->data = $dom->saveXML();
|
||||
}
|
||||
return $this;
|
||||
}
|
||||
|
||||
/**
|
||||
* @return string|null
|
||||
*/
|
||||
public function getData(): ?string
|
||||
{
|
||||
$data = $this->data;
|
||||
$this->clear();
|
||||
return $data;
|
||||
}
|
||||
|
||||
/**
|
||||
* @param SimpleXMLElement $dom
|
||||
* @param $data
|
||||
*/
|
||||
public function toXml(SimpleXMLElement $dom, $data)
|
||||
{
|
||||
foreach ($data as $key => $val) {
|
||||
if (is_numeric($key)) {
|
||||
$key = 'item' . $key;
|
||||
}
|
||||
if (is_array($val)) {
|
||||
$node = $dom->addChild($key);
|
||||
$this->toXml($node, $val);
|
||||
} else if (is_object($val)) {
|
||||
$val = get_object_vars($val);
|
||||
$node = $dom->addChild($key);
|
||||
$this->toXml($node, $val);
|
||||
} else {
|
||||
$dom->addChild($key, htmlspecialchars((string)$val));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public function clear(): void
|
||||
{
|
||||
$this->data = null;
|
||||
unset($this->data);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,181 @@
|
||||
<?php
|
||||
|
||||
namespace Http\Handler;
|
||||
|
||||
use Annotation\Aspect;
|
||||
use Closure;
|
||||
use Exception;
|
||||
use Psr\Http\Server\MiddlewareInterface;
|
||||
use Kiri\Di\NoteManager;
|
||||
use Kiri\IAspect;
|
||||
use Kiri\Kiri;
|
||||
use ReflectionException;
|
||||
use Throwable;
|
||||
|
||||
class Pipeline
|
||||
{
|
||||
protected mixed $passable;
|
||||
|
||||
protected mixed $overall;
|
||||
|
||||
protected mixed $pipes = [];
|
||||
|
||||
|
||||
protected mixed $pipeline;
|
||||
|
||||
protected mixed $exceptionHandler;
|
||||
|
||||
/**
|
||||
* 初始数据
|
||||
* @param $passable
|
||||
* @return $this
|
||||
*/
|
||||
public function send($passable): static
|
||||
{
|
||||
$this->passable = $passable;
|
||||
return $this;
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* @param $middle
|
||||
* @return $this
|
||||
*/
|
||||
public function overall($middle): static
|
||||
{
|
||||
$this->overall = $middle;
|
||||
return $this;
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* 调用栈
|
||||
* @param $pipes
|
||||
* @return $this
|
||||
*/
|
||||
public function through($pipes): static
|
||||
{
|
||||
if (empty($pipes)) return $this;
|
||||
if (empty($this->pipes)) {
|
||||
$this->pipes = is_array($pipes) ? $pipes : func_get_args();
|
||||
} else {
|
||||
foreach ($pipes as $pipe) {
|
||||
$this->pipes[] = $pipe;
|
||||
}
|
||||
}
|
||||
return $this;
|
||||
}
|
||||
|
||||
/**
|
||||
* 执行
|
||||
* @param callable $destination
|
||||
* @return static
|
||||
* @throws ReflectionException
|
||||
*/
|
||||
public function then(callable $destination): static
|
||||
{
|
||||
$parameters = $this->passable;
|
||||
if (!empty($this->overall)) {
|
||||
array_unshift($this->pipes, $this->overall);
|
||||
}
|
||||
if (is_array($destination)) {
|
||||
$destination = $this->aspect_caller($destination, $parameters);
|
||||
}
|
||||
$this->pipeline = array_reduce(array_reverse($this->pipes), $this->carry(),
|
||||
static function () use ($destination, $parameters) {
|
||||
return call_user_func($destination, ...$parameters);
|
||||
}
|
||||
);
|
||||
return $this->clear();
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* @return $this
|
||||
*/
|
||||
private function clear(): static
|
||||
{
|
||||
$this->pipes = [];
|
||||
$this->passable = null;
|
||||
$this->overall = null;
|
||||
return $this;
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* @param $destination
|
||||
* @param $parameters
|
||||
* @return Closure|array
|
||||
* @throws ReflectionException
|
||||
*/
|
||||
private function aspect_caller($destination, $parameters): Closure|array
|
||||
{
|
||||
[$controller, $action] = $destination;
|
||||
/** @var Aspect $aop */
|
||||
$aop = NoteManager::getSpecify_annotation(Aspect::class, $controller::class, $action);
|
||||
if (!empty($aop)) {
|
||||
$aop = Kiri::getDi()->get($aop->aspect);
|
||||
$destination = static function () use ($aop, $destination, $parameters) {
|
||||
/** @var IAspect $aop */
|
||||
$aop->before();
|
||||
$aop->after($data = $aop->invoke($destination, $parameters));
|
||||
return $data;
|
||||
};
|
||||
}
|
||||
return $destination;
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* @param $request
|
||||
* @return mixed
|
||||
*/
|
||||
public function interpreter($request): mixed
|
||||
{
|
||||
return call_user_func($this->pipeline, $request);
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* 设置异常处理器
|
||||
* @param callable $handler
|
||||
* @return $this
|
||||
*/
|
||||
public function whenException(callable $handler): static
|
||||
{
|
||||
$this->exceptionHandler = $handler;
|
||||
return $this;
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* @return Closure
|
||||
*/
|
||||
protected function carry(): Closure
|
||||
{
|
||||
return static function ($stack, $pipe) {
|
||||
return static function ($passable) use ($stack, $pipe) {
|
||||
if ($pipe instanceof MiddlewareInterface) {
|
||||
$pipe = [$pipe, 'process'];
|
||||
}
|
||||
return $pipe($passable, $stack);
|
||||
};
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* 异常处理
|
||||
* @param $passable
|
||||
* @param Throwable $e
|
||||
* @return mixed
|
||||
* @throws Throwable
|
||||
*/
|
||||
protected function handleException($passable, Throwable $e): mixed
|
||||
{
|
||||
if ($this->exceptionHandler) {
|
||||
return call_user_func($this->exceptionHandler, $passable, $e);
|
||||
}
|
||||
throw $e;
|
||||
}
|
||||
|
||||
}
|
||||
+143
-19
@@ -3,8 +3,12 @@
|
||||
namespace Http\Handler;
|
||||
|
||||
use Closure;
|
||||
use Exception;
|
||||
use Http\Handler\Abstracts\HandlerManager;
|
||||
use Http\Route\MiddlewareManager;
|
||||
use Http\Handler\Abstracts\MiddlewareManager;
|
||||
use Kiri\Abstracts\Logger;
|
||||
use Kiri\Kiri;
|
||||
use Throwable;
|
||||
|
||||
class Router
|
||||
{
|
||||
@@ -14,34 +18,105 @@ class Router
|
||||
|
||||
|
||||
/**
|
||||
* @param string $route
|
||||
* @param string|Closure $closure
|
||||
* @param array $options
|
||||
* @throws \ReflectionException
|
||||
* @param $route
|
||||
* @param $handler
|
||||
* @return void
|
||||
* @throws
|
||||
*/
|
||||
public function get(string $route, string|Closure $closure, array $options = [])
|
||||
public static function socket($route, $handler): void
|
||||
{
|
||||
array_push($this->groupTack, $options);
|
||||
|
||||
$this->addRoute('GET', $route, $closure);
|
||||
|
||||
array_pop($this->groupTack);
|
||||
$router = Kiri::getDi()->get(Router::class);
|
||||
$router->addRoute($route, $handler, 'SOCKET');
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* @param string $route
|
||||
* @param string|Closure $closure
|
||||
* @param array $options
|
||||
* @throws \ReflectionException
|
||||
* @param $route
|
||||
* @param $handler
|
||||
* @return void
|
||||
* @throws
|
||||
*/
|
||||
public function post(string $route, string|Closure $closure, array $options = [])
|
||||
public static function post($route, $handler): void
|
||||
{
|
||||
array_push($this->groupTack, $options);
|
||||
$router = Kiri::getDi()->get(Router::class);
|
||||
$router->addRoute($route, $handler, 'POST');
|
||||
}
|
||||
|
||||
$this->addRoute('POST', $route, $closure);
|
||||
/**
|
||||
* @param $route
|
||||
* @param $handler
|
||||
* @return void
|
||||
* @throws
|
||||
*/
|
||||
public static function get($route, $handler): void
|
||||
{
|
||||
$router = Kiri::getDi()->get(Router::class);
|
||||
$router->addRoute($route, $handler, 'GET');
|
||||
}
|
||||
|
||||
array_pop($this->groupTack);
|
||||
|
||||
/**
|
||||
* @param $route
|
||||
* @param $handler
|
||||
* @return void
|
||||
* @throws
|
||||
*/
|
||||
public static function options($route, $handler): void
|
||||
{
|
||||
$router = Kiri::getDi()->get(Router::class);
|
||||
$router->addRoute($route, $handler, 'OPTIONS');
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* @param $route
|
||||
* @param $handler
|
||||
* @throws
|
||||
*/
|
||||
public static function any($route, $handler): void
|
||||
{
|
||||
$router = Kiri::getDi()->get(Router::class);
|
||||
foreach ($router->methods as $method) {
|
||||
$router->addRoute($route, $handler, $method);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* @param $route
|
||||
* @param $handler
|
||||
* @return void
|
||||
* @throws
|
||||
*/
|
||||
public static function delete($route, $handler): void
|
||||
{
|
||||
$router = Kiri::getDi()->get(Router::class);
|
||||
$router->addRoute($route, $handler, 'DELETE');
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* @param $route
|
||||
* @param $handler
|
||||
* @return void
|
||||
* @throws Exception
|
||||
*/
|
||||
public static function head($route, $handler): void
|
||||
{
|
||||
$router = Kiri::getDi()->get(Router::class);
|
||||
$router->addRoute($route, $handler, 'HEAD');
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* @param $route
|
||||
* @param $handler
|
||||
* @return void
|
||||
* @throws
|
||||
*/
|
||||
public static function put($route, $handler): void
|
||||
{
|
||||
$router = Kiri::getDi()->get(Router::class);
|
||||
$router->addRoute($route, $handler, 'PUT');
|
||||
}
|
||||
|
||||
|
||||
@@ -129,4 +204,53 @@ class Router
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* @throws Exception
|
||||
*/
|
||||
public function _loader()
|
||||
{
|
||||
$this->loadRouteDir(APP_PATH . 'routes');
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* @param $path
|
||||
* @throws Exception
|
||||
* 加载目录下的路由文件
|
||||
*/
|
||||
private function loadRouteDir($path)
|
||||
{
|
||||
$files = glob($path . '/*');
|
||||
for ($i = 0; $i < count($files); $i++) {
|
||||
if (is_dir($files[$i])) {
|
||||
$this->loadRouteDir($files[$i]);
|
||||
} else {
|
||||
$this->loadRouterFile($files[$i]);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* @param $files
|
||||
* @throws Exception
|
||||
*/
|
||||
private function loadRouterFile($files)
|
||||
{
|
||||
try {
|
||||
include_once "$files";
|
||||
} catch (Throwable $exception) {
|
||||
di(Logger::class)->error('router', [
|
||||
$exception->getMessage(),
|
||||
$exception->getFile(),
|
||||
$exception->getLine(),
|
||||
]);
|
||||
} finally {
|
||||
if (isset($exception)) {
|
||||
unset($exception);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
}
|
||||
|
||||
@@ -1,88 +0,0 @@
|
||||
<?php
|
||||
|
||||
namespace Http\Handler;
|
||||
|
||||
use Exception;
|
||||
use Http\Context\Context;
|
||||
use Http\Handler\Abstracts\HandlerManager;
|
||||
use Http\Message\ServerRequest;
|
||||
use Http\Message\Stream;
|
||||
use Http\Route\MiddlewareManager;
|
||||
use Psr\Http\Message\ServerRequestInterface;
|
||||
use Server\Constrict\RequestInterface;
|
||||
use Server\Constrict\ResponseEmitter;
|
||||
use Server\Constrict\ResponseInterface;
|
||||
use Swoole\Http\Request;
|
||||
use Swoole\Http\Response;
|
||||
|
||||
class TestRequest
|
||||
{
|
||||
|
||||
|
||||
private ?ResponseEmitter $response = null;
|
||||
|
||||
public function __construct()
|
||||
{
|
||||
$this->response = new ResponseEmitter();
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* @param Request $request
|
||||
* @param Response $response
|
||||
* @throws Exception
|
||||
*/
|
||||
public function onRequest(Request $request, Response $response): void
|
||||
{
|
||||
try {
|
||||
[$PsrRequest, $PsrResponse] = $this->initRequestResponse($request);
|
||||
/** @var Handler $handler */
|
||||
$handler = HandlerManager::get($request->server['request_uri'], $request->getMethod());
|
||||
if (is_integer($handler)) {
|
||||
$PsrResponse->withStatus($handler)->withBody(new Stream('Allow Method[' . $request->getMethod() . '].'));
|
||||
} else if (is_null($handler)) {
|
||||
$PsrResponse->withStatus(404)->withBody(new Stream('Page not found.'));
|
||||
} else {
|
||||
$PsrResponse = $this->handler($handler, $PsrRequest);
|
||||
}
|
||||
} catch (\Throwable $throwable) {
|
||||
$PsrResponse = \response()->withStatus($throwable->getCode())
|
||||
->withContentType(\Http\Message\Response::CONTENT_TYPE_HTML)
|
||||
->withBody(new Stream(jTraceEx($throwable, null, true)));
|
||||
} finally {
|
||||
$this->response->sender($response, $PsrResponse);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* @param Handler $handler
|
||||
* @param $PsrRequest
|
||||
* @return ResponseInterface
|
||||
* @throws Exception
|
||||
*/
|
||||
protected function handler(Handler $handler, $PsrRequest): \Psr\Http\Message\ResponseInterface
|
||||
{
|
||||
$middlewares = MiddlewareManager::get($handler->callback);
|
||||
|
||||
$dispatcher = new Dispatcher($handler, $middlewares);
|
||||
|
||||
return $dispatcher->handle($PsrRequest);
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* @param Request $request
|
||||
* @return array<ServerRequestInterface, ResponseInterface>
|
||||
* @throws Exception
|
||||
*/
|
||||
private function initRequestResponse(Request $request): array
|
||||
{
|
||||
$PsrResponse = Context::setContext(ResponseInterface::class, new \Http\Message\Response());
|
||||
|
||||
$PsrRequest = Context::setContext(RequestInterface::class, ServerRequest::createServerRequest($request));
|
||||
|
||||
return [$PsrRequest, $PsrResponse];
|
||||
}
|
||||
|
||||
}
|
||||
Reference in New Issue
Block a user