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

StartWebSocketServer   A

Complexity

Total Complexity 16

Size/Duplication

Total Lines 139
Duplicated Lines 21.58 %

Coupling/Cohesion

Components 1
Dependencies 17

Importance

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

10 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 6 1
A handle() 0 11 1
A configureStatisticsLogger() 0 22 1
A configureMessageLogger() 10 10 2
A configureConnectionLogger() 10 10 1
A registerEchoRoutes() 0 6 1
A startWebSocketServer() 0 16 1
A configureHttpLogger() 10 10 2
A configurePubSubReplication() 0 14 3
A getDnsResolver() 0 15 3

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