diff --git a/src/Event/PostWasLiked.php b/src/Event/PostWasLiked.php index 5a99117..05af301 100644 --- a/src/Event/PostWasLiked.php +++ b/src/Event/PostWasLiked.php @@ -14,9 +14,30 @@ class PostWasLiked { - public function __construct( - public Post $post, - public User $user - ) { + /** + * @var Post + */ + public $post; + + /** + * @var User + */ + public $user; + + /** + * @var User + */ + public $actor; + + /** + * @param Post $post + * @param User $user + * @param User $actor + */ + public function __construct(Post $post, User $user, User $actor) + { + $this->post = $post; + $this->user = $user; + $this->actor = $actor; } } diff --git a/src/Event/PostWasUnliked.php b/src/Event/PostWasUnliked.php index 500da32..6eac5a1 100644 --- a/src/Event/PostWasUnliked.php +++ b/src/Event/PostWasUnliked.php @@ -14,9 +14,30 @@ class PostWasUnliked { - public function __construct( - public Post $post, - public User $user - ) { + /** + * @var Post + */ + public $post; + + /** + * @var User + */ + public $user; + + /** + * @var User + */ + public $actor; + + /** + * @param Post $post + * @param User $user + * @param User $actor + */ + public function __construct(Post $post, User $user, User $actor) + { + $this->post = $post; + $this->user = $user; + $this->actor = $actor; } } diff --git a/src/Listener/DispatchEventsTrait.php b/src/Listener/DispatchEventsTrait.php new file mode 100644 index 0000000..b433773 --- /dev/null +++ b/src/Listener/DispatchEventsTrait.php @@ -0,0 +1,76 @@ +releaseEvents() as $event) { + $this->injectActorToEvent($event, $actor); + $this->events->dispatch($event); + } + } + + /** + * 安全地注入 Actor 到事件对象 + * + * @param object $event 事件对象 + * @param User|null $actor 需要注入的用户 + * + * @throws LogicException 当事件不兼容时抛出异常 + */ + protected function injectActorToEvent(object $event, ?User $actor): void + { + // 优先使用类型安全的方法注入 + if ($event instanceof ActorAwareEventInterface) { + $event->setActor($actor); + return; + } + + // 兼容旧版事件的属性注入(带类型检查) + if (property_exists($event, 'actor')) { + if (!$event->actor instanceof User && null !== $event->actor) { + throw new LogicException( + sprintf('Event %s has non-user type for actor property', get_class($event)) + ); + } + + $event->actor = $actor; + return; + } + + // 调试模式下的警告记录 + if (getenv('FLARUM_DEBUG')) { + error_log( + sprintf('[Deprecation] Event %s does not implement actor injection interface', get_class($event)) + ); + } + } +} + +// 配套接口定义 +interface ActorAwareEventInterface +{ + /** + * 设置事件关联的操作用户 + * + * @param User|null $actor + */ + public function setActor(?User $actor): void; +} \ No newline at end of file