Completed
Pull Request — master (#447)
by Marcel
03:00 queued 01:29
created

TriggerEvent::__invoke()   B

Complexity

Conditions 5
Paths 12

Size

Total Lines 46

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 46
rs 8.867
c 0
b 0
f 0
cc 5
nc 12
nop 1
1
<?php
2
3
namespace BeyondCode\LaravelWebSockets\API;
4
5
use BeyondCode\LaravelWebSockets\DashboardLogger;
6
use BeyondCode\LaravelWebSockets\Facades\StatisticsCollector;
7
use Illuminate\Http\Request;
8
9
class TriggerEvent extends Controller
10
{
11
    /**
12
     * Handle the incoming request.
13
     *
14
     * @param  \Illuminate\Http\Request  $request
15
     * @return \Illuminate\Http\Response
16
     */
17
    public function __invoke(Request $request)
18
    {
19
        $channels = $request->channels ?: [];
20
21
        if (is_string($channels)) {
22
            $channels = [$channels];
23
        }
24
25
        foreach ($channels as $channelName) {
26
            // Here you can use the ->find(), even if the channel
27
            // does not exist on the server. If it does not exist,
28
            // then the message simply will get broadcasted
29
            // across the other servers.
30
            $channel = $this->channelManager->find(
31
                $request->appId, $channelName
32
            );
33
34
            $payload = [
35
                'event' => $request->name,
36
                'channel' => $channelName,
37
                'data' => $request->data,
38
            ];
39
40
            if ($channel) {
41
                $channel->broadcastToEveryoneExcept(
42
                    (object) $payload,
43
                    $request->socket_id,
44
                    $request->appId
45
                );
46
            } else {
47
                $this->channelManager->broadcastAcrossServers(
48
                    $request->appId, $request->socket_id, $channelName, (object) $payload
49
                );
50
            }
51
52
            StatisticsCollector::apiMessage($request->appId);
53
54
            DashboardLogger::log($request->appId, DashboardLogger::TYPE_API_MESSAGE, [
55
                'event' => $request->name,
56
                'channel' => $channelName,
57
                'payload' => $request->data,
58
            ]);
59
        }
60
61
        return $request->json()->all();
62
    }
63
}
64