This commit is contained in:
as2252258@163.com
2021-07-27 03:30:55 +08:00
parent 22fa0d292c
commit 4e3b41331d
13 changed files with 888 additions and 1199 deletions
+2 -7
View File
@@ -192,14 +192,9 @@ class Annotation extends Component
* @param string|array $outPath * @param string|array $outPath
* @throws Exception * @throws Exception
*/ */
public function runtime(string $dir, string|array $outPath = '') public function runtime(string $dir)
{ {
if (empty($outPath)) { return $this->_loader->loadByDirectory($dir);
$outPath = [];
} else if (is_string($outPath)) {
$outPath = [$outPath];
}
$this->_loader->loadByDirectory($dir, $outPath);
} }
+9 -141
View File
@@ -38,13 +38,6 @@ class Loader extends BaseObject
private static array $_methods = []; private static array $_methods = [];
/**
* @return array
*/
public function getDirectory(): array
{
return static::$_directory;
}
/** /**
* @param $path * @param $path
@@ -56,16 +49,6 @@ class Loader extends BaseObject
$this->_scanDir(new DirectoryIterator($path), $namespace); $this->_scanDir(new DirectoryIterator($path), $namespace);
} }
/**
* @return array
*/
public function getClasses(): array
{
return static::$_classes;
}
/** /**
* @param string $class * @param string $class
* @param string $property * @param string $property
@@ -121,16 +104,6 @@ class Loader extends BaseObject
} }
/**
* @param string $class
* @return array
*/
public function getTarget(string $class): array
{
return static::$_classes[$class] ?? [];
}
/** /**
* @param DirectoryIterator $paths * @param DirectoryIterator $paths
* @param $namespace * @param $namespace
@@ -173,16 +146,7 @@ class Loader extends BaseObject
} }
$this->appendFileToDirectory($path->getRealPath(), $replace->getName()); $this->appendFileToDirectory($path->getRealPath(), $replace->getName());
$_array['handler'] = $replace->newInstance(); static::$_classes[] = $replace->getName();
$_array['target'] = [];
$_array['methods'] = [];
$_array['property'] = [];
$_array = $this->_targets($replace, $_array);
$_array = $this->_methods($replace, $_array);
$_array = $this->_properties($replace, $_array);
static::$_classes[$replace->getName()] = $_array;
} catch (Throwable $throwable) { } catch (Throwable $throwable) {
$this->addError($throwable, 'throwable'); $this->addError($throwable, 'throwable');
} }
@@ -202,75 +166,6 @@ class Loader extends BaseObject
} }
/**
* @param ReflectionClass $replace
* @param array $_array
* @return array
*/
private function _targets(ReflectionClass $replace, array $_array): array
{
foreach ($replace->getAttributes() as $attribute) {
if ($attribute->getName() == Attribute::class) {
continue;
}
if ($attribute->getName() == Target::class) {
continue;
}
$_array['target'][] = $attribute->newInstance();
}
return $_array;
}
/**
* @param ReflectionClass $replace
* @param array $_array
* @return array
*/
private function _methods(ReflectionClass $replace, array $_array): array
{
$methods = $replace->getMethods(ReflectionMethod::IS_PUBLIC);
foreach ($methods as $method) {
$_method = [];
foreach ($method->getAttributes() as $attribute) {
if (!class_exists($attribute->getName())) {
continue;
}
$_method[] = $attribute->newInstance();
}
if (!empty($_method)) {
static::$_methods[$replace->getName()][$method->getName()] = $_method;
}
}
return $_array;
}
/**
* @param ReflectionClass $replace
* @param array $_array
* @return array
*/
private function _properties(ReflectionClass $replace, array $_array): array
{
$methods = $replace->getProperties();
foreach ($methods as $method) {
$_property = [];
if ($method->isStatic()) continue;
foreach ($method->getAttributes() as $attribute) {
if (!class_exists($attribute->getName())) {
continue;
}
$_property[] = $attribute->newInstance();
}
if (!empty($_property)) {
static::$_property[$replace->getName()][$method->getName()] = $_property;
}
}
return $_array;
}
/** /**
* @param string $path * @param string $path
* @param string|array $outPath * @param string|array $outPath
@@ -280,15 +175,22 @@ class Loader extends BaseObject
{ {
try { try {
$path = '/' . trim($path, '/'); $path = '/' . trim($path, '/');
$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) || in_array($key, $outPath)) { if (!str_starts_with($key, $path) || in_array($key, $outPath)) {
continue; continue;
} }
$this->execute($_path);
foreach ($_path as $item) {
$paths[] = $item;
}
} }
return $paths;
} catch (Throwable $exception) { } catch (Throwable $exception) {
$this->addError($exception, 'throwable'); $this->addError($exception, 'throwable');
return [];
} }
} }
@@ -326,38 +228,4 @@ class Loader extends BaseObject
} }
/**
* @param array $classes
* @throws Exception
*/
private function execute(array $classes)
{
if (empty($classes)) {
return;
}
foreach ($classes as $className) {
if (!isset(static::$_methods[$className])) {
continue;
}
foreach (static::$_methods[$className] as $name => $attribute) {
$this->methods($attribute, $className, $name);
}
}
}
/**
* @param $attribute
* @param $annotation
* @param $className
* @param $name
*/
private function methods($attribute, $className, $name)
{
$handler = static::$_classes[$className]['handler'];
foreach ($attribute as $value) {
$value->execute($handler, $name);
}
}
} }
-2
View File
@@ -4,9 +4,7 @@
namespace Annotation\Model; namespace Annotation\Model;
use Annotation\Annotation;
use Attribute; use Attribute;
use Database\ActiveRecord;
use Exception; use Exception;
use Snowflake\Snowflake; use Snowflake\Snowflake;
-52
View File
@@ -1,52 +0,0 @@
<?php
namespace Annotation\Route;
use Annotation\Attribute;
use JetBrains\PhpStorm\Pure;
use Snowflake\Snowflake;
/**
* Class Interceptor
* @package Annotation\Route
*/
#[\Attribute(\Attribute::TARGET_METHOD)] class Interceptor extends Attribute
{
/**
* Interceptor constructor.
* @param string|array $interceptor
* @throws
*/
public function __construct(public string|array $interceptor)
{
if (is_string($this->interceptor)) {
$this->interceptor = [$this->interceptor];
}
foreach ($this->interceptor as $key => $value) {
$sn = Snowflake::createObject($value);
if (!($sn instanceof \HttpServer\IInterface\Interceptor)) {
continue;
}
$this->interceptor[$key] = [$sn, 'Interceptor'];
}
}
/**
* @param mixed $class
* @param mixed|null $method
* @return Interceptor
*/
public function execute(mixed $class, mixed $method = null): static
{
return $this;
}
}
-52
View File
@@ -1,52 +0,0 @@
<?php
namespace Annotation\Route;
use Annotation\Attribute;
use Snowflake\Snowflake;
/**
* Class Limits
* @package Annotation\Route
*/
#[\Attribute(\Attribute::TARGET_METHOD)] class Limits extends Attribute
{
/**
* Limits constructor.
* @param string|array $limits
* @throws
*/
public function __construct(public string|array $limits)
{
if (is_string($this->limits)) {
$this->limits = [$this->limits];
}
foreach ($this->limits as $key => $value) {
$sn = Snowflake::createObject($value);
if (!($sn instanceof \HttpServer\IInterface\Limits)) {
continue;
}
$this->limits[$key] = [$sn, 'next'];
}
}
/**
* @param mixed $class
* @param mixed|null $method
* @return Limits
*/
public function execute(mixed $class, mixed $method = null): static
{
return $this;
}
}
+31 -28
View File
@@ -5,6 +5,7 @@ namespace Annotation\Route;
use Annotation\Attribute; use Annotation\Attribute;
use HttpServer\Route\Middlewares;
use Snowflake\Snowflake; use Snowflake\Snowflake;
use HttpServer\IInterface\Middleware as IMiddleware; use HttpServer\IInterface\Middleware as IMiddleware;
@@ -16,38 +17,40 @@ use HttpServer\IInterface\Middleware as IMiddleware;
{ {
/** /**
* Interceptor constructor. * Interceptor constructor.
* @param string|array $middleware * @param string|array $middleware
* @throws * @throws
*/ */
public function __construct(public string|array $middleware) public function __construct(public string|array $middleware)
{ {
if (is_string($this->middleware)) { if (is_string($this->middleware)) {
$this->middleware = [$this->middleware]; $this->middleware = [$this->middleware];
} }
$array = []; $array = [];
foreach ($this->middleware as $key => $value) { foreach ($this->middleware as $value) {
$sn = Snowflake::createObject($value); $sn = Snowflake::createObject($value);
if (!($sn instanceof IMiddleware)) { if (!($sn instanceof IMiddleware)) {
continue; continue;
} }
$array[] = [$sn, 'onHandler']; $array[] = [$sn, 'onHandler'];
} }
$this->middleware = $array; $this->middleware = $array;
} }
/** /**
* @param mixed $class * @param mixed $class
* @param mixed|null $method * @param mixed|null $method
* @return Middleware * @return Middleware
*/ */
public function execute(mixed $class, mixed $method = null): static public function execute(mixed $class, mixed $method = null): static
{ {
return $this; $middleware = Snowflake::getDi()->get(Middlewares::class);
} $middleware->addMiddlewares($class, $method, $this->middleware);
return $this;
}
} }
+34 -27
View File
@@ -13,36 +13,43 @@ use Snowflake\Snowflake;
#[\Attribute(\Attribute::TARGET_METHOD)] class Route extends Attribute #[\Attribute(\Attribute::TARGET_METHOD)] class Route extends Attribute
{ {
/** /**
* Route constructor. * Route constructor.
* @param string $uri * @param string $uri
* @param string $method * @param string $method
* @param string $version * @param string $version
*/ */
public function __construct( public function __construct(
public string $uri, public string $uri,
public string $method, public string $method,
public string $version = 'v.1.0' public string $version = 'v.1.0'
) )
{ {
} }
/** /**
* @param mixed $class * @param mixed $class
* @param mixed|null $method * @param mixed|null $method
* @return Router * @return Router
* @throws Exception * @throws Exception
*/ */
public function execute(mixed $class, mixed $method = null): Router public function execute(mixed $class, mixed $method = null): Router
{ {
// TODO: Implement setHandler() method. // TODO: Implement setHandler() method.
$router = Snowflake::app()->getRouter(); $router = Snowflake::app()->getRouter();
$node = $router->addRoute($this->uri, [$class, $method], $this->method);
$router->addRoute($this->uri, [$class, $method], $this->method); if ($node !== null) {
$attribute = Snowflake::getDi()->getMethodAttribute($class::class, $method);
return $router; foreach ($attribute as $item) {
} if ($item instanceof Route) {
continue;
}
$item->execute($class, $method);
}
}
return $router;
}
} }
+69
View File
@@ -0,0 +1,69 @@
<?php
namespace HttpServer\Route;
use HttpServer\IInterface\Middleware;
use Snowflake\Abstracts\BaseObject;
/**
* Class Middlewares
* @package HttpServer\Route
*/
class Middlewares extends BaseObject
{
private static array $_middlewares = [];
/**
* @param $class
* @param $method
* @param array|string $middlewares
*/
public function addMiddlewares($class, $method, array|string $middlewares)
{
if (is_object($class)) {
$class = get_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;
return;
}
foreach ($middlewares as $middleware) {
if (in_array($middlewares, static::$_middlewares[$class . '::' . $method])) {
continue;
}
static::$_middlewares[$class . '::' . $method][] = $middleware;
}
}
/**
* @param $class
* @param $method
* @param $caller
*/
public function callerMiddlewares($class, $method, $caller)
{
$middlewares = static::$_middlewares[$class . '::' . $method] ?? [];
if (empty($middlewares)) {
return $caller;
}
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);
}
}
+283 -525
View File
@@ -5,15 +5,10 @@ declare(strict_types=1);
namespace HttpServer\Route; namespace HttpServer\Route;
use Annotation\Route\After;
use Annotation\Route\Interceptor;
use Annotation\Route\Limits;
use Annotation\Route\Middleware;
use Annotation\Route\RpcProducer; use Annotation\Route\RpcProducer;
use Closure; use Closure;
use Exception; use Exception;
use HttpServer\Abstracts\HttpService; use HttpServer\Abstracts\HttpService;
use HttpServer\Controller;
use HttpServer\Http\Context; use HttpServer\Http\Context;
use HttpServer\Http\Request; use HttpServer\Http\Request;
use JetBrains\PhpStorm\Pure; use JetBrains\PhpStorm\Pure;
@@ -22,7 +17,6 @@ use Snowflake\Aop;
use Snowflake\Core\Json; use Snowflake\Core\Json;
use Snowflake\Exception\NotFindClassException; use Snowflake\Exception\NotFindClassException;
use Snowflake\Snowflake; use Snowflake\Snowflake;
use Throwable;
/** /**
* Class Node * Class Node
@@ -31,524 +25,288 @@ use Throwable;
class Node extends HttpService class Node extends HttpService
{ {
public string $path = ''; public string $path = '';
public int $index = 0; public int $index = 0;
public string $method = ''; public string $method = '';
/** @var Node[] $childes */ /** @var Node[] $childes */
public array $childes = []; public array $childes = [];
public array $group = []; public array $group = [];
private string $_error = ''; private string $_error = '';
private string $_dataType = ''; private string $_dataType = '';
/** @var ?Closure|?array */ /** @var ?Closure|?array */
public Closure|array|null $handler; public Closure|array|null $handler;
public string $htmlSuffix = '.html'; public string $htmlSuffix = '.html';
public bool $enableHtmlSuffix = false; public bool $enableHtmlSuffix = false;
public array $namespace = []; public array $namespace = [];
public array $middleware = []; public array $middleware = [];
/** @var array|Closure */ /** @var array|Closure */
public Closure|array $callback = []; public Closure|array $callback = [];
private string $_alias = ''; private string $_alias = '';
private array $_interceptors = [];
private array $_after = []; /**
private array $_limits = []; * @param string $dataType
*/
public function setDataType(string $dataType)
/** {
* @param string $dataType $this->_dataType = $dataType;
*/ }
public function setDataType(string $dataType)
{
$this->_dataType = $dataType; /**
} * @param string $data
* @return mixed
*/
/** public function unpack(string $data): mixed
* @param string $data {
* @return mixed if ($this->_dataType == RpcProducer::PROTOCOL_JSON) {
*/ return json_decode($data, true);
public function unpack(string $data): mixed }
{ if ($this->_dataType == RpcProducer::PROTOCOL_SERIALIZE) {
if ($this->_dataType == RpcProducer::PROTOCOL_JSON) { return unserialize($data);
return json_decode($data, true); }
} return $data;
if ($this->_dataType == RpcProducer::PROTOCOL_SERIALIZE) { }
return unserialize($data);
}
return $data; /**
} * @param $handler
* @return Node
* @throws
/** */
* @param $handler public function bindHandler($handler): static
* @return Node {
* @throws if (is_string($handler) && str_contains($handler, '@')) {
*/ list($controller, $action) = explode('@', $handler);
public function bindHandler($handler): static if (!class_exists($controller) && !empty($this->namespace)) {
{ $controller = implode('\\', $this->namespace) . '\\' . $controller;
if (is_string($handler) && str_contains($handler, '@')) { }
list($controller, $action) = explode('@', $handler); $this->handler = [Snowflake::getDi()->get($controller), $action];
if (!class_exists($controller) && !empty($this->namespace)) { } else if ($handler != null && !is_callable($handler, true)) {
$controller = implode('\\', $this->namespace) . '\\' . $controller; $this->_error = 'Controller is con\'t exec.';
} } else {
$this->handler = $this->getReflect($controller, $action); $this->handler = $handler;
} else if ($handler != null && !is_callable($handler, true)) { }
$this->_error = 'Controller is con\'t exec.'; if (!empty($this->handler)) {
} else if ($handler instanceof Closure) { $this->callback = di(Middlewares::class)->callerMiddlewares(
$this->handler = $handler; $this->handler[0], $this->handler[1], $this->createDispatch()
} else { );
[$controller, $action] = $this->handler = $handler; }
if (!($controller instanceof Controller)) { return $this;
return $this; }
}
$this->annotationInject($controller::class, $action);
} /**
if (!empty($this->handler)) { * @throws ReflectionException
$this->callback = Reduce::reduce($this->createDispatch(), $this->annotation()); * @throws NotFindClassException
$this->setAop(); * @throws Exception
} */
return $this; private function createDispatch()
} {
$application = $this;
private array $_aop;
/** @var Aop $aop */
$aop = Snowflake::app()->get('aop');
/** if (!is_array($this->handler) || !$aop->hasAop($this->handler)) {
* @return Closure return static function () use ($application) {
* @throws Exception $dispatchParam = Context::getContext('dispatch-param', [\request()]);
*/
public function createDispatch(): Closure return call_user_func($application->handler, ...$dispatchParam);
{ };
$application = $this; }
return static function () use ($application) {
$dispatchParam = Context::getContext('dispatch-param', [\request()]); $reflect = $aop->getAop($this->handler);
if (!empty($application->_aop)) { $callback = [$reflect->getMethod('invoke'), 'invokeArgs'];
return call_user_func($application->_aop[0], $application->_aop[1], $dispatchParam);
} return static function () use ($callback, $application, $reflect) {
return call_user_func($application->handler, ...$dispatchParam); $dispatchParam = Context::getContext('dispatch-param', [\request()]);
};
} $asp = $reflect->newInstance($this->handler);
call_user_func($callback, $asp, $dispatchParam);
/** };
* @throws ReflectionException }
* @throws NotFindClassException
* @throws Exception
*/ /**
private function setAop() * @return array
{ */
/** @var Aop $aop */ #[Pure] protected function annotation(): array
$aop = Snowflake::app()->get('aop'); {
if (!is_array($this->handler) || !$aop->hasAop($this->handler)) { return $this->getMiddleWares();
return; }
}
$reflect = $aop->getAop($this->handler);
$this->_aop = [ /**
[$reflect->getMethod('invoke'), 'invokeArgs'], * @param Request $request
$reflect->newInstance($this->handler) * @return bool
]; */
} public function methodAllow(Request $request): bool
{
if ($this->method == $request->getMethod()) {
private bool $_hasBeforeAction = false; return true;
}
return $this->method == 'any';
/** }
* @return bool
* @throws Exception /**
*/ * @return bool
public function beforeAction(): bool * @throws Exception
{ */
if (!$this->_hasBeforeAction) return true; public function checkSuffix(): bool
[$controller, $action] = $this->handler; {
if (!$controller->beforeAction(\request())) { if ($this->enableHtmlSuffix) {
return false; $url = request()->getUri();
} $nowLength = strlen($this->htmlSuffix);
return true; if (strpos($url, $this->htmlSuffix) !== strlen($url) - $nowLength) {
} return false;
}
}
/** return true;
* @return array }
*/
#[Pure] protected function annotation(): array
{ /**
$middleWares = $this->getMiddleWares(); * @param Closure|array|string $handler
$middleWares = $this->annotation_limit($this, $middleWares); * @throws Exception
return $this->annotation_interceptor($this, $middleWares); */
} public function addLimits(Closure|string|array $handler)
{
if (!is_array($handler) || is_object($handler[0])) {
/** $handler = [$handler];
* @param Node $node }
* @param array $middleWares foreach ($handler as $closure) {
* @return array if (in_array($closure, $this->_limits)) {
*/ continue;
#[Pure] protected function annotation_interceptor(Node $node, array $middleWares = []): array }
{ $this->_limits[] = $closure;
if (!$node->hasInterceptor()) { }
return $middleWares; }
}
foreach ($node->getInterceptor() as $item) {
$middleWares[] = $item; /**
} * @return string
return $middleWares; * 错误信息
} */
public function getError(): string
{
/** return $this->_error;
* @param Node $node }
* @param array $middleWares
* @return array /**
*/ * @param Node $node
#[Pure] protected function annotation_limit(Node $node, array $middleWares = []): array * @param string $field
{ * @return Node
if (!$node->hasLimits()) { */
return $middleWares; public function addChild(Node $node, string $field): Node
} {
foreach ($node->getLimits() as $item) { $field = (string)$field;
$middleWares[] = $item; /** @var Node $oLod */
} $oLod = $this->childes[$field] ?? null;
return $middleWares; if (!empty($oLod)) {
} $node = $oLod;
}
$this->childes[$field] = $node;
/** return $this->childes[$field];
* @return bool }
*/
#[Pure] public function hasInterceptor(): bool
{ /**
return count($this->_interceptors) > 0; * @param string $search
} * @return Node|null
* @throws Exception
*/
/** public function findNode(string $search): ?Node
* @return bool {
*/ if (empty($this->childes)) {
#[Pure] public function hasLimits(): bool return null;
{ }
return count($this->_limits) > 0; if (isset($this->childes[$search])) {
} return $this->childes[$search];
}
foreach ($this->childes as $key => $val) {
/** if ($search == $key) {
* @param null $response return $this->childes[$key];
* @return mixed }
* @throws Exception }
*/ return null;
public function afterDispatch($response = null): mixed }
{
if (is_object($this->_after[0])) {
return call_user_func($this->_after, \request(), $response); /**
} * @param string $alias
foreach ($this->_after as $value) { * @return $this
call_user_func($value, \request(), $response); * 别称
} */
return $this->_after; public function alias(string $alias): static
} {
$this->_alias = $alias;
return $this;
/** }
* @return array
*/
public function getInterceptor(): array /**
{ * @return string
return $this->_interceptors; */
} public function getAlias(): string
{
return $this->_alias;
/** }
* @return array
*/
public function getAfters(): array /**
{ * @param Closure|array $class
return $this->_after; * @return $this
} */
public function addMiddleware(Closure|array $class): static
{
/** if (empty($class)) return $this;
* @return bool foreach ($class as $closure) {
*/ if (in_array($closure, $this->middleware)) {
#[Pure] public function hasAfter(): bool continue;
{ }
return count($this->_after) > 0; $this->middleware[] = $closure;
} }
return $this;
}
/**
* @return array
*/ /**
public function getLimits(): array * @return array
{ */
return $this->_limits; public function getMiddleWares(): array
} {
return $this->middleware;
/** }
* @param Request $request
* @return bool
*/ /**
public function methodAllow(Request $request): bool * @return mixed
{ * @throws Exception
if ($this->method == $request->getMethod()) { */
return true; public function dispatch(): mixed
} {
return $this->method == 'any'; Context::setContext('dispatch-param', func_get_args());
} if (empty($this->callback)) {
return Json::to(404, $this->errorMsg());
/** }
* @return bool return call_user_func($this->callback, \request());
* @throws Exception }
*/
public function checkSuffix(): bool
{ /**
if ($this->enableHtmlSuffix) { * @return string
$url = request()->getUri(); */
$nowLength = strlen($this->htmlSuffix); private function errorMsg(): string
if (strpos($url, $this->htmlSuffix) !== strlen($url) - $nowLength) { {
return false; return $this->_error ?? 'Page not found.';
} }
}
return true;
}
/**
* @param string $controller
* @param string $action
* @return null|array
* @throws Exception
*/
private function getReflect(string $controller, string $action): ?array
{
try {
$reflect = Snowflake::getDi()->getReflect($controller);
if (empty($reflect)) {
throw new Exception($controller . ' Class is con\'t Instantiable.');
}
if (!empty($action) && !$reflect->hasMethod($action)) {
throw new Exception('method ' . $action . ' not exists at ' . $controller . '.');
}
$this->_hasBeforeAction = $reflect->hasMethod('beforeAction');
$this->annotationInject($reflect->getName(), $action);
return [$reflect->newInstance(), $action];
} catch (Throwable $exception) {
$this->_error = $exception->getMessage();
$this->addError($exception, 'router');
return null;
}
}
/**
* @param Closure|array|string $handler
* @throws Exception
*/
public function addInterceptor(Closure|string|array $handler)
{
if (!is_array($handler) || is_object($handler[0])) {
$handler = [$handler];
}
foreach ($handler as $closure) {
if (in_array($closure, $this->_interceptors)) {
continue;
}
$this->_interceptors[] = $closure;
}
}
/**
* @param string $className
* @param string $action
* @return Node
* @throws Exception
*/
public function annotationInject(string $className, string $action): Node
{
$annotation = annotation()->getMethods($className, $action);
if (empty($annotation)) {
return $this;
}
foreach ($annotation as $attribute) {
if ($attribute instanceof Interceptor) {
$this->addInterceptor($attribute->interceptor);
}
if ($attribute instanceof After) {
$this->addAfter($attribute->after);
}
if ($attribute instanceof Middleware) {
$this->addMiddleware($attribute->middleware);
}
if ($attribute instanceof Limits) {
$this->addLimits($attribute->limits);
}
}
return $this;
}
/**
* @param Closure|array|string $handler
* @throws Exception
*/
public function addAfter(Closure|string|array $handler)
{
if (!is_array($handler) || is_object($handler[0])) {
$handler = [$handler];
}
foreach ($handler as $closure) {
if (in_array($closure, $this->_after)) {
continue;
}
$this->_after[] = $closure;
}
}
/**
* @param Closure|array|string $handler
* @throws Exception
*/
public function addLimits(Closure|string|array $handler)
{
if (!is_array($handler) || is_object($handler[0])) {
$handler = [$handler];
}
foreach ($handler as $closure) {
if (in_array($closure, $this->_limits)) {
continue;
}
$this->_limits[] = $closure;
}
}
/**
* @return string
* 错误信息
*/
public function getError(): string
{
return $this->_error;
}
/**
* @param Node $node
* @param string $field
* @return Node
*/
public function addChild(Node $node, string $field): Node
{
$field = (string)$field;
/** @var Node $oLod */
$oLod = $this->childes[$field] ?? null;
if (!empty($oLod)) {
$node = $oLod;
}
$this->childes[$field] = $node;
return $this->childes[$field];
}
/**
* @param string $search
* @return Node|null
* @throws Exception
*/
public function findNode(string $search): ?Node
{
if (empty($this->childes)) {
return null;
}
if (isset($this->childes[$search])) {
return $this->childes[$search];
}
foreach ($this->childes as $key => $val) {
if ($search == $key) {
return $this->childes[$key];
}
}
return null;
}
/**
* @param string $alias
* @return $this
* 别称
*/
public function alias(string $alias): static
{
$this->_alias = $alias;
return $this;
}
/**
* @return string
*/
public function getAlias(): string
{
return $this->_alias;
}
/**
* @param Closure|array $class
* @return $this
*/
public function addMiddleware(Closure|array $class): static
{
if (empty($class)) return $this;
foreach ($class as $closure) {
if (in_array($closure, $this->middleware)) {
continue;
}
$this->middleware[] = $closure;
}
return $this;
}
/**
* @return array
*/
public function getMiddleWares(): array
{
return $this->middleware;
}
/**
* @return mixed
* @throws Exception
*/
public function dispatch(): mixed
{
Context::setContext('dispatch-param', func_get_args());
if (empty($this->callback)) {
return Json::to(404, $this->errorMsg());
}
return call_user_func($this->callback, \request());
}
/**
* @return string
*/
private function errorMsg(): string
{
return $this->_error ?? 'Page not found.';
}
} }
+5 -41
View File
@@ -19,52 +19,16 @@ class Reduce
* @return mixed * @return mixed
*/ */
public static function reduce($last, $middleWares): mixed public static function reduce($last, $middleWares): mixed
{
return array_reduce(array_reverse($middleWares), static::core(), $last);
}
/**
* @param $middleWares
* @return mixed
*/
public static function after($middleWares): mixed
{ {
return array_reduce(array_reverse($middleWares), function ($stack, $pipe) { return array_reduce(array_reverse($middleWares), function ($stack, $pipe) {
return function ($request, $passable) use ($stack, $pipe) { return function ($passable) use ($stack, $pipe) {
if (!($pipe instanceof After)) { if ($pipe instanceof Middleware) {
return call_user_func($pipe, $request, $passable, $stack); return $pipe->onHandler($passable, $stack);
} }
return $pipe->onHandler($request, $passable); return call_user_func($pipe, $passable, $stack);
}; };
}); }, $last);
} }
/**
* @return Closure
*/
private static function core(): Closure
{
return function ($stack, $pipe) {
return static::passable($stack, $pipe);
};
}
/**
* @param $stack
* @param $pipe
* @return Closure
*/
public static function passable($stack, $pipe): Closure
{
return function ($passable) use ($stack, $pipe) {
if ($pipe instanceof Middleware) {
return $pipe->onHandler($passable, $stack);
}
return call_user_func($pipe, $passable, $stack);
};
}
} }
+12 -11
View File
@@ -44,6 +44,9 @@ class Router extends HttpService implements RouterInterface
public int $useTree = ROUTER_TREE; public int $useTree = ROUTER_TREE;
private static array $controllers = [];
public ?Response $response = null; public ?Response $response = null;
@@ -119,10 +122,6 @@ class Router extends HttpService implements RouterInterface
$handler = Closure::bind($handler, new Controller()); $handler = Closure::bind($handler, new Controller());
} }
// if ($this->useTree === ROUTER_TREE) {
// return $this->tree($path, $handler, $method);
// }
return $this->hash($path, $handler, $method); return $this->hash($path, $handler, $method);
} }
@@ -136,7 +135,6 @@ class Router extends HttpService implements RouterInterface
private function hash($path, $handler, string $method = 'any'): ?Node private function hash($path, $handler, string $method = 'any'): ?Node
{ {
$path = $this->resolve($path); $path = $this->resolve($path);
static::$nodes[$method][$path] = $this->NodeInstance($path, 0, $method); static::$nodes[$method][$path] = $this->NodeInstance($path, 0, $method);
return static::$nodes[$method][$path]->bindHandler($handler); return static::$nodes[$method][$path]->bindHandler($handler);
@@ -343,11 +341,9 @@ class Router extends HttpService implements RouterInterface
if ($this->middleware instanceof \Closure) { if ($this->middleware instanceof \Closure) {
$node->addMiddleware([$this->middleware]); $node->addMiddleware([$this->middleware]);
} }
if (is_array($name)) { if (is_array($name)) {
$node->addMiddleware($this->resolve_middleware($name)); $node->addMiddleware($this->resolve_middleware($name));
} }
return $node; return $node;
} }
@@ -527,10 +523,7 @@ class Router extends HttpService implements RouterInterface
$this->response->setFormat(Response::HTML); $this->response->setFormat(Response::HTML);
$this->response->send('<h1 style="text-align: center;">404</h1>'); $this->response->send('<h1 style="text-align: center;">404</h1>');
} else { } else {
$this->response->send(($response = $node->dispatch()), 200); $this->response->send($node->dispatch(), 200);
if ($node->hasAfter()) {
$node->afterDispatch($response);
}
} }
} }
@@ -637,6 +630,14 @@ class Router extends HttpService implements RouterInterface
public function _loader() public function _loader()
{ {
$this->loadRouteDir(APP_PATH . 'routes'); $this->loadRouteDir(APP_PATH . 'routes');
$classes = Snowflake::getAnnotation()->runtime(CONTROLLER_PATH);
foreach ($classes as $class) {
$instance = Snowflake::getDi()->get($class);
$methods = Snowflake::getDi()->getMethodAttribute($class);
foreach ($methods as $method => $attribute) {
$attribute->execute($instance, $method);
}
}
} }
/** /**
-5
View File
@@ -56,15 +56,10 @@ class ServerWorker extends \Server\Abstracts\Server
echo sprintf("\033[36m[" . date('Y-m-d H:i:s') . "]\033[0m Worker[%d].%d start.", $server->worker_pid, $workerId) . PHP_EOL; echo sprintf("\033[36m[" . date('Y-m-d H:i:s') . "]\033[0m Worker[%d].%d start.", $server->worker_pid, $workerId) . PHP_EOL;
$this->setProcessName(sprintf('Worker[%d].%d', $server->worker_pid, $workerId)); $this->setProcessName(sprintf('Worker[%d].%d', $server->worker_pid, $workerId));
$annotation->runtime(CONTROLLER_PATH);
$annotation->runtime(MODEL_PATH);
} else { } else {
echo sprintf("\033[36m[" . date('Y-m-d H:i:s') . "]\033[0m Tasker[%d].%d start.", $server->worker_pid, $workerId) . PHP_EOL; echo sprintf("\033[36m[" . date('Y-m-d H:i:s') . "]\033[0m Tasker[%d].%d start.", $server->worker_pid, $workerId) . PHP_EOL;
$this->setProcessName(sprintf('Tasker[%d].%d', $server->worker_pid, $workerId)); $this->setProcessName(sprintf('Tasker[%d].%d', $server->worker_pid, $workerId));
$annotation->runtime(APP_PATH, [CONTROLLER_PATH]);
} }
} }
+443 -308
View File
@@ -9,13 +9,16 @@ declare(strict_types=1);
namespace Snowflake\Di; namespace Snowflake\Di;
use Annotation\Attribute;
use Annotation\Inject; use Annotation\Inject;
use Annotation\Target;
use Exception; use Exception;
use ReflectionClass; use ReflectionClass;
use ReflectionException; use ReflectionException;
use ReflectionMethod; use ReflectionMethod;
use ReflectionProperty; use ReflectionProperty;
use Snowflake\Abstracts\BaseObject; use Snowflake\Abstracts\BaseObject;
use Snowflake\Abstracts\Configure;
use Snowflake\Exception\NotFindClassException; use Snowflake\Exception\NotFindClassException;
use Snowflake\Snowflake; use Snowflake\Snowflake;
@@ -26,344 +29,476 @@ use Snowflake\Snowflake;
class Container extends BaseObject class Container extends BaseObject
{ {
/** /**
* @var array * @var array
* *
* instance class by className * instance class by className
*/ */
private array $_singletons = []; private static array $_singletons = [];
/** /**
* @var array * @var array
* *
* class new instance construct parameter * class new instance construct parameter
*/ */
private array $_constructs = []; private static array $_constructs = [];
/** /**
* @var array * @var array
* *
* implements \ReflectClass * implements \ReflectClass
*/ */
private array $_reflection = []; private static array $_reflection = [];
private array $_reflectionProperty = [];
private array $_property = []; /**
* @var ReflectionProperty[]
*/
private static array $_reflectionProperty = [];
/**
* @var ReflectionMethod[]
*/
private static array $_reflectionMethod = [];
/**
* @var ReflectionClass[]
*/
private static array $_reflectionClass = [];
/** /**
* @var array * @var array
* */
* The construct parameter private static array $_propertyAttributes = [];
*/
private array $_param = [];
/**
* @param $class
* @param array $constrict
* @param array $config
*
* @return mixed
* @throws NotFindClassException
* @throws ReflectionException
* @throws Exception
*/
public function get($class, array $constrict = [], array $config = []): mixed
{
if (isset($this->_singletons[$class])) {
return $this->_singletons[$class];
} else if (!isset($this->_constructs[$class])) {
return $this->resolve($class, $constrict, $config);
}
$definition = $this->_constructs[$class];
if (is_callable($definition, TRUE)) {
return call_user_func($definition, $this, $constrict, $config);
} else if (is_array($definition)) {
$object = $this->resolveDefinition($definition, $class, $config, $constrict);
} else if (is_object($definition)) {
return $this->_singletons[$class] = $definition;
} else {
throw new NotFindClassException($class);
}
return $this->_singletons[$class] = $object;
}
/** /**
* @param $definition * @var array
* @param $class */
* @param $config private static array $_methodsAttributes = [];
* @param $constrict
* @return mixed
* @throws NotFindClassException /**
* @throws ReflectionException * @var array
* @throws Exception */
*/ private static array $_targetAttributes = [];
private function resolveDefinition($definition, $class, $config, $constrict): mixed
{
if (!isset($definition['class'])) { private static array $_attributeMaping = [];
throw new NotFindClassException($class);
}
$_className = $definition['class']; /**
unset($definition['class']); * @var array
*
* The construct parameter
*/
private static array $_param = [];
/**
* @param $class
* @param array $constrict
* @param array $config
*
* @return mixed
* @throws NotFindClassException
* @throws ReflectionException
* @throws Exception
*/
public function get($class, array $constrict = [], array $config = []): mixed
{
if (isset(static::$_singletons[$class])) {
return static::$_singletons[$class];
} else if (!isset(static::$_constructs[$class])) {
return $this->resolve($class, $constrict, $config);
}
$definition = static::$_constructs[$class];
if (is_callable($definition, TRUE)) {
return call_user_func($definition, $this, $constrict, $config);
} else if (is_array($definition)) {
$object = $this->resolveDefinition($definition, $class, $config, $constrict);
} else if (is_object($definition)) {
return static::$_singletons[$class] = $definition;
} else {
throw new NotFindClassException($class);
}
return static::$_singletons[$class] = $object;
}
/**
* @param $definition
* @param $class
* @param $config
* @param $constrict
* @return mixed
* @throws NotFindClassException
* @throws ReflectionException
* @throws Exception
*/
private function resolveDefinition($definition, $class, $config, $constrict): mixed
{
if (!isset($definition['class'])) {
throw new NotFindClassException($class);
}
$_className = $definition['class'];
unset($definition['class']);
// $config = array_merge($definition, $config); // $config = array_merge($definition, $config);
$definition = $this->mergeParam($class, $constrict); $definition = $this->mergeParam($class, $constrict);
if ($_className === $class) { if ($_className === $class) {
$object = $this->resolve($class, $definition, $config); $object = $this->resolve($class, $definition, $config);
} else { } else {
$object = $this->get($class, $definition, $config); $object = $this->get($class, $definition, $config);
} }
return $object; return $object;
} }
/** /**
* @param $class * @param $class
* @param $constrict * @param $constrict
* @param $config * @param $config
* *
* @return object * @return object
* @throws Exception * @throws Exception
*/ */
private function resolve($class, $constrict, $config): object private function resolve($class, $constrict, $config): object
{ {
/** @var ReflectionClass $reflect */ /** @var ReflectionClass $reflect */
[$reflect, $dependencies] = $this->resolveDependencies($class); [$reflect, $dependencies] = $this->resolveDependencies($class);
if (empty($reflect)) { if (empty($reflect) || !$reflect->isInstantiable()) {
throw new NotFindClassException($class); throw new NotFindClassException($class);
} }
foreach ($constrict as $index => $param) { $dependencies = array_merge($dependencies, $constrict);
$dependencies[$index] = $param; unset($dependencies['class']);
} if (empty($config) || !is_array($config)) {
$object = $this->newInstance($reflect, $dependencies);
} else if (!empty($dependencies) && $reflect->implementsInterface(Configure::class)) {
$dependencies[count($dependencies) - 1] = $config;
$object = $this->newInstance($reflect, $dependencies);
} else {
if (!empty($config)) static::$_param[$class] = $config;
if (!$reflect->isInstantiable()) { $object = $this->onAfterInit($this->newInstance($reflect, $dependencies), $config);
throw new NotFindClassException($reflect->getName()); }
} static::$_reflectionClass[$reflect->getName()] = [];
foreach ($reflect->getAttributes() as $attribute) {
unset($dependencies['class']); static::$_reflectionClass[$reflect->getName()][] = $attribute->newInstance();
if (empty($config) || !is_array($config)) { }
$object = $this->newInstance($reflect, $dependencies); return $this->propertyInject($reflect, $object);
} else if (!empty($dependencies) && $reflect->implementsInterface('Snowflake\Abstracts\Configure')) { }
$dependencies[count($dependencies) - 1] = $config;
$object = $this->newInstance($reflect, $dependencies);
} else {
if (!empty($config)) $this->_param[$class] = $config;
$object = $this->onAfterInit($this->newInstance($reflect, $dependencies), $config);
}
return $this->propertyInject($reflect, $object);
}
/** /**
* @param $reflect * @param $reflect
* @param $dependencies * @param $dependencies
* @return mixed * @return mixed
*/ */
private function newInstance($reflect, $dependencies): mixed private function newInstance($reflect, $dependencies): mixed
{ {
if (!empty($dependencies)) { if (!empty($dependencies)) {
return $reflect->newInstanceArgs($dependencies); return $reflect->newInstanceArgs($dependencies);
} }
return $reflect->newInstance(); return $reflect->newInstance();
} }
/** /**
* @param ReflectionClass $reflect * @param ReflectionClass $reflect
* @param $object * @param $object
* @return mixed * @return mixed
* @throws Exception * @throws Exception
*/ */
private function propertyInject(ReflectionClass $reflect, $object): mixed private function propertyInject(ReflectionClass $reflect, $object): mixed
{ {
if (!isset($this->_property[$reflect->getName()])) { if (!isset(static::$_propertyAttributes[$reflect->getName()])) {
return $object; return $object;
} }
foreach ($this->_property[$reflect->getName()] as $property => $inject) { foreach (static::$_propertyAttributes[$reflect->getName()] as $property => $inject) {
/** @var Inject $inject */ /** @var Inject $inject */
$inject->execute($object, $property); $inject->execute($object, $property);
} }
return $object; return $object;
} }
/** /**
* @param string $class * @param \ReflectionClass $class
* @param string|null $property */
* @return ReflectionProperty|array|null private function resolveMethodAttribute(ReflectionClass $class)
*/ {
public function getClassProperty(string $class, string $property = null): ReflectionProperty|null|array if ($class->isAbstract() || $class->isTrait()) {
{ return;
if (!isset($this->_reflectionProperty[$class])) { }
return null; foreach ($class->getMethods() as $method) {
} if ($method->isStatic()) {
$properties = $this->_reflectionProperty[$class]; continue;
if (!empty($property)) { }
return $properties[$property] ?? null; static::$_reflectionMethod[$class->getName()][$method->getName()] = $method;
} static::$_methodsAttributes[$class->getName()][$method->getName()] = [];
return $properties; foreach ($method->getAttributes() as $attribute) {
} if (!class_exists($attribute->getName())) {
continue;
}
/** $instance = $attribute->newInstance();
* @param $object
* @param $config
* @return mixed
*/
private function onAfterInit($object, $config): mixed
{
Snowflake::configure($object, $config);
if (method_exists($object, 'afterInit')) {
call_user_func([$object, 'afterInit']);
}
return $object;
}
/** $this->setAttributeMapping($attribute, $class, $method, $instance);
* @param $class $this->setMethodsAttributes($class, $method, $instance);
* @return array|null static::$_methodsAttributes[$class->getName()][$method->getName()][] = $attribute->newInstance();
* @throws ReflectionException|NotFindClassException }
*/ }
private function resolveDependencies($class): ?array }
{
if (!isset($this->_reflection[$class])) {
$this->_reflection[$class] = new ReflectionClass($class);
if (!$this->_reflection[$class]->isInstantiable()) {
return null;
}
$this->scanProperty($this->_reflection[$class]);
}
if (!is_null($constructs = $this->_reflection[$class]->getConstructor())) {
$constructs = $this->resolveMethodParam($constructs);
}
return [$this->_reflection[$class], $constructs];
}
/** /**
* @param ReflectionClass $reflectionClass * @param \ReflectionAttribute $attribute
* @return void * @param \ReflectionClass $class
*/ * @param $object
private function scanProperty(ReflectionClass $reflectionClass): void */
{ private function setAttributeMapping(\ReflectionAttribute $attribute, ReflectionClass $class, $object)
$properties = $reflectionClass->getProperties(ReflectionProperty::IS_PUBLIC | {
ReflectionProperty::IS_PRIVATE | ReflectionProperty::IS_PROTECTED if (!isset(static::$_attributeMaping[$attribute->getName()])) {
); static::$_attributeMaping[$attribute->getName()] = [];
}
$className = $reflectionClass->getName(); static::$_attributeMaping[$attribute->getName()][$class->getName()][] = $object;
foreach ($properties as $property) { }
$targets = $property->getAttributes(Inject::class);
if (count($targets) < 1) {
continue;
}
$this->_reflectionProperty[$className][$property->getName()] = $property;
$this->_property[$className][$property->getName()] = $targets[0]->newInstance();
}
}
/** /**
* @param ReflectionMethod|null $method * @param \ReflectionAttribute $attribute
* @return array * @param \ReflectionClass $class
* @throws NotFindClassException * @param $object
* @throws ReflectionException */
*/ private function setMethodsAttributes(\ReflectionClass $attribute, ReflectionMethod $method, $object)
private function resolveMethodParam(?ReflectionMethod $method): array {
{ if (!isset(static::$_methodsAttributes[$attribute->getName()])) {
$array = []; static::$_methodsAttributes[$attribute->getName()] = [];
foreach ($method->getParameters() as $key => $parameter) { }
if ($parameter->isDefaultValueAvailable()) { static::$_methodsAttributes[$attribute->getName()][$method->getName()][] = $object;
$array[] = $parameter->getDefaultValue(); }
} else {
$type = $parameter->getType();
if (is_string($type) && class_exists($type)) {
$type = Snowflake::createObject($type);
}
$array[] = match ($parameter->getType()) {
'string' => '',
'int', 'float' => 0,
'', null, 'object', 'mixed' => NULL,
'bool' => false,
default => $type
};
}
}
return $array;
}
/** /**
* @param $class * @param \ReflectionClass $class
* @return ReflectionClass|null */
* @throws NotFindClassException private function resolveTargetAttribute(ReflectionClass $class)
* @throws ReflectionException {
*/ if ($class->isAbstract() || $class->isTrait()) {
public function getReflect($class): ?ReflectionClass return;
{ }
$reflect = $this->_reflection[$class] ?? null; foreach ($class->getAttributes() as $method) {
if (!is_null($reflect)) { if ($method->getName() == Target::class) {
return $reflect; continue;
} }
$reflect = $this->resolveDependencies($class); static::$_targetAttributes[$class->getName()] = $method->newInstance();
if (is_array($reflect)) { }
return $reflect[0]; }
}
return null;
}
/**
* @param $class
*/
public function unset($class)
{
if (is_array($class) && isset($class['class'])) {
$class = $class['class'];
} else if (is_object($class)) {
$class = $class::class;
}
unset(
$this->_reflection[$class], $this->_singletons[$class],
$this->_param[$class], $this->_constructs[$class]
);
}
/** /**
* @return $this * @param $className
*/ * @param $method
public function flush(): static * @return \ReflectionMethod|null
{ */
$this->_reflection = []; public function getReflectionMethod($className, $method): ?ReflectionMethod
$this->_singletons = []; {
$this->_param = []; return static::$_reflectionMethod[$className][$method] ?? null;
$this->_constructs = []; }
return $this;
}
/**
* @param $class /**
* @param $newParam * @param $className
* * @param $method
* @return mixed * @return array
*/ */
private function mergeParam($class, $newParam): array public function getMethodAttribute($className, $method = null): array
{ {
if (empty($this->_param[$class])) { $methods = static::$_methodsAttributes[$className] ?? [];
return $newParam; if ($method === null || empty($method)) {
} else if (empty($newParam)) { return $methods;
return $this->_param[$class]; }
} return $methods[$method] ?? [];
$old = $this->_param[$class]; }
foreach ($newParam as $key => $val) {
$old[$key] = $val;
} /**
return $old; * @param string $class
} * @param string|null $property
* @return ReflectionProperty|array|null
*/
public function getClassProperty(string $class, string $property = null): ReflectionProperty|null|array
{
if (!isset(static::$_reflectionProperty[$class])) {
return null;
}
$properties = static::$_reflectionProperty[$class];
if (!empty($property)) {
return $properties[$property] ?? null;
}
return $properties;
}
/**
* @param $object
* @param $config
* @return mixed
*/
private function onAfterInit($object, $config): mixed
{
Snowflake::configure($object, $config);
if (method_exists($object, 'afterInit')) {
call_user_func([$object, 'afterInit']);
}
return $object;
}
/**
* @param $class
* @return array|null
* @throws ReflectionException|NotFindClassException
*/
private function resolveDependencies($class): ?array
{
if (!isset(static::$_reflection[$class])) {
static::$_reflection[$class] = new ReflectionClass($class);
if (!static::$_reflection[$class]->isInstantiable()) {
return null;
}
$this->resolveTargetAttribute(static::$_reflection[$class]);
$this->resolveMethodAttribute(static::$_reflection[$class]);
$this->scanProperty(static::$_reflection[$class]);
}
if (!is_null($constructs = static::$_reflection[$class]->getConstructor())) {
$constructs = $this->resolveMethodParam($constructs);
}
return [static::$_reflection[$class], $constructs];
}
/**
* @param ReflectionClass $reflectionClass
* @return void
*/
private function scanProperty(ReflectionClass $reflectionClass): void
{
$properties = $reflectionClass->getProperties(ReflectionProperty::IS_PUBLIC |
ReflectionProperty::IS_PRIVATE | ReflectionProperty::IS_PROTECTED
);
$className = $reflectionClass->getName();
foreach ($properties as $property) {
$targets = $property->getAttributes(Inject::class);
if (count($targets) < 1) {
continue;
}
static::$_reflectionProperty[$className][$property->getName()] = $property;
static::$_propertyAttributes[$className][$property->getName()] = $targets[0]->newInstance();
}
}
/**
* @param ReflectionMethod|null $method
* @return array
* @throws NotFindClassException
* @throws ReflectionException
*/
private function resolveMethodParam(?ReflectionMethod $method): array
{
$array = [];
foreach ($method->getParameters() as $key => $parameter) {
if ($parameter->isDefaultValueAvailable()) {
$array[] = $parameter->getDefaultValue();
} else {
$type = $parameter->getType();
if (is_string($type) && class_exists($type)) {
$type = Snowflake::createObject($type);
}
$array[] = match ($parameter->getType()) {
'string' => '',
'int', 'float' => 0,
'', null, 'object', 'mixed' => NULL,
'bool' => false,
default => $type
};
}
}
return $array;
}
/**
* @param $class
* @return ReflectionClass|null
* @throws NotFindClassException
* @throws ReflectionException
*/
public function getReflect($class): ?ReflectionClass
{
$reflect = static::$_reflection[$class] ?? null;
if (!is_null($reflect)) {
return $reflect;
}
$reflect = $this->resolveDependencies($class);
if (is_array($reflect)) {
return $reflect[0];
}
return null;
}
/**
* @param $class
*/
public function unset($class)
{
if (is_array($class) && isset($class['class'])) {
$class = $class['class'];
} else if (is_object($class)) {
$class = $class::class;
}
unset(
static::$_reflection[$class], static::$_singletons[$class],
static::$_param[$class], static::$_constructs[$class]
);
}
/**
* @return $this
*/
public function flush(): static
{
static::$_reflection = [];
static::$_singletons = [];
static::$_param = [];
static::$_constructs = [];
return $this;
}
/**
* @param $class
* @param $newParam
*
* @return mixed
*/
private function mergeParam($class, $newParam): array
{
if (empty(static::$_param[$class])) {
return $newParam;
} else if (empty($newParam)) {
return static::$_param[$class];
}
$old = static::$_param[$class];
foreach ($newParam as $key => $val) {
$old[$key] = $val;
}
return $old;
}
} }