Completed
Pull Request — master (#447)
by Alexandru
01:27
created

StartServer   A

Complexity

Total Complexity 19

Size/Duplication

Total Lines 251
Duplicated Lines 11.95 %

Coupling/Cohesion

Components 1
Dependencies 11

Importance

Changes 0
Metric Value
wmc 19
lcom 1
cbo 11
dl 30
loc 251
rs 10
c 0
b 0
f 0

13 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 6 1
A handle() 0 14 1
A configureLoggers() 0 6 1
A configureManagers() 7 10 1
A configureStatistics() 7 26 3
A configureRestartTimer() 0 10 2
A configureRoutes() 0 4 1
A configureHttpLogger() 8 8 2
A configureMessageLogger() 8 8 2
A configureConnectionLogger() 0 8 1
A startServer() 0 16 2
A buildServer() 0 12 1
A getLastRestart() 0 6 1

How to fix   Duplicated Code   

Duplicated Code

Duplicate code is one of the most pungent code smells. A rule that is often used is to re-structure code once it is duplicated in three or more places.

Common duplication problems, and corresponding solutions are:

1
<?php
2
3
namespace BeyondCode\LaravelWebSockets\Console\Commands;
4
5
use BeyondCode\LaravelWebSockets\Contracts\ChannelManager;
6
use BeyondCode\LaravelWebSockets\Contracts\StatisticsCollector;
7
use BeyondCode\LaravelWebSockets\Facades\StatisticsCollector as StatisticsCollectorFacade;
8
use BeyondCode\LaravelWebSockets\Facades\WebSocketRouter;
9
use BeyondCode\LaravelWebSockets\Server\Loggers\ConnectionLogger;
10
use BeyondCode\LaravelWebSockets\Server\Loggers\HttpLogger;
11
use BeyondCode\LaravelWebSockets\Server\Loggers\WebSocketsLogger;
12
use BeyondCode\LaravelWebSockets\ServerFactory;
13
use Illuminate\Console\Command;
14
use Illuminate\Support\Facades\Cache;
15
use React\EventLoop\Factory as LoopFactory;
16
17
class StartServer extends Command
18
{
19
    /**
20
     * The name and signature of the console command.
21
     *
22
     * @var string
23
     */
24
    protected $signature = 'websockets:serve
25
        {--host=0.0.0.0}
26
        {--port=6001}
27
        {--disable-statistics : Disable the statistics tracking.}
28
        {--statistics-interval= : The amount of seconds to tick between statistics saving.}
29
        {--debug : Forces the loggers to be enabled and thereby overriding the APP_DEBUG setting.}
30
        {--test : Prepare the server, but do not start it.}
31
    ';
32
33
    /**
34
     * The console command description.
35
     *
36
     * @var string|null
37
     */
38
    protected $description = 'Start the LaravelWebSockets server.';
39
40
    /**
41
     * Get the loop instance.
42
     *
43
     * @var \React\EventLoop\LoopInterface
44
     */
45
    protected $loop;
46
47
    /**
48
     * The Pusher server instance.
49
     *
50
     * @var \Ratchet\Server\IoServer
51
     */
52
    public $server;
53
54
    /**
55
     * Initialize the command.
56
     *
57
     * @return void
0 ignored issues
show
Comprehensibility Best Practice introduced by
Adding a @return annotation to constructors is generally not recommended as a constructor does not have a meaningful return value.

Adding a @return annotation to a constructor is not recommended, since a constructor does not have a meaningful return value.

Please refer to the PHP core documentation on constructors.

Loading history...
58
     */
59
    public function __construct()
60
    {
61
        parent::__construct();
62
63
        $this->loop = LoopFactory::create();
64
    }
65
66
    /**
67
     * Run the command.
68
     *
69
     * @return void
70
     */
71
    public function handle()
72
    {
73
        $this->configureLoggers();
74
75
        $this->configureManagers();
76
77
        $this->configureStatistics();
78
79
        $this->configureRestartTimer();
80
81
        $this->configureRoutes();
82
83
        $this->startServer();
84
    }
85
86
    /**
87
     * Configure the loggers used for the console.
88
     *
89
     * @return void
90
     */
91
    protected function configureLoggers()
92
    {
93
        $this->configureHttpLogger();
94
        $this->configureMessageLogger();
95
        $this->configureConnectionLogger();
96
    }
97
98
    /**
99
     * Register the managers that are not resolved
100
     * in the package service provider.
101
     *
102
     * @return void
103
     */
104
    protected function configureManagers()
105
    {
106 View Code Duplication
        $this->laravel->singleton(ChannelManager::class, function () {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
107
            $mode = config('websockets.replication.mode', 'local');
108
109
            $class = config("websockets.replication.modes.{$mode}.channel_manager");
110
111
            return new $class($this->loop);
112
        });
113
    }
114
115
    /**
116
     * Register the Statistics Collectors that
117
     * are not resolved in the package service provider.
118
     *
119
     * @return void
120
     */
121
    protected function configureStatistics()
122
    {
123 View Code Duplication
        $this->laravel->singleton(StatisticsCollector::class, function () {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
124
            $replicationMode = config('websockets.replication.mode', 'local');
125
126
            $class = config("websockets.replication.modes.{$replicationMode}.collector");
127
128
            return new $class;
129
        });
130
131
        $this->laravel->singleton(StatisticsStore::class, function () {
132
            $class = config('websockets.statistics.store');
133
134
            return new $class;
135
        });
136
137
        if (! $this->option('disable-statistics')) {
138
            $intervalInSeconds = $this->option('statistics-interval') ?: config('websockets.statistics.interval_in_seconds', 3600);
139
140
            $this->loop->addPeriodicTimer($intervalInSeconds, function () {
141
                $this->line('Saving statistics...');
142
143
                StatisticsCollectorFacade::save();
144
            });
145
        }
146
    }
147
148
    /**
149
     * Configure the restart timer.
150
     *
151
     * @return void
152
     */
153
    public function configureRestartTimer()
154
    {
155
        $this->lastRestart = $this->getLastRestart();
0 ignored issues
show
Bug introduced by
The property lastRestart 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...
156
157
        $this->loop->addPeriodicTimer(10, function () {
158
            if ($this->getLastRestart() !== $this->lastRestart) {
159
                $this->loop->stop();
160
            }
161
        });
162
    }
163
164
    /**
165
     * Register the routes for the server.
166
     *
167
     * @return void
168
     */
169
    protected function configureRoutes()
170
    {
171
        WebSocketRouter::routes();
172
    }
173
174
    /**
175
     * Configure the HTTP logger class.
176
     *
177
     * @return void
178
     */
179 View Code Duplication
    protected function configureHttpLogger()
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
180
    {
181
        $this->laravel->singleton(HttpLogger::class, function () {
182
            return (new HttpLogger($this->output))
183
                ->enable($this->option('debug') ?: config('app.debug'))
184
                ->verbose($this->output->isVerbose());
185
        });
186
    }
187
188
    /**
189
     * Configure the logger for messages.
190
     *
191
     * @return void
192
     */
193 View Code Duplication
    protected function configureMessageLogger()
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
194
    {
195
        $this->laravel->singleton(WebSocketsLogger::class, function () {
196
            return (new WebSocketsLogger($this->output))
197
                ->enable($this->option('debug') ?: config('app.debug'))
198
                ->verbose($this->output->isVerbose());
199
        });
200
    }
201
202
    /**
203
     * Configure the connection logger.
204
     *
205
     * @return void
206
     */
207
    protected function configureConnectionLogger()
208
    {
209
        $this->laravel->bind(ConnectionLogger::class, function () {
210
            return (new ConnectionLogger($this->output))
211
                ->enable(config('app.debug'))
212
                ->verbose($this->output->isVerbose());
213
        });
214
    }
215
216
    /**
217
     * Start the server.
218
     *
219
     * @return void
220
     */
221
    protected function startServer()
222
    {
223
        $this->info("Starting the WebSocket server on port {$this->option('port')}...");
224
225
        $this->buildServer();
226
227
        // For testing, just boot up the server, run it
228
        // but exit after the next tick.
229
        if ($this->option('test')) {
230
            $this->loop->futureTick(function () {
231
                $this->loop->stop();
232
            });
233
        }
234
235
        $this->server->run();
236
    }
237
238
    /**
239
     * Build the server instance.
240
     *
241
     * @return void
242
     */
243
    protected function buildServer()
244
    {
245
        $this->server = new ServerFactory(
0 ignored issues
show
Documentation Bug introduced by
It seems like new \BeyondCode\LaravelW... $this->option('port')) of type object<BeyondCode\Larave...bSockets\ServerFactory> is incompatible with the declared type object<Ratchet\Server\IoServer> of property $server.

Our type inference engine has found an assignment to a property that is incompatible with the declared type of that property.

Either this assignment is in error or the assigned type should be added to the documentation/type hint for that property..

Loading history...
246
            $this->option('host'), $this->option('port')
247
        );
248
249
        $this->server = $this->server
250
            ->setLoop($this->loop)
251
            ->withRoutes(WebSocketRouter::getRoutes())
252
            ->setConsoleOutput($this->output)
253
            ->createServer();
254
    }
255
256
    /**
257
     * Get the last time the server restarted.
258
     *
259
     * @return int
260
     */
261
    protected function getLastRestart()
262
    {
263
        return Cache::get(
264
            'beyondcode:websockets:restart', 0
265
        );
266
    }
267
}
268