Completed
Push — master ( 03c983...d145cd )
by Marcel
01:30
created

FetchChannelsController::__invoke()   B

Complexity

Conditions 7
Paths 9

Size

Total Lines 31

Duplication

Lines 0
Ratio 0 %

Importance

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