2018-11-25 21:24:31 +00:00
|
|
|
<?php
|
|
|
|
|
|
2018-11-26 08:55:06 +00:00
|
|
|
namespace BeyondCode\LaravelWebSockets\Dashboard\Http\Controllers;
|
2018-11-25 21:24:31 +00:00
|
|
|
|
2020-09-10 19:59:26 +00:00
|
|
|
use BeyondCode\LaravelWebSockets\Contracts\ChannelManager;
|
|
|
|
|
use BeyondCode\LaravelWebSockets\Rules\AppId;
|
2020-03-04 09:58:39 +00:00
|
|
|
use Illuminate\Http\Request;
|
2018-11-25 21:24:31 +00:00
|
|
|
|
|
|
|
|
class SendMessage
|
|
|
|
|
{
|
2020-08-18 17:21:22 +00:00
|
|
|
/**
|
|
|
|
|
* Send the message to the requested channel.
|
|
|
|
|
*
|
|
|
|
|
* @param \Illuminate\Http\Request $request
|
2020-09-10 19:59:26 +00:00
|
|
|
* @param \BeyondCode\LaravelWebSockets\Contracts\ChannelManager $channelManager
|
2020-08-18 17:21:22 +00:00
|
|
|
* @return \Illuminate\Http\Response
|
|
|
|
|
*/
|
2020-09-10 19:59:26 +00:00
|
|
|
public function __invoke(Request $request, ChannelManager $channelManager)
|
2018-12-04 08:08:25 +00:00
|
|
|
{
|
2020-08-23 16:12:22 +00:00
|
|
|
$request->validate([
|
2020-08-18 17:21:22 +00:00
|
|
|
'appId' => ['required', new AppId],
|
|
|
|
|
'channel' => 'required|string',
|
|
|
|
|
'event' => 'required|string',
|
|
|
|
|
'data' => 'required|json',
|
2018-12-04 08:08:25 +00:00
|
|
|
]);
|
|
|
|
|
|
2020-09-10 19:59:26 +00:00
|
|
|
$payload = [
|
|
|
|
|
'channel' => $request->channel,
|
|
|
|
|
'event' => $request->event,
|
|
|
|
|
'data' => json_decode($request->data, true),
|
|
|
|
|
];
|
|
|
|
|
|
|
|
|
|
// Here you can use the ->find(), even if the channel
|
|
|
|
|
// does not exist on the server. If it does not exist,
|
|
|
|
|
// then the message simply will get broadcasted
|
|
|
|
|
// across the other servers.
|
|
|
|
|
$channel = $channelManager->find(
|
|
|
|
|
$request->appId, $request->channel
|
|
|
|
|
);
|
|
|
|
|
|
|
|
|
|
if ($channel) {
|
|
|
|
|
$channel->broadcastToEveryoneExcept(
|
|
|
|
|
(object) $payload,
|
|
|
|
|
null,
|
|
|
|
|
$request->appId
|
|
|
|
|
);
|
|
|
|
|
} else {
|
|
|
|
|
$channelManager->broadcastAcrossServers(
|
|
|
|
|
$request->appId, $request->channel, (object) $payload
|
2020-08-24 06:03:52 +00:00
|
|
|
);
|
|
|
|
|
}
|
2018-11-25 21:24:31 +00:00
|
|
|
|
2020-08-24 06:03:52 +00:00
|
|
|
return response()->json([
|
|
|
|
|
'ok' => true,
|
|
|
|
|
]);
|
2018-11-25 21:24:31 +00:00
|
|
|
}
|
2018-11-26 07:56:56 +00:00
|
|
|
}
|