1<?php
2
3// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the GNU Affero General Public License v3.0.
4// See the LICENCE file in the repository root for full licence text.
5
6namespace App\Events;
7
8use App\Models\Chat\Message;
9use App\Transformers\Chat\MessageTransformer;
10use App\Transformers\UserCompactTransformer;
11use Illuminate\Broadcasting\Channel;
12use Illuminate\Contracts\Broadcasting\ShouldBroadcastNow;
13
14class ChatMessageEvent extends BroadcastableEventBase implements ShouldBroadcastNow
15{
16 public function __construct(public Message $message)
17 {
18 }
19
20 public function broadcastAs()
21 {
22 return 'chat.message.new';
23 }
24
25 /**
26 * Get the channels the event should broadcast on.
27 *
28 * @return Channel|array
29 */
30 public function broadcastOn()
31 {
32 return array_map(
33 fn ($userId) => new Channel("private:user:{$userId}"),
34 $this->message->channel->activeUserIds()
35 );
36 }
37
38 public function broadcastWith()
39 {
40 return [
41 'messages' => json_collection([$this->message], new MessageTransformer()),
42 'users' => json_collection([$this->message->sender], new UserCompactTransformer()),
43 ];
44 }
45}