Completed
Pull Request — master (#31)
by Alex
01:49
created

StartWebSocketServer::getDnsResolver()   A

Complexity

Conditions 3
Paths 2

Size

Total Lines 15

Duplication

Lines 0
Ratio 0 %

Importance

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