This commit is contained in:
2021-04-19 14:33:14 +08:00
parent 18f541759f
commit db2db63ee7
+34 -30
View File
@@ -20,25 +20,25 @@ class Aop extends Component
{ {
private array $_aop = []; private array $_aop = [];
/** /**
* @param array $handler * @param array $handler
* @param string $aspect * @param string $aspect
*/ */
public function aop_add(array $handler, string $aspect) public function aop_add(array $handler, string $aspect)
{ {
[$class, $method] = $handler; [$class, $method] = $handler;
$alias = get_class($class) . '::' . $method; $alias = get_class($class) . '::' . $method;
if (!isset($this->_aop[$alias])) { if (!isset($this->_aop[$alias])) {
$this->_aop[$alias] = []; $this->_aop[$alias] = [];
} }
if (in_array($aspect, $this->_aop[$alias])) { if (in_array($aspect, $this->_aop[$alias])) {
return; return;
} }
$this->_aop[$alias][] = $aspect; $this->_aop[$alias][] = $aspect;
} }
/** /**
@@ -47,26 +47,30 @@ class Aop extends Component
* @throws ReflectionException * @throws ReflectionException
* @throws Exception * @throws Exception
*/ */
final public function dispatch(): mixed final public function dispatch(): mixed
{ {
$get_args = func_get_args(); $get_args = func_get_args();
if (($close = array_shift($get_args)) instanceof \Closure) { if (($close = array_shift($get_args)) instanceof \Closure) {
return call_user_func($close, ...$get_args); return call_user_func($close, ...$get_args);
} }
$aopName = get_class($close[0]) . '::' . $close[1]; if (empty($close)) {
if (!isset($this->_aop[$aopName])) { return response()->close(404);
return call_user_func($close, ...$get_args); }
}
$reflect = Snowflake::getDi()->getReflect(current($this->_aop[$aopName])); $aopName = get_class($close[0]) . '::' . $close[1];
if (!$reflect->isInstantiable() || !$reflect->hasMethod('invoke')) { if (!isset($this->_aop[$aopName])) {
throw new Exception(ASPECT_ERROR . IAspect::class); return call_user_func($close, ...$get_args);
} }
$method = $reflect->getMethod('invoke');
return $method->invokeArgs($reflect->newInstance($close), $get_args); $reflect = Snowflake::getDi()->getReflect(current($this->_aop[$aopName]));
} if (!$reflect->isInstantiable() || !$reflect->hasMethod('invoke')) {
throw new Exception(ASPECT_ERROR . IAspect::class);
}
$method = $reflect->getMethod('invoke');
return $method->invokeArgs($reflect->newInstance($close), $get_args);
}
} }