Completed
Push — master ( 5e84ef...556f43 )
by Marcel
01:27
created

StartWebSocketServer::registerCustomRoutes()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 6

Duplication

Lines 0
Ratio 0 %

Importance

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