Completed
Pull Request — master (#284)
by
unknown
01:25
created

StartWebSocketServer   A

Complexity

Total Complexity 17

Size/Duplication

Total Lines 153
Duplicated Lines 19.61 %

Coupling/Cohesion

Components 1
Dependencies 16

Importance

Changes 0
Metric Value
wmc 17
lcom 1
cbo 16
dl 30
loc 153
rs 10
c 0
b 0
f 0

12 Methods

Rating   Name   Duplication   Size   Complexity  
A getDnsResolver() 0 15 3
A __construct() 0 6 1
A handle() 0 12 1
A configureStatisticsLogger() 0 22 1
A configureHttpLogger() 10 10 2
A configureMessageLogger() 10 10 2
A configureConnectionLogger() 10 10 1
A configureRestartTimer() 0 12 2
A registerEchoRoutes() 0 6 1
A registerCustomRoutes() 0 6 1
A startWebSocketServer() 0 16 1
A getLastRestart() 0 4 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;
4
5
use BeyondCode\LaravelWebSockets\Facades\StatisticsLogger;
6
use BeyondCode\LaravelWebSockets\Facades\WebSocketsRouter;
7
use BeyondCode\LaravelWebSockets\Server\Logger\ConnectionLogger;
8
use BeyondCode\LaravelWebSockets\Server\Logger\HttpLogger;
9
use BeyondCode\LaravelWebSockets\Server\Logger\WebsocketsLogger;
10
use BeyondCode\LaravelWebSockets\Server\WebSocketServerFactory;
11
use BeyondCode\LaravelWebSockets\Statistics\DnsResolver;
12
use BeyondCode\LaravelWebSockets\Statistics\Logger\HttpStatisticsLogger;
13
use BeyondCode\LaravelWebSockets\Statistics\Logger\StatisticsLogger as StatisticsLoggerInterface;
14
use BeyondCode\LaravelWebSockets\WebSockets\Channels\ChannelManager;
15
use Clue\React\Buzz\Browser;
16
use Illuminate\Console\Command;
17
use Illuminate\Support\Facades\Cache;
18
use React\Dns\Config\Config as DnsConfig;
19
use React\Dns\Resolver\Factory as DnsFactory;
20
use React\Dns\Resolver\ResolverInterface;
21
use React\EventLoop\Factory as LoopFactory;
22
use React\Socket\Connector;
23
24
class StartWebSocketServer extends Command
25
{
26
    protected $signature = 'websockets:serve {--host=0.0.0.0} {--port=6001} {--debug : Forces the loggers to be enabled and thereby overriding the app.debug config setting } ';
27
28
    protected $description = 'Start the Laravel WebSocket Server';
29
30
    /** @var \React\EventLoop\LoopInterface */
31
    protected $loop;
32
33
    /** @var int */
34
    protected $lastRestart;
35
36
    public function __construct()
37
    {
38
        parent::__construct();
39
40
        $this->loop = LoopFactory::create();
41
    }
42
43
    public function handle()
44
    {
45
        $this
46
            ->configureStatisticsLogger()
47
            ->configureHttpLogger()
48
            ->configureMessageLogger()
49
            ->configureConnectionLogger()
50
            ->configureRestartTimer()
51
            ->registerEchoRoutes()
52
            ->registerCustomRoutes()
53
            ->startWebSocketServer();
54
    }
55
56
    protected function configureStatisticsLogger()
57
    {
58
        $connector = new Connector($this->loop, [
59
            'dns' => $this->getDnsResolver(),
60
            'tls' => [
61
                'verify_peer' => config('app.env') === 'production',
62
                'verify_peer_name' => config('app.env') === 'production',
63
            ],
64
        ]);
65
66
        $browser = new Browser($this->loop, $connector);
67
68
        app()->singleton(StatisticsLoggerInterface::class, function () use ($browser) {
69
            return new HttpStatisticsLogger(app(ChannelManager::class), $browser);
70
        });
71
72
        $this->loop->addPeriodicTimer(config('websockets.statistics.interval_in_seconds'), function () {
73
            StatisticsLogger::save();
74
        });
75
76
        return $this;
77
    }
78
79 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...
80
    {
81
        app()->singleton(HttpLogger::class, function () {
82
            return (new HttpLogger($this->output))
83
                ->enable($this->option('debug') ?: config('app.debug'))
84
                ->verbose($this->output->isVerbose());
85
        });
86
87
        return $this;
88
    }
89
90 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...
91
    {
92
        app()->singleton(WebsocketsLogger::class, function () {
93
            return (new WebsocketsLogger($this->output))
94
                ->enable($this->option('debug') ?: config('app.debug'))
95
                ->verbose($this->output->isVerbose());
96
        });
97
98
        return $this;
99
    }
100
101 View Code Duplication
    protected function configureConnectionLogger()
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...
102
    {
103
        app()->bind(ConnectionLogger::class, function () {
104
            return (new ConnectionLogger($this->output))
105
                ->enable(config('app.debug'))
106
                ->verbose($this->output->isVerbose());
107
        });
108
109
        return $this;
110
    }
111
112
    public function configureRestartTimer()
113
    {
114
        $this->lastRestart = $this->getLastRestart();
115
116
        $this->loop->addPeriodicTimer(10, function () {
117
            if ($this->getLastRestart() !== $this->lastRestart) {
118
                $this->loop->stop();
119
            }
120
        });
121
122
        return $this;
123
    }
124
125
    protected function registerEchoRoutes()
126
    {
127
        WebSocketsRouter::echo();
128
129
        return $this;
130
    }
131
132
    protected function registerCustomRoutes()
133
    {
134
        WebSocketsRouter::customRoutes();
135
136
        return $this;
137
    }
138
139
    protected function startWebSocketServer()
140
    {
141
        $this->info("Starting the WebSocket server on port {$this->option('port')}...");
142
143
        $routes = WebSocketsRouter::getRoutes();
144
145
        /* 🛰 Start the server 🛰  */
146
        (new WebSocketServerFactory())
147
            ->setLoop($this->loop)
148
            ->useRoutes($routes)
149
            ->setHost($this->option('host'))
150
            ->setPort($this->option('port'))
151
            ->setConsoleOutput($this->output)
152
            ->createServer()
153
            ->run();
154
    }
155
156
    protected function getDnsResolver(): ResolverInterface
157
    {
158
        if (! config('websockets.statistics.perform_dns_lookup')) {
159
            return new DnsResolver;
160
        }
161
162
        $dnsConfig = DnsConfig::loadSystemConfigBlocking();
163
164
        return (new DnsFactory)->createCached(
165
            $dnsConfig->nameservers
166
                ? reset($dnsConfig->nameservers)
167
                : '1.1.1.1',
168
            $this->loop
169
        );
170
    }
171
172
    protected function getLastRestart()
173
    {
174
        return Cache::get('beyondcode:websockets:restart', 0);
175
    }
176
}
177