Files
hyperf_test/app/Aspect/CommonReturnAspect.php
2025-09-06 23:53:15 +08:00

83 lines
2.0 KiB
PHP

<?php
namespace App\Aspect;
use App\Interface\Test\Decorator\LoggerInterface;
use App\Lib\Return\AdminReturn;
use App\Lib\Return\CommonReturn;
use App\Lib\Return\TestReturn;
use Hyperf\Context\Context;
use Hyperf\Di\Annotation\Aspect;
use Hyperf\Di\Annotation\Inject;
use Hyperf\Di\Aop\AbstractAspect;
use Hyperf\Di\Aop\ProceedingJoinPoint;
use Hyperf\Di\Exception\Exception;
use Hyperf\HttpServer\Contract\RequestInterface;
#[Aspect]
class CommonReturnAspect extends AbstractAspect
{
/**
* 需要切入的类
* @var array|string[]
*/
public array $classes = [
AdminReturn::class,
TestReturn::class,
// CommonReturn::class,
];
/**
* 需要切入的注解
* @var array
*/
public array $annotations = [];
/**
* @var LoggerInterface
*/
#[Inject]
protected LoggerInterface $logger;
/**
* 依赖注入容器
* @param RequestInterface $request
* @param int $userId
*/
public function __construct(
private readonly RequestInterface $request,
private int $userId = 0
) {}
/**
* 切面逻辑
* @param ProceedingJoinPoint $proceedingJoinPoint
* @return mixed
* @throws Exception
*/
public function process(ProceedingJoinPoint $proceedingJoinPoint): mixed
{
// 在调用前进行处理
$result = $proceedingJoinPoint->process();
// 在调用后进行处理
// 未登录返回 0
$this->userId = Context::get('user_id',0);
$this->writeResponseLog(json_encode($result));
return $result;
}
/**
* 写入请求日志
* @param string $content
* @return void
*/
private function writeResponseLog(string $content): void
{
$this->logger->log('返回切入请求体:'.json_encode($this->request->all()));
$this->logger->log('返回切入用户id:'.$this->userId);
$this->logger->log('返回切入返回体:'.$content);
}
}