Completed
Pull Request — master (#140)
by Alexandru
01:30
created

WebSocketsServiceProvider   A

Complexity

Total Complexity 11

Size/Duplication

Total Lines 106
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 12

Importance

Changes 0
Metric Value
wmc 11
lcom 1
cbo 12
dl 0
loc 106
rs 10
c 0
b 0
f 0

5 Methods

Rating   Name   Duplication   Size   Complexity  
A boot() 0 25 2
A configurePubSub() 0 32 4
A register() 0 17 3
A registerRoutes() 0 17 1
A registerDashboardGate() 0 8 1
1
<?php
2
3
namespace BeyondCode\LaravelWebSockets;
4
5
use BeyondCode\LaravelWebSockets\Apps\AppProvider;
6
use BeyondCode\LaravelWebSockets\Dashboard\Http\Controllers\AuthenticateDashboard;
7
use BeyondCode\LaravelWebSockets\Dashboard\Http\Controllers\DashboardApiController;
8
use BeyondCode\LaravelWebSockets\Dashboard\Http\Controllers\SendMessage;
9
use BeyondCode\LaravelWebSockets\Dashboard\Http\Controllers\ShowDashboard;
10
use BeyondCode\LaravelWebSockets\Dashboard\Http\Middleware\Authorize as AuthorizeDashboard;
11
use BeyondCode\LaravelWebSockets\PubSub\Broadcasters\RedisPusherBroadcaster;
12
use BeyondCode\LaravelWebSockets\PubSub\Drivers\LocalClient;
13
use BeyondCode\LaravelWebSockets\PubSub\Drivers\RedisClient;
14
use BeyondCode\LaravelWebSockets\PubSub\ReplicationInterface;
15
use BeyondCode\LaravelWebSockets\Server\Router;
16
use BeyondCode\LaravelWebSockets\Statistics\Http\Controllers\WebSocketStatisticsEntriesController;
17
use BeyondCode\LaravelWebSockets\Statistics\Http\Middleware\Authorize as AuthorizeStatistics;
18
use BeyondCode\LaravelWebSockets\WebSockets\Channels\ChannelManager;
19
use BeyondCode\LaravelWebSockets\WebSockets\Channels\ChannelManagers\ArrayChannelManager;
20
use Pusher\Pusher;
21
use Psr\Log\LoggerInterface;
22
use Illuminate\Broadcasting\BroadcastManager;
23
use Illuminate\Support\Facades\Gate;
24
use Illuminate\Support\Facades\Route;
25
use Illuminate\Support\ServiceProvider;
26
use Illuminate\Support\Facades\Schema;
27
28
class WebSocketsServiceProvider extends ServiceProvider
29
{
30
    public function boot()
31
    {
32
        $this->publishes([
33
            __DIR__.'/../config/websockets.php' => base_path('config/websockets.php'),
34
        ], 'config');
35
36
        if (! Schema::hasTable('websockets_statistics_entries')) {
37
            $this->publishes([
38
                __DIR__.'/../database/migrations/create_websockets_statistics_entries_table.php.stub' => database_path('migrations/'.date('Y_m_d_His', time()).'_create_websockets_statistics_entries_table.php'),
39
            ], 'migrations');
40
        }
41
42
        $this
43
            ->registerRoutes()
44
            ->registerDashboardGate();
45
46
        $this->loadViewsFrom(__DIR__.'/../resources/views/', 'websockets');
47
48
        $this->commands([
49
            Console\StartWebSocketServer::class,
50
            Console\CleanStatistics::class,
51
        ]);
52
53
        $this->configurePubSub();
54
    }
55
56
    protected function configurePubSub()
57
    {
58
        if (config('websockets.replication.enabled') !== true || config('websockets.replication.driver') !== 'redis') {
59
            $this->app->singleton(ReplicationInterface::class, function () {
60
                return new LocalClient();
61
            });
62
63
            return;
64
        }
65
66
        $this->app->singleton(ReplicationInterface::class, function () {
67
            return (new RedisClient())->boot($this->loop);
0 ignored issues
show
Bug introduced by
The property loop does not exist. Did you maybe forget to declare it?

In PHP it is possible to write to properties without declaring them. For example, the following is perfectly valid PHP code:

class MyClass { }

$x = new MyClass();
$x->foo = true;

Generally, it is a good practice to explictly declare properties to avoid accidental typos and provide IDE auto-completion:

class MyClass {
    public $foo;
}

$x = new MyClass();
$x->foo = true;
Loading history...
68
        });
69
70
        $this->app->get(BroadcastManager::class)->extend('redis-pusher', function ($app, array $config) {
71
            $pusher = new Pusher(
72
                $config['key'], $config['secret'],
73
                $config['app_id'], $config['options'] ?? []
74
            );
75
76
            if ($config['log'] ?? false) {
77
                $pusher->setLogger($this->app->make(LoggerInterface::class));
78
            }
79
80
            return new RedisPusherBroadcaster(
81
                $pusher,
82
                $config['app_id'],
83
                $this->app->make('redis'),
84
                $config['connection'] ?? null
85
            );
86
        });
87
    }
88
89
    public function register()
90
    {
91
        $this->mergeConfigFrom(__DIR__.'/../config/websockets.php', 'websockets');
92
93
        $this->app->singleton('websockets.router', function () {
94
            return new Router();
95
        });
96
97
        $this->app->singleton(ChannelManager::class, function () {
98
            return config('websockets.channel_manager') !== null && class_exists(config('websockets.channel_manager'))
99
                ? $this->app->make(config('websockets.channel_manager')) : new ArrayChannelManager();
100
        });
101
102
        $this->app->singleton(AppProvider::class, function () {
103
            return $this->app->make(config('websockets.app_provider'));
104
        });
105
    }
106
107
    protected function registerRoutes()
108
    {
109
        Route::prefix(config('websockets.path'))->group(function () {
110
            Route::middleware(config('websockets.middleware', [AuthorizeDashboard::class]))->group(function () {
111
                Route::get('/', ShowDashboard::class);
112
                Route::get('/api/{appId}/statistics', [DashboardApiController::class, 'getStatistics']);
113
                Route::post('auth', AuthenticateDashboard::class);
114
                Route::post('event', SendMessage::class);
115
            });
116
117
            Route::middleware(AuthorizeStatistics::class)->group(function () {
118
                Route::post('statistics', [WebSocketStatisticsEntriesController::class, 'store']);
119
            });
120
        });
121
122
        return $this;
123
    }
124
125
    protected function registerDashboardGate()
126
    {
127
        Gate::define('viewWebSocketsDashboard', function ($user = null) {
0 ignored issues
show
Unused Code introduced by
The parameter $user is not used and could be removed.

This check looks from parameters that have been defined for a function or method, but which are not used in the method body.

Loading history...
128
            return $this->app->environment('local');
129
        });
130
131
        return $this;
132
    }
133
}
134