Completed
Pull Request — master (#127)
by
unknown
04:53 queued 12s
created

FetchChannelsController::__invoke()   B

Complexity

Conditions 7
Paths 10

Size

Total Lines 30

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 30
rs 8.5066
c 0
b 0
f 0
cc 7
nc 10
nop 1
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 Symfony\Component\HttpKernel\Exception\HttpException;
9
use BeyondCode\LaravelWebSockets\WebSockets\Channels\PresenceChannel;
10
11
class FetchChannelsController extends Controller
12
{
13
    public function __invoke(Request $request)
14
    {
15
        $channels = Collection::make($this->channelManager->getChannels($request->appId));
16
17
        if ($request->has('filter_by_prefix')) {
18
            $channels = $channels->filter(function ($channel, $channelName) use ($request) {
19
                return Str::startsWith($channelName, $request->filter_by_prefix);
20
            });
21
        }
22
23
        $attributes = [];
24
25
        if ($request->has('info')) {
26
            $attributes = explode(',', trim($request->info));
27
28
            if (in_array('user_count', $attributes) && !Str::startsWith($request->filter_by_prefix, 'presence-')) {
29
                throw new HttpException(400, 'Request must be limited to presence channels in order to fetch user_count');
30
            }
31
        }
32
33
        return [
34
            'channels' => $channels->map(function ($channel) use ($attributes) {
35
                $info = new \stdClass;
36
                if (in_array('user_count', $attributes)) {
37
                    $info->user_count = count($channel->getUsers());
38
                }
39
                return $info;
40
            })->toArray() ?: new \stdClass,
41
        ];
42
    }
43
}
44