Files
kiri-core/System/Aop.php
T

101 lines
2.3 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-04-21 01:45:59 +08:00
private array $_aop = [];
/**
* @param array $handler
* @param string $aspect
*/
public function aop_add(array $handler, string $aspect)
{
[$class, $method] = $handler;
2021-04-25 11:22:23 +08:00
$alias = $class::class . '::' . $method;
2021-04-21 01:45:59 +08:00
if (!isset($this->_aop[$alias])) {
$this->_aop[$alias] = [];
}
if (in_array($aspect, $this->_aop[$alias])) {
return;
}
$this->_aop[$alias][] = $aspect;
}
2021-04-22 14:22:11 +08:00
/**
* @param $handler
* @param $params
* @return mixed
* @throws NotFindClassException
* @throws ReflectionException
* @throws Exception
*/
2021-04-21 01:45:59 +08:00
final public function dispatch($handler, $params): mixed
{
if ($handler instanceof \Closure) {
return call_user_func($handler, ...$params);
}
2021-04-25 11:22:23 +08:00
$aopName = $handler[0]::class . '::' . $handler[1];
2021-04-21 01:45:59 +08:00
if (!isset($this->_aop[$aopName])) {
return $this->notFound($handler, $params);
}
return $this->invoke($handler, $params, $aopName);
}
2021-04-22 14:22:11 +08:00
/**
* @param $handler
* @param $params
* @param $aopName
* @return mixed
* @throws ReflectionException
* @throws NotFindClassException
* @throws Exception
*/
private function invoke($handler, $params, $aopName): mixed
2021-04-21 01:45:59 +08:00
{
$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($handler), $params);
}
2021-04-22 14:22:11 +08:00
/**
* @param $handler
* @param $params
* @return mixed
* @throws Exception
*/
private function notFound($handler, $params): mixed
2021-04-21 01:45:59 +08:00
{
if (!method_exists($handler[0], $handler[1])) {
return response()->close(404);
}
return call_user_func($handler, ...$params);
}
2021-03-29 03:09:55 +08:00
}