Files
kiri-core/System/Aop.php
T

68 lines
1.4 KiB
PHP
Raw Normal View History

2021-03-29 03:09:55 +08:00
<?php
namespace Snowflake;
use Snowflake\Abstracts\Component;
defined('ASPECT_ERROR') or define('ASPECT_ERROR', 'Aspect annotation must implement ');
/**
* Class Aop
* @package Snowflake
*/
class Aop extends Component
{
private array $_aop = [];
/**
* @param $className
* @param null $method
*/
public function aop_add(array $handler, string $aspect)
{
[$class, $method] = $handler;
if (!isset($this->_aop[$aspect])) {
$this->_aop[$aspect] = [];
}
$this->_aop[get_class($class) . '::' . $method][] = $aspect;
}
/**
* @return mixed|void
* @throws \ReflectionException
*/
final public function dispatch()
{
$get_args = func_get_args();
2021-03-29 03:23:05 +08:00
if (($close = array_shift($get_args)) instanceof \Closure) {
return call_user_func($close, ...$get_args);
}
2021-03-29 03:09:55 +08:00
2021-03-29 03:23:05 +08:00
$aopName = get_class($close[0]) . '::' . $close[1];
2021-03-29 03:09:55 +08:00
if (!isset($this->_aop[$aopName])) {
2021-03-29 03:23:05 +08:00
return call_user_func($close, ...$get_args);
2021-03-29 03:09:55 +08:00
}
$reflect = new \ReflectionClass($this->_aop[$aopName]);
if (!$reflect->hasMethod('invoke')) {
throw new \Exception(ASPECT_ERROR . IAspect::class);
}
$method = $reflect->getMethod('invoke');
2021-03-29 03:23:05 +08:00
$data = $method->invokeArgs($reflect->newInstance($close), $get_args);
2021-03-29 03:09:55 +08:00
if ($method->getReturnType() !== null) {
return $data;
}
}
}