This commit is contained in:
2021-07-27 16:08:16 +08:00
parent ef423dc1b8
commit a36f876792
8 changed files with 744 additions and 748 deletions
+7 -6
View File
@@ -19,11 +19,12 @@ use Snowflake\Snowflake;
{ {
/** /**
* Inject constructor. * Inject constructor.
* @param string $value * @param string $value
* @param array $args * @param bool $withContext
*/ * @param array $args
*/
public function __construct(private string $value, public bool $withContext = false, private array $args = []) public function __construct(private string $value, public bool $withContext = false, private array $args = [])
{ {
} }
@@ -78,7 +79,7 @@ use Snowflake\Snowflake;
return $method; return $method;
} }
if (is_object($class)) $class = $class::class; if (is_object($class)) $class = $class::class;
$method = Snowflake::getDi()->getClassProperty($class, $method); $method = Snowflake::getDi()->getClassReflectionProperty($class, $method);
if (!$method || $method->isStatic()) { if (!$method || $method->isStatic()) {
return false; return false;
} }
+169 -172
View File
@@ -4,15 +4,10 @@
namespace Annotation; namespace Annotation;
use Annotation\Model\Get;
use Annotation\Model\Relation;
use Annotation\Model\Set;
use Attribute;
use DirectoryIterator; use DirectoryIterator;
use Exception; use Exception;
use ReflectionClass; use ReflectionClass;
use ReflectionException; use ReflectionException;
use ReflectionMethod;
use Snowflake\Abstracts\BaseObject; use Snowflake\Abstracts\BaseObject;
use Snowflake\Exception\NotFindClassException; use Snowflake\Exception\NotFindClassException;
use Snowflake\Snowflake; use Snowflake\Snowflake;
@@ -27,204 +22,206 @@ class Loader extends BaseObject
{ {
private static array $_classes = []; private static array $_classes = [];
private static array $_directory = []; private static array $_directory = [];
private static array $_property = []; private static array $_property = [];
private static array $_methods = []; private static array $_methods = [];
/** /**
* @param $path * @param $path
* @param $namespace * @param $namespace
* @throws Exception * @throws Exception
*/ */
public function loader($path, $namespace) public function loader($path, $namespace)
{ {
$this->_scanDir(new DirectoryIterator($path), $namespace); $this->_scanDir(new DirectoryIterator($path), $namespace);
} }
/** /**
* @param string $class * @param string $class
* @param string $property * @param string $property
* @return mixed * @return mixed
*/ */
public function getProperty(string $class, string $property = ''): mixed public function getProperty(string $class, string $property = ''): mixed
{ {
if (!isset(static::$_property[$class])) { return Snowflake::getDi()->getClassReflectionProperty($class, $property);
return null;
} if (!isset(static::$_property[$class])) {
if (!empty($property)) { return null;
return static::$_property[$class][$property] ?? []; }
} if (!empty($property)) {
return static::$_property[$class]; return static::$_property[$class][$property] ?? [];
} }
return static::$_property[$class];
}
/** /**
* @param string $class * @param string $class
* @param mixed $handler * @param object $handler
* @return Loader * @return $this
*/ * @throws NotFindClassException
public function injectProperty(string $class, object $handler): static * @throws ReflectionException
{ * @throws Exception
$properties = $this->getProperty($class); */
if (empty($properties)) { public function injectProperty(string $class, object $handler): static
return $this; {
} $di = Snowflake::getDi();
foreach ($properties as $property => $attributes) {
foreach ($attributes as $attribute) { $reflect = $di->getReflect($class);
$attribute->execute($handler, $property);
} $di->propertyInject($reflect, $handler);
}
return $this; return $this;
} }
/** /**
* @param string $class * @param string $class
* @param string $method * @param string $method
* @return mixed * @return mixed
*/ */
public function getMethod(string $class, string $method = ''): array public function getMethod(string $class, string $method = ''): array
{ {
if (!isset(static::$_methods[$class])) { if (!isset(static::$_methods[$class])) {
return []; return [];
} }
$properties = static::$_methods[$class]; $properties = static::$_methods[$class];
if (!empty($method) && isset($properties[$method])) { if (!empty($method) && isset($properties[$method])) {
return $properties[$method]; return $properties[$method];
} }
return $properties; return $properties;
} }
/** /**
* @param DirectoryIterator $paths * @param DirectoryIterator $paths
* @param $namespace * @param $namespace
* @throws Exception * @throws Exception
*/ */
public function _scanDir(DirectoryIterator $paths, $namespace) public function _scanDir(DirectoryIterator $paths, $namespace)
{ {
foreach ($paths as $path) { foreach ($paths as $path) {
if ($path->isDot() || str_starts_with($path->getFilename(), '.')) { if ($path->isDot() || str_starts_with($path->getFilename(), '.')) {
continue; continue;
} }
if ($path->isDir()) { if ($path->isDir()) {
$iterator = new DirectoryIterator($path->getRealPath()); $iterator = new DirectoryIterator($path->getRealPath());
$directory = rtrim($path->getRealPath(), '/'); $directory = rtrim($path->getRealPath(), '/');
if (!isset(static::$_directory[$directory])) { if (!isset(static::$_directory[$directory])) {
static::$_directory[$directory] = []; static::$_directory[$directory] = [];
} }
$this->_scanDir($iterator, $namespace); $this->_scanDir($iterator, $namespace);
} else { } else {
$this->readFile($path, $namespace); $this->readFile($path, $namespace);
} }
} }
} }
/** /**
* @param DirectoryIterator $path * @param DirectoryIterator $path
* @param $namespace * @param $namespace
* @throws Exception * @throws Exception
*/ */
private function readFile(DirectoryIterator $path, $namespace) private function readFile(DirectoryIterator $path, $namespace)
{ {
try { try {
if ($path->getExtension() !== 'php') { if ($path->getExtension() !== 'php') {
return; return;
} }
$replace = $this->getReflect($path, $namespace); $replace = $this->getReflect($path, $namespace);
if (empty($replace) || count($replace->getAttributes(Target::class)) < 1) { if (empty($replace) || count($replace->getAttributes(Target::class)) < 1) {
return; return;
} }
$this->appendFileToDirectory($path->getRealPath(), $replace->getName()); $this->appendFileToDirectory($path->getRealPath(), $replace->getName());
static::$_classes[] = $replace->getName(); static::$_classes[] = $replace->getName();
} catch (Throwable $throwable) { } catch (Throwable $throwable) {
$this->addError($throwable, 'throwable'); $this->addError($throwable, 'throwable');
} }
} }
/** /**
* @param DirectoryIterator $path * @param DirectoryIterator $path
* @param string $namespace * @param string $namespace
* @return ReflectionClass|null * @return ReflectionClass|null
* @throws ReflectionException * @throws ReflectionException
* @throws NotFindClassException * @throws NotFindClassException
*/ */
private function getReflect(DirectoryIterator $path, string $namespace): ?ReflectionClass private function getReflect(DirectoryIterator $path, string $namespace): ?ReflectionClass
{ {
return Snowflake::getDi()->getReflect($this->explodeFileName($path, $namespace)); return Snowflake::getDi()->getReflect($this->explodeFileName($path, $namespace));
} }
/** /**
* @param string $path * @param string $path
* @param string|array $outPath * @param string|array $outPath
* @throws Exception * @throws Exception
*/ */
public function loadByDirectory(string $path) public function loadByDirectory(string $path)
{ {
try { try {
$path = '/' . trim($path, '/'); $path = '/' . trim($path, '/');
$paths = []; $paths = [];
foreach (static::$_directory as $key => $_path) { foreach (static::$_directory as $key => $_path) {
$key = '/' . trim($key, '/'); $key = '/' . trim($key, '/');
if (!str_starts_with($key, $path)) { if (!str_starts_with($key, $path)) {
continue; continue;
} }
foreach ($_path as $item) { foreach ($_path as $item) {
$paths[] = $item; $paths[] = $item;
} }
} }
return $paths; return $paths;
} catch (Throwable $exception) { } catch (Throwable $exception) {
$this->addError($exception, 'throwable'); $this->addError($exception, 'throwable');
return []; return [];
} }
} }
/** /**
* @param DirectoryIterator $path * @param DirectoryIterator $path
* @param string $namespace * @param string $namespace
* @return string * @return string
*/ */
private function explodeFileName(DirectoryIterator $path, string $namespace): string private function explodeFileName(DirectoryIterator $path, string $namespace): string
{ {
$replace = str_replace(APP_PATH . 'app', '', $path->getRealPath()); $replace = str_replace(APP_PATH . 'app', '', $path->getRealPath());
$replace = str_replace('.php', '', $replace); $replace = str_replace('.php', '', $replace);
$replace = str_replace(DIRECTORY_SEPARATOR, '\\', $replace); $replace = str_replace(DIRECTORY_SEPARATOR, '\\', $replace);
$explode = explode('\\', $replace); $explode = explode('\\', $replace);
array_shift($explode); array_shift($explode);
return $namespace . '\\' . implode('\\', $explode); return $namespace . '\\' . implode('\\', $explode);
} }
/** /**
* @param string $filePath * @param string $filePath
* @param string $className * @param string $className
*/ */
public function appendFileToDirectory(string $filePath, string $className) public function appendFileToDirectory(string $filePath, string $className)
{ {
$array = explode('/', $filePath); $array = explode('/', $filePath);
unset($array[count($array) - 1]); unset($array[count($array) - 1]);
$array = '/' . trim(implode('/', $array), '/'); $array = '/' . trim(implode('/', $array), '/');
static::$_directory[$array][] = $className; static::$_directory[$array][] = $className;
} }
} }
-48
View File
@@ -1,48 +0,0 @@
<?php
namespace Annotation\Route;
use Annotation\Attribute;
use Snowflake\Snowflake;
/**
* Class Interceptor
* @package Annotation\Route
*/
#[\Attribute(\Attribute::TARGET_METHOD)] class After extends Attribute
{
/**
* Interceptor constructor.
* @param \HttpServer\IInterface\After|\HttpServer\IInterface\After[] $after
* @throws
*/
public function __construct(public string|array $after)
{
if (is_string($this->after)) {
$this->after = [$this->after];
}
foreach ($this->after as $key => $value) {
$sn = Snowflake::createObject($value);
if (!($sn instanceof \HttpServer\IInterface\After)) {
continue;
}
$this->after[$key] = [$sn, 'onHandler'];
}
}
/**
* @param mixed $class
* @param mixed|null $method
* @return After
*/
public function execute(mixed $class, mixed $method = null): static
{
return $this;
}
}
+450 -441
View File
@@ -3,17 +3,12 @@ declare(strict_types=1);
namespace HttpServer\Http; namespace HttpServer\Http;
use Annotation\Route\Socket;
use Exception; use Exception;
use HttpServer\Abstracts\HttpService; use HttpServer\Abstracts\HttpService;
use HttpServer\Http\Response as HResponse;
use HttpServer\IInterface\AuthIdentity; use HttpServer\IInterface\AuthIdentity;
use JetBrains\PhpStorm\Pure; use JetBrains\PhpStorm\Pure;
use Snowflake\Abstracts\Config;
use Snowflake\Core\ArrayAccess;
use Snowflake\Core\Help; use Snowflake\Core\Help;
use Snowflake\Core\Json; use Snowflake\Core\Json;
use Snowflake\Exception\ConfigException;
use Snowflake\Snowflake; use Snowflake\Snowflake;
use function router; use function router;
@@ -38,442 +33,456 @@ defined('REQUEST_FAIL') or define('REQUEST_FAIL', 500);
class Request extends HttpService class Request extends HttpService
{ {
public int $fd = 0; public int $fd = 0;
public ?HttpParams $params; public ?HttpParams $params;
public ?HttpHeaders $headers; public ?HttpHeaders $headers;
public bool $isCli = FALSE; public bool $isCli = FALSE;
public float $startTime; public float $startTime;
public ?array $clientInfo; public ?array $clientInfo;
public string $uri = ''; public string $uri = '';
public int $statusCode = 200; public int $statusCode = 200;
/** @var string[] */ /** @var string[] */
private array $explode = []; private array $explode = [];
const PLATFORM_MAC_OX = 'mac'; const PLATFORM_MAC_OX = 'mac';
const PLATFORM_IPHONE = 'iphone'; const PLATFORM_IPHONE = 'iphone';
const PLATFORM_ANDROID = 'android'; const PLATFORM_ANDROID = 'android';
const PLATFORM_WINDOWS = 'windows'; const PLATFORM_WINDOWS = 'windows';
const HTTP_POST = 'post'; const HTTP_POST = 'post';
const HTTP_GET = 'get'; const HTTP_GET = 'get';
const HTTP_CMD = 'rpc'; const HTTP_CMD = 'rpc';
const HTTP_LISTEN = 'listen'; const HTTP_LISTEN = 'listen';
const HTTP_SOCKET = 'sw::socket'; const HTTP_SOCKET = 'sw::socket';
/** /**
* @var AuthIdentity|null * @var AuthIdentity|null
*/ */
private ?AuthIdentity $_grant = null; private ?AuthIdentity $_grant = null;
/** /**
* @param $fd * @param $fd
*/ */
public function setFd($fd) public function setFd($fd)
{ {
$this->fd = $fd; $this->fd = $fd;
} }
/** /**
* @return array|null * @return array|null
* @throws Exception * @throws Exception
*/ */
public function getConnectInfo(): array|null public function getConnectInfo(): array|null
{ {
if (empty($this->fd)) { if (empty($this->fd)) {
return null; return null;
} }
$server = Snowflake::app()->getSwoole(); $server = Snowflake::app()->getSwoole();
return $server->getClientInfo($this->fd); return $server->getClientInfo($this->fd);
} }
/** /**
* @return int * @return int
*/ */
public function getClientId(): int public function getClientId(): int
{ {
return $this->fd; return $this->fd;
} }
/** /**
* @return bool * @return bool
*/ */
public function isFavicon(): bool public function isFavicon(): bool
{ {
return $this->getUri() === 'favicon.ico'; return $this->getUri() === 'favicon.ico';
} }
/** /**
* @return AuthIdentity|null * @return AuthIdentity|null
*/ */
public function getIdentity(): ?AuthIdentity public function getIdentity(): ?AuthIdentity
{ {
return $this->_grant; return $this->_grant;
} }
/** /**
* @return bool * @return bool
*/ */
public function isHead(): bool public function isHead(): bool
{ {
$result = $this->headers->getHeader('request_method') == 'head'; $result = $this->headers->getHeader('request_method') == 'head';
if ($result) { if ($result) {
$this->setStatus(101); $this->setStatus(101);
} else { } else {
$this->setStatus(200); $this->setStatus(200);
} }
return $result; return $result;
} }
/** /**
* @param $status * @param $status
* @return mixed * @return mixed
*/ */
public function setStatus($status): mixed public function setStatus($status): mixed
{ {
return $this->statusCode = $status; return $this->statusCode = $status;
} }
/** /**
* @return int * @return int
*/ */
public function getStatus(): int public function getStatus(): int
{ {
return $this->statusCode; return $this->statusCode;
} }
/** /**
* @return bool * @return bool
*/ */
public function getIsPackage(): bool public function getIsPackage(): bool
{ {
return $this->headers->getHeader('request_method') == 'package'; return $this->headers->getHeader('request_method') == 'package';
} }
/** /**
* @return bool * @return bool
*/ */
public function getIsReceive(): bool public function getIsReceive(): bool
{ {
return $this->headers->getHeader('request_method') == 'receive'; return $this->headers->getHeader('request_method') == 'receive';
} }
/** /**
* @param $value * @param $value
*/ */
public function setGrantAuthorization($value) public function setGrantAuthorization($value)
{ {
$this->_grant = $value; $this->_grant = $value;
} }
/** /**
* @return bool * @return bool
*/ */
public function hasGrant(): bool public function hasGrant(): bool
{ {
return $this->_grant !== null; return $this->_grant !== null;
} }
/** /**
* @return string * @return string
*/ */
public function parseUri(): string public function parseUri(): string
{ {
$array = []; $array = [];
$explode = explode('/', $this->headers->getHeader('request_uri')); $explode = explode('/', $this->headers->getHeader('request_uri'));
foreach ($explode as $item) { foreach ($explode as $item) {
if (empty($item)) { if (empty($item)) {
continue; continue;
} }
$array[] = $item; $array[] = $item;
} }
return $this->uri = implode('/', ($this->explode = $array)); return $this->uri = implode('/', ($this->explode = $array));
} }
/** /**
* @return string[] * @return string[]
*/ */
public function getExplode(): array public function getExplode(): array
{ {
return $this->explode; return $this->explode;
} }
/** /**
* @return string * @return string
*/ */
#[Pure] public function getCurrent(): string #[Pure] public function getCurrent(): string
{ {
return current($this->explode); return current($this->explode);
} }
/** /**
* @return string * @return string
*/ */
public function getUri(): string public function getUri(): string
{ {
if (!$this->headers) { if (!$this->headers) {
return 'command exec.'; return 'command exec.';
} }
if (!empty($this->uri)) { if (!empty($this->uri)) {
return $this->uri; return $this->uri;
} }
$uri = $this->headers->getHeader('request_uri'); $uri = $this->headers->getHeader('request_uri');
$uri = ltrim($uri, '/'); $uri = ltrim($uri, '/');
if (empty($uri)) return '/'; if (empty($uri)) return '/';
return $uri; return $uri;
} }
/** /**
* @return mixed * @return mixed
* @throws Exception * @throws Exception
*/ */
public function adapter(): void public function adapter(): void
{ {
if (!$this->isHead()) { if (!$this->isHead()) {
router()->dispatch(); router()->dispatch();
} }
} }
/** /**
* @return string|null * @return string|null
*/ */
public function getPlatform(): ?string public function getPlatform(): ?string
{ {
$user = $this->headers->getHeader('user-agent'); $user = $this->headers->getHeader('user-agent');
$match = preg_match('/\(.*\)?/', $user, $output); $match = preg_match('/\(.*\)?/', $user, $output);
if (!$match || count($output) < 1) { if (!$match || count($output) < 1) {
return null; return null;
} }
$output = strtolower(array_shift($output)); $output = strtolower(array_shift($output));
if (strpos('mac', $output)) { if (strpos('mac', $output)) {
return 'mac'; return 'mac';
} else if (strpos('iphone', $output)) { } else if (strpos('iphone', $output)) {
return 'iphone'; return 'iphone';
} else if (strpos('android', $output)) { } else if (strpos('android', $output)) {
return 'android'; return 'android';
} else if (strpos('windows', $output)) { } else if (strpos('windows', $output)) {
return 'windows'; return 'windows';
} }
return null; return null;
} }
/** /**
* @return bool * @return bool
*/ */
public function isIos(): bool public function isIos(): bool
{ {
return $this->getPlatform() == static::PLATFORM_IPHONE; return $this->getPlatform() == static::PLATFORM_IPHONE;
} }
/** /**
* @return bool * @return bool
*/ */
public function isAndroid(): bool public function isAndroid(): bool
{ {
return $this->getPlatform() == static::PLATFORM_ANDROID; return $this->getPlatform() == static::PLATFORM_ANDROID;
} }
/** /**
* @return bool * @return bool
*/ */
public function isMacOs(): bool public function isMacOs(): bool
{ {
return $this->getPlatform() == static::PLATFORM_MAC_OX; return $this->getPlatform() == static::PLATFORM_MAC_OX;
} }
/** /**
* @return bool * @return bool
*/ */
public function isWindows(): bool public function isWindows(): bool
{ {
return $this->getPlatform() == static::PLATFORM_WINDOWS; return $this->getPlatform() == static::PLATFORM_WINDOWS;
} }
/** /**
* @return bool * @return bool
*/ */
public function getIsPost(): bool public function getIsPost(): bool
{ {
return $this->getMethod() == 'post'; return $this->getMethod() == 'post';
} }
/** /**
* @return bool * @return bool
* @throws Exception * @throws Exception
*/ */
public function getIsHttp(): bool public function getIsHttp(): bool
{ {
return true; return true;
} }
/** /**
* @return bool * @return bool
*/ */
public function getIsOption(): bool public function getIsOption(): bool
{ {
return $this->getMethod() == 'options'; return $this->getMethod() == 'options';
} }
/** /**
* @return bool * @return bool
*/ */
public function getIsGet(): bool public function getIsGet(): bool
{ {
return $this->getMethod() == 'get'; return $this->getMethod() == 'get';
} }
/** /**
* @return bool * @return bool
*/ */
public function getIsDelete(): bool public function getIsDelete(): bool
{ {
return $this->getMethod() == 'delete'; return $this->getMethod() == 'delete';
} }
/** /**
* @return string * @return string
* *
* 获取请求类型 * 获取请求类型
*/ */
public function getMethod(): string public function getMethod(): string
{ {
$method = $this->headers->get('request_method'); $method = $this->headers->get('request_method');
if (empty($method)) { if (empty($method)) {
return 'get'; return 'get';
} }
return strtolower($method); return strtolower($method);
} }
/** /**
* @return bool * @return bool
*/ */
public function getIsCli(): bool public function getIsCli(): bool
{ {
return $this->isCli === TRUE; return $this->isCli === TRUE;
} }
/** /**
* @param $name * @param $name
* @param $value * @param $value
* *
* @throws Exception * @throws Exception
*/ */
public function __set($name, $value) public function __set($name, $value)
{ {
$method = 'set' . ucfirst($name); $method = 'set' . ucfirst($name);
if (method_exists($this, $method)) { if (method_exists($this, $method)) {
$this->$method($value); $this->$method($value);
} else { } else {
parent::__set($name, $value); // TODO: Change the autogenerated stub parent::__set($name, $value); // TODO: Change the autogenerated stub
} }
} }
/** /**
* @return mixed|null * @return mixed|null
*/ */
#[Pure] public function getIp(): string|null #[Pure] public function getIp(): string|null
{ {
$headers = $this->headers->getHeaders(); $headers = $this->headers->getHeaders();
if (!empty($headers['remoteip'])) return $headers['remoteip']; if (!empty($headers['remoteip'])) return $headers['remoteip'];
if (!empty($headers['x-forwarded-for'])) return $headers['x-forwarded-for']; if (!empty($headers['x-forwarded-for'])) return $headers['x-forwarded-for'];
if (!empty($headers['request-ip'])) return $headers['request-ip']; if (!empty($headers['request-ip'])) return $headers['request-ip'];
if (!empty($headers['remote_addr'])) return $headers['remote_addr']; if (!empty($headers['remote_addr'])) return $headers['remote_addr'];
return NULL; return NULL;
} }
/** /**
* @return string * @return string
*/ */
#[Pure] public function getRuntime(): string #[Pure] public function getRuntime(): string
{ {
return sprintf('%.5f', microtime(TRUE) - $this->startTime); return sprintf('%.5f', microtime(TRUE) - $this->startTime);
} }
/** /**
* @return string * @return string
*/ */
public function getDebug(): string public function getDebug(): string
{ {
$mainstay = sprintf("%.6f", microtime(true)); // 带毫秒的时间戳 $mainstay = sprintf("%.6f", microtime(true)); // 带毫秒的时间戳
$timestamp = floatval($mainstay); // 时间戳 $timestamp = floatval($mainstay); // 时间戳
$milliseconds = round(($mainstay - $timestamp) * 1000); // 毫秒 $milliseconds = round(($mainstay - $timestamp) * 1000); // 毫秒
$datetime = date("Y-m-d H:i:s", (int)$timestamp) . '.' . $milliseconds; $datetime = date("Y-m-d H:i:s", (int)$timestamp) . '.' . $milliseconds;
$tmp = [ $tmp = [
'[Debug ' . $datetime . '] ', '[Debug ' . $datetime . '] ',
$this->getIp(), $this->getIp(),
$this->getUri(), $this->getUri(),
'`' . $this->headers->getHeader('user-agent') . '`', '`' . $this->headers->getHeader('user-agent') . '`',
$this->getRuntime() $this->getRuntime()
]; ];
return implode(' ', $tmp); return implode(' ', $tmp);
} }
/** /**
* @param $router * @param $router
* @return bool * @return bool
*/ */
public function is($router): bool public function is($router): bool
{ {
return $this->getUri() == $router; return $this->getUri() == $router;
} }
/** /**
* @return bool * @return bool
*/ */
public function isNotFound(): bool public function isNotFound(): bool
{ {
return Json::to(404, 'Page ' . $this->getUri() . ' not found.'); return Json::to(404, 'Page ' . $this->getUri() . ' not found.');
} }
/** /**
* @param \Swoole\Http\Request $request * @param \Swoole\Http\Request $request
* @return mixed * @return mixed
*/ */
public static function create(\Swoole\Http\Request $request): Request public static function create(\Swoole\Http\Request $request): Request
{ {
/** @var Request $sRequest */ /** @var Request $sRequest */
$sRequest = Context::setContext('request', new Request()); $sRequest = Context::setContext('request', new Request());
$sRequest->fd = $request->fd;
$sRequest->startTime = microtime(true); $sRequest->fd = $request->fd;
$sRequest->startTime = microtime(true);
$sRequest->params = new HttpParams(Help::toArray($request->rawContent()), $request->get, $request->files);
if (!empty($request->post)) { $sRequest->params = new HttpParams(Help::toArray($request->rawContent()), $request->get, $request->files);
$sRequest->params->setPosts($request->post ?? []); if (!empty($request->post)) {
} $sRequest->params->setPosts($request->post ?? []);
Context::setContext(HttpParams::class, $sRequest->params); }
Context::setContext(HttpParams::class, $sRequest->params);
$sRequest->headers = new HttpHeaders(array_merge($request->server, $request->header));
Context::setContext(HttpHeaders::class, $sRequest->headers); $sRequest->headers = new HttpHeaders(array_merge($request->server, $request->header));
Context::setContext(HttpHeaders::class, $sRequest->headers);
$sRequest->uri = $sRequest->headers->get('request_uri');
$sRequest->uri = $sRequest->headers->get('request_uri');
$sRequest->parseUri();
$sRequest->parseUri();
return $sRequest;
} return $sRequest;
}
/**
* @param string $key
* @param mixed|null $defaultValue
* @return mixed
*/
public function post(string $key, mixed $defaultValue = null): mixed
{
/** @var HttpParams $params */
$params = Context::getContext(HttpParams::class);
return $params->post($key, $defaultValue);
}
} }
+80 -60
View File
@@ -4,6 +4,7 @@
namespace HttpServer\Route; namespace HttpServer\Route;
use Closure;
use HttpServer\IInterface\Middleware; use HttpServer\IInterface\Middleware;
use Snowflake\Abstracts\BaseObject; use Snowflake\Abstracts\BaseObject;
@@ -15,72 +16,91 @@ use Snowflake\Abstracts\BaseObject;
class MiddlewareManager extends BaseObject class MiddlewareManager extends BaseObject
{ {
private static array $_middlewares = []; private static array $_middlewares = [];
/** /**
* @param $class * @param $class
* @param $method * @param $method
* @param array|string $middlewares * @param array|string $middlewares
*/ */
public function addMiddlewares($class, $method, array|string $middlewares) public function addMiddlewares($class, $method, array|string $middlewares)
{ {
if (is_object($class)) { if (is_object($class)) {
$class = $class::class; $class = $class::class;
} }
if (!isset(static::$_middlewares[$class . '::' . $method])) { if (!isset(static::$_middlewares[$class . '::' . $method])) {
static::$_middlewares[$class . '::' . $method] = []; static::$_middlewares[$class . '::' . $method] = [];
} }
if (is_string($middlewares) && !in_array($middlewares, static::$_middlewares[$class . '::' . $method])) { if (is_string($middlewares) && !in_array($middlewares, static::$_middlewares[$class . '::' . $method])) {
static::$_middlewares[$class . '::' . $method][] = $middlewares; static::$_middlewares[$class . '::' . $method][] = $middlewares;
return; return;
} }
foreach ($middlewares as $middleware) { foreach ($middlewares as $middleware) {
if (in_array($middlewares, static::$_middlewares[$class . '::' . $method])) { if (in_array($middlewares, static::$_middlewares[$class . '::' . $method])) {
continue; continue;
} }
static::$_middlewares[$class . '::' . $method][] = $middleware; static::$_middlewares[$class . '::' . $method][] = $middleware;
} }
} }
/** /**
* @param $class * @param $class
* @param $method * @param $method
* @return bool * @return bool
*/ */
public function hasMiddleware($class, $method) public function hasMiddleware($class, $method): bool
{ {
if (is_object($class)) { if (is_object($class)) {
$class = $class::class; $class = $class::class;
} }
return isset(static::$_middlewares[$class . '::' . $method]); return isset(static::$_middlewares[$class . '::' . $method]);
} }
/** /**
* @param $class * @param $class
* @param $method * @param $method
* @param $caller * @param $caller
*/ * @return mixed
public function callerMiddlewares($class, $method, $caller) */
{ public function callerMiddlewares($class, $method, $caller): mixed
if (is_object($class)) { {
$class = $class::class; if (is_object($class)) {
} $class = $class::class;
$middlewares = static::$_middlewares[$class . '::' . $method] ?? []; }
if (empty($middlewares)) { $middlewares = static::$_middlewares[$class . '::' . $method] ?? [];
return $caller; if (empty($middlewares)) {
} return $caller;
return array_reduce(array_reverse($middlewares), function ($stack, $pipe) { }
return function ($passable) use ($stack, $pipe) { return array_reduce(array_reverse($middlewares), function ($stack, $pipe) {
if ($pipe instanceof Middleware) { return function ($passable) use ($stack, $pipe) {
return $pipe->onHandler($passable, $stack); if ($pipe instanceof Middleware) {
} return $pipe->onHandler($passable, $stack);
return call_user_func($pipe, $passable, $stack); }
}; return call_user_func($pipe, $passable, $stack);
}, $caller); };
} }, $caller);
}
/**
* @param $middlewares
* @param Closure $caller
* @return Closure
*/
public function closureMiddlewares($middlewares, Closure $caller): Closure
{
return array_reduce(array_reverse($middlewares), function ($stack, $pipe) {
return function ($passable) use ($stack, $pipe) {
if ($pipe instanceof Middleware) {
return $pipe->onHandler($passable, $stack);
}
return call_user_func($pipe, $passable, $stack);
};
}, $caller);
}
} }
+20 -2
View File
@@ -94,8 +94,26 @@ class Node extends HttpService
} else { } else {
$this->handler = $handler; $this->handler = $handler;
} }
if (!empty($this->handler) && is_array($this->handler)) { return $this->injectMiddleware();
$this->callback = di(MiddlewareManager::class)->callerMiddlewares( }
/**
* @throws NotFindClassException
* @throws ReflectionException
*/
private function injectMiddleware(): static
{
$manager = di(MiddlewareManager::class);
if ($this->handler instanceof Closure) {
if (!empty($this->middleware)) {
$this->callback = $manager->closureMiddlewares($this->middleware, $this->createDispatch());
} else {
$this->callback = $this->createDispatch();
}
} else {
$manager->addMiddlewares($this->handler[0], $this->handler[1], $this->middleware);
$this->callback = $manager->callerMiddlewares(
$this->handler[0], $this->handler[1], $this->createDispatch() $this->handler[0], $this->handler[1], $this->createDispatch()
); );
} }
+17 -18
View File
@@ -214,7 +214,7 @@ class Container extends BaseObject
* @return mixed * @return mixed
* @throws Exception * @throws Exception
*/ */
private function propertyInject(ReflectionClass $reflect, $object): mixed public function propertyInject(ReflectionClass $reflect, $object): mixed
{ {
if (!isset(static::$_propertyAttributes[$reflect->getName()])) { if (!isset(static::$_propertyAttributes[$reflect->getName()])) {
return $object; return $object;
@@ -228,7 +228,7 @@ class Container extends BaseObject
/** /**
* @param \ReflectionClass $class * @param ReflectionClass $class
*/ */
private function resolveMethodAttribute(ReflectionClass $class) private function resolveMethodAttribute(ReflectionClass $class)
{ {
@@ -251,12 +251,11 @@ class Container extends BaseObject
} }
/** /**
* @param \ReflectionAttribute $attribute * @param ReflectionClass $class
* @param \ReflectionClass $class * @param ReflectionMethod $method
* @param $object */
*/ private function setReflectionMethod(ReflectionClass $class, ReflectionMethod $method)
private function setReflectionMethod(ReflectionClass $class, \ReflectionMethod $method)
{ {
if (!isset(static::$_attributeMaping[$class->getName()])) { if (!isset(static::$_attributeMaping[$class->getName()])) {
static::$_attributeMaping[$class->getName()] = []; static::$_attributeMaping[$class->getName()] = [];
@@ -265,12 +264,12 @@ class Container extends BaseObject
} }
/** /**
* @param \ReflectionAttribute $attribute * @param ReflectionClass $attribute
* @param \ReflectionClass $class * @param ReflectionMethod $method
* @param $object * @param $object
*/ */
private function setMethodsAttributes(\ReflectionClass $attribute, ReflectionMethod $method, $object) private function setMethodsAttributes(ReflectionClass $attribute, ReflectionMethod $method, $object)
{ {
if (!isset(static::$_methodsAttributes[$attribute->getName()])) { if (!isset(static::$_methodsAttributes[$attribute->getName()])) {
static::$_methodsAttributes[$attribute->getName()] = []; static::$_methodsAttributes[$attribute->getName()] = [];
@@ -280,7 +279,7 @@ class Container extends BaseObject
/** /**
* @param \ReflectionClass $class * @param ReflectionClass $class
*/ */
private function resolveTargetAttribute(ReflectionClass $class) private function resolveTargetAttribute(ReflectionClass $class)
{ {
@@ -299,7 +298,7 @@ class Container extends BaseObject
/** /**
* @param $className * @param $className
* @param $method * @param $method
* @return \ReflectionMethod|null * @return ReflectionMethod|null
*/ */
public function getReflectionMethod($className, $method): ?ReflectionMethod public function getReflectionMethod($className, $method): ?ReflectionMethod
{ {
@@ -325,9 +324,9 @@ class Container extends BaseObject
/** /**
* @param string $class * @param string $class
* @param string|null $property * @param string|null $property
* @return ReflectionProperty|array|null * @return ReflectionProperty|ReflectionProperty[]|null
*/ */
public function getClassProperty(string $class, string $property = null): ReflectionProperty|null|array public function getClassReflectionProperty(string $class, string $property = null): ReflectionProperty|null|array
{ {
if (!isset(static::$_reflectionProperty[$class])) { if (!isset(static::$_reflectionProperty[$class])) {
return null; return null;
+1 -1
View File
@@ -56,7 +56,7 @@ class Snowflake
*/ */
public static function injectProperty(object $class) public static function injectProperty(object $class)
{ {
$attributes = static::getDi()->getClassProperty($class::class); $attributes = static::getDi()->getClassReflectionProperty($class::class);
/** /**
* @var string $property * @var string $property
* @var ReflectionProperty $attribute * @var ReflectionProperty $attribute