Completed
Pull Request — master (#140)
by
unknown
01:36
created

FetchChannelsController::collectUserCounts()   A

Complexity

Conditions 3
Paths 2

Size

Total Lines 13

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 13
rs 9.8333
c 0
b 0
f 0
cc 3
nc 2
nop 3
1
<?php
2
3
namespace BeyondCode\LaravelWebSockets\HttpApi\Controllers;
4
5
use Illuminate\Support\Str;
6
use Illuminate\Http\Request;
7
use Illuminate\Support\Collection;
8
use React\Promise\PromiseInterface;
9
use BeyondCode\LaravelWebSockets\PubSub\ReplicationInterface;
10
use BeyondCode\LaravelWebSockets\WebSockets\Channels\PresenceChannel;
11
use Symfony\Component\HttpKernel\Exception\HttpException;
12
13
class FetchChannelsController extends Controller
14
{
15
    public function __invoke(Request $request)
16
    {
17
        $attributes = [];
18
19
        if ($request->has('info')) {
20
            $attributes = explode(',', trim($request->info));
21
22
            if (in_array('user_count', $attributes) && ! Str::startsWith($request->filter_by_prefix, 'presence-')) {
23
                throw new HttpException(400, 'Request must be limited to presence channels in order to fetch user_count');
24
            }
25
        }
26
27
        $channels = Collection::make($this->channelManager->getChannels($request->appId));
28
29
        if ($request->has('filter_by_prefix')) {
30
            $channels = $channels->filter(function ($channel, $channelName) use ($request) {
31
                return Str::startsWith($channelName, $request->filter_by_prefix);
32
            });
33
        }
34
35
        if (config('websockets.replication.enabled') === true) {
36
            // We want to get the channel user count all in one shot when
37
            // using a replication backend rather than doing individual queries.
38
            // To do so, we first collect the list of channel names.
39
            $channelNames = $channels->map(function (PresenceChannel $channel) use ($request) {
40
                return $channel->getChannelName();
41
            })->toArray();
42
43
            /** @var PromiseInterface $memberCounts */
44
            // We ask the replication backend to get us the member count per channel
45
            $memberCounts = app(ReplicationInterface::class)
46
                ->channelMemberCounts($request->appId, $channelNames);
47
48
            // We return a promise since the backend runs async. We get $counts back
49
            // as a key-value array of channel names and their member count.
50
            return $memberCounts->then(function (array $counts) use ($channels, $attributes) {
51
                return $this->collectUserCounts($channels, $attributes, function (PresenceChannel $channel) use ($counts) {
52
                    return $counts[$channel->getChannelName()];
53
                });
54
            });
55
        }
56
57
        return $this->collectUserCounts($channels, $attributes, function (PresenceChannel $channel) {
58
            return $channel->getUserCount();
59
        });
60
    }
61
62
    protected function collectUserCounts(Collection $channels, array $attributes, callable $transformer)
63
    {
64
        return [
65
            'channels' => $channels->map(function (PresenceChannel $channel) use ($transformer, $attributes) {
66
                $info = new \stdClass;
67
                if (in_array('user_count', $attributes)) {
68
                    $info->user_count = $transformer($channel);
69
                }
70
71
                return $info;
72
            })->toArray() ?: new \stdClass,
73
        ];
74
    }
75
}
76