Files
kiri-core/System/Aop.php
T

73 lines
1.6 KiB
PHP
Raw Normal View History

2021-03-29 03:09:55 +08:00
<?php
namespace Snowflake;
2021-03-29 10:05:51 +08:00
use Exception;
use ReflectionException;
2021-03-29 03:09:55 +08:00
use Snowflake\Abstracts\Component;
2021-03-29 10:05:51 +08:00
use Snowflake\Exception\NotFindClassException;
2021-03-29 03:09:55 +08:00
defined('ASPECT_ERROR') or define('ASPECT_ERROR', 'Aspect annotation must implement ');
/**
* Class Aop
* @package Snowflake
*/
class Aop extends Component
{
2021-03-30 12:07:25 +08:00
private array $_aop = [];
2021-03-29 03:09:55 +08:00
2021-03-29 10:05:51 +08:00
/**
* @param array $handler
* @param string $aspect
*/
2021-03-30 12:07:25 +08:00
public function aop_add(array $handler, string $aspect)
{
[$class, $method] = $handler;
$alias = get_class($class) . '::' . $method;
if (!isset($this->_aop[$alias])) {
$this->_aop[$alias] = [];
}
if (in_array($aspect, $this->_aop[$alias])) {
return;
}
$this->_aop[$alias][] = $aspect;
}
2021-03-29 03:09:55 +08:00
2021-03-29 10:05:51 +08:00
/**
* @return mixed
* @throws NotFindClassException
* @throws ReflectionException
* @throws Exception
*/
2021-03-30 12:07:25 +08:00
final public function dispatch(): mixed
{
$get_args = func_get_args();
if (($close = array_shift($get_args)) instanceof \Closure) {
return call_user_func($close, ...$get_args);
}
$aopName = get_class($close[0]) . '::' . $close[1];
if (!isset($this->_aop[$aopName])) {
return call_user_func($close, ...$get_args);
}
2021-03-30 12:07:52 +08:00
$reflect = Snowflake::getDi()->getReflect(current($this->_aop[$aopName]));
2021-03-30 12:07:25 +08:00
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);
}
2021-03-29 03:09:55 +08:00
}