Files
chatroom/app/Events/MessageSent.php
T

112 lines
2.8 KiB
PHP
Raw Normal View History

<?php
/**
* 文件功能:用户发送新消息广播事件
*
* @author ChatRoom Laravel
*
* @version 1.0.0
*/
namespace App\Events;
2026-04-19 14:42:52 +08:00
use App\Models\User;
use Illuminate\Broadcasting\InteractsWithSockets;
use Illuminate\Broadcasting\PresenceChannel;
2026-04-19 14:42:52 +08:00
use Illuminate\Broadcasting\PrivateChannel;
use Illuminate\Contracts\Broadcasting\ShouldBroadcastNow;
use Illuminate\Foundation\Events\Dispatchable;
use Illuminate\Queue\SerializesModels;
2026-04-19 14:42:52 +08:00
/**
* 类功能:根据消息可见范围选择广播频道。
*/
class MessageSent implements ShouldBroadcastNow
{
use Dispatchable, InteractsWithSockets, SerializesModels;
/**
2026-04-27 14:43:43 +08:00
* 创建消息广播事件实例。
*
2026-04-27 14:43:43 +08:00
* @param int $roomId 房间 ID
* @param array $message 发送的消息数据
*/
public function __construct(
public readonly int $roomId,
public readonly array $message,
) {}
/**
2026-04-19 14:42:52 +08:00
* 获取消息应广播到的频道。
*
2026-04-27 14:43:43 +08:00
* 公共消息和普通定向发言走房间 Presence 频道;
* 悄悄话只发给发送方与接收方的私有用户频道。
*
* @return array<int, \Illuminate\Broadcasting\Channel>
*/
public function broadcastOn(): array
{
2026-04-19 14:42:52 +08:00
if ($this->shouldBroadcastPrivately()) {
$privateChannels = [];
foreach ($this->resolveVisibleUserIds() as $userId) {
$privateChannels[] = new PrivateChannel('user.'.$userId);
}
return $privateChannels;
}
return [
new PresenceChannel('room.'.$this->roomId),
];
}
/**
* 获取广播时的数据
*
* @return array<string, mixed>
*/
public function broadcastWith(): array
{
return [
'message' => $this->message,
];
}
2026-04-19 14:42:52 +08:00
/**
* 判断当前消息是否应仅广播给特定用户。
*/
private function shouldBroadcastPrivately(): bool
{
2026-04-27 14:43:43 +08:00
return (bool) ($this->message['is_secret'] ?? false);
2026-04-19 14:42:52 +08:00
}
/**
* 解析本条消息真正可见的用户 ID 列表。
*
* @return array<int, int>
*/
private function resolveVisibleUserIds(): array
{
$userIds = [];
$fromUser = trim((string) ($this->message['from_user'] ?? ''));
if ($fromUser !== '') {
$senderId = User::query()->where('username', $fromUser)->value('id');
if ($senderId !== null) {
$userIds[] = (int) $senderId;
}
}
$toUser = trim((string) ($this->message['to_user'] ?? ''));
if ($toUser !== '' && $toUser !== '大家') {
$receiverId = User::query()->where('username', $toUser)->value('id');
if ($receiverId !== null) {
$userIds[] = (int) $receiverId;
}
}
return array_values(array_unique($userIds));
}
}