laravel-websockets/src/HttpApi/Controllers/FetchChannelsController.php

76 lines
3.1 KiB
PHP
Raw Normal View History

2018-11-22 21:20:23 +00:00
<?php
2018-11-27 15:42:19 +00:00
namespace BeyondCode\LaravelWebSockets\HttpApi\Controllers;
2018-11-22 21:20:23 +00:00
use Illuminate\Support\Str;
2018-11-22 21:20:23 +00:00
use Illuminate\Http\Request;
use Illuminate\Support\Collection;
use React\Promise\PromiseInterface;
use BeyondCode\LaravelWebSockets\PubSub\ReplicationInterface;
use BeyondCode\LaravelWebSockets\WebSockets\Channels\PresenceChannel;
use Symfony\Component\HttpKernel\Exception\HttpException;
2018-11-22 21:20:23 +00:00
2018-11-27 20:15:29 +00:00
class FetchChannelsController extends Controller
2018-11-22 21:20:23 +00:00
{
public function __invoke(Request $request)
{
$attributes = [];
if ($request->has('info')) {
$attributes = explode(',', trim($request->info));
if (in_array('user_count', $attributes) && ! Str::startsWith($request->filter_by_prefix, 'presence-')) {
throw new HttpException(400, 'Request must be limited to presence channels in order to fetch user_count');
}
}
$channels = Collection::make($this->channelManager->getChannels($request->appId));
2018-11-22 21:20:23 +00:00
if ($request->has('filter_by_prefix')) {
$channels = $channels->filter(function ($channel, $channelName) use ($request) {
return Str::startsWith($channelName, $request->filter_by_prefix);
2018-11-22 21:20:23 +00:00
});
}
if (config('websockets.replication.enabled') === true) {
// We want to get the channel user count all in one shot when
// using a replication backend rather than doing individual queries.
// To do so, we first collect the list of channel names.
$channelNames = $channels->map(function (PresenceChannel $channel) use ($request) {
return $channel->getChannelName();
})->toArray();
/** @var PromiseInterface $memberCounts */
// We ask the replication backend to get us the member count per channel
$memberCounts = app(ReplicationInterface::class)
->channelMemberCounts($request->appId, $channelNames);
// We return a promise since the backend runs async. We get $counts back
// as a key-value array of channel names and their member count.
return $memberCounts->then(function (array $counts) use ($channels) {
return $this->collectUserCounts($channels, $attributes, function (PresenceChannel $channel) use ($counts) {
return $counts[$channel->getChannelName()];
});
});
}
return $this->collectUserCounts($channels, $attributes, function (PresenceChannel $channel) {
return $channel->getUserCount();
});
}
protected function collectUserCounts(Collection $channels, array $attributes, callable $transformer)
{
2018-11-22 21:20:23 +00:00
return [
'channels' => $channels->map(function (PresenceChannel $channel) use ($transformer, $attributes) {
$info = new \stdClass;
if (in_array('user_count', $attributes)) {
$info->user_count = $transformer($channel);
}
return $info;
})->toArray() ?: new \stdClass,
2018-11-22 21:20:23 +00:00
];
}
2018-12-04 21:22:33 +00:00
}