Files
hyperf_rbac_framework_serve…/app/Aspect/ResponseFormatAspect.php
2025-09-12 15:23:08 +08:00

52 lines
1.4 KiB
PHP

<?php
declare(strict_types=1);
namespace App\Aspect;
use App\Annotation\ResponseFormat;
use Hyperf\Di\Annotation\Aspect;
use Hyperf\Di\Aop\AbstractAspect;
use Hyperf\Di\Exception\Exception;
use Hyperf\HttpServer\Request;
use Psr\Container\ContainerInterface;
use Hyperf\Di\Aop\ProceedingJoinPoint;
#[Aspect]
class ResponseFormatAspect extends AbstractAspect
{
/**
* @var array|class-string[]
*/
public array $annotations = [
ResponseFormat::class,
];
/**
* @param ContainerInterface $container
*/
public function __construct(protected ContainerInterface $container) {}
/**
* @param ProceedingJoinPoint $proceedingJoinPoint
* @return mixed
* @throws Exception
*/
public function process(ProceedingJoinPoint $proceedingJoinPoint): mixed
{
// 获取注解定义的格式
$annotation = $proceedingJoinPoint->getAnnotationMetadata()->class[ResponseFormat::class]
?? $proceedingJoinPoint->getAnnotationMetadata()->method[ResponseFormat::class] ?? null;
if ($annotation) {
// 将注解格式存入请求属性(覆盖中间件的默认值)
$request = $proceedingJoinPoint->arguments['request'] ?? null;
if ($request instanceof Request) {
$request->withAttribute('response_format', $annotation->format);
}
}
return $proceedingJoinPoint->process();
}
}