This commit is contained in:
as2252258@163.com
2021-03-29 03:09:55 +08:00
parent 79acf12f71
commit b0cbcb0caa
4 changed files with 160 additions and 2 deletions
+65
View File
@@ -0,0 +1,65 @@
<?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();
[$class, $method] = array_shift($get_args);
$aopName = get_class($class) . '::' . $method;
if (!isset($this->_aop[$aopName])) {
return call_user_func($get_args, ...$get_args);
}
$reflect = new \ReflectionClass($this->_aop[$aopName]);
if (!$reflect->hasMethod('invoke')) {
throw new \Exception(ASPECT_ERROR . IAspect::class);
}
$method = $reflect->getMethod('invoke');
$data = $method->invokeArgs($reflect->newInstance([$class, $method]), $get_args);
if ($method->getReturnType() !== null) {
return $data;
}
}
}
+55
View File
@@ -0,0 +1,55 @@
<?php
namespace Snowflake\Error;
use Snowflake\IAspect;
/**
* Class LoggerAspect
* @package Snowflake\Error
*/
class LoggerAspect implements IAspect
{
private string $className = '';
private string $methodName = '';
/**
* LoggerAspect constructor.
* @param array $handler
*/
public function __construct(public array $handler, $needReturn)
{
$this->className = get_class($this->handler[0]);
$this->methodName = $this->handler[1];
}
/**
* @return mixed|void
*/
public function invoke()
{
$startTime = microtime(true);
$data = call_user_func($this->handler, func_get_args());
$this->print_runtime($startTime);
return $data;
}
private function print_runtime($startTime)
{
$runTime = round(microtime(true) - $startTime, 6);
echo sprintf('run %s::%s use time %6f', $this->className, $this->methodName, $runTime);
echo PHP_EOL;
}
}
+23
View File
@@ -0,0 +1,23 @@
<?php
namespace Snowflake;
interface IAspect
{
/**
* IAspect constructor.
* @param array $handler
*/
public function __construct(array $handler, bool $needRetruen);
/**
* @return mixed|void
*/
public function invoke();
}