Completed
Pull Request — master (#61)
by
unknown
10:24
created

StartWebSocketServer::configurePubSubReplication()   A

Complexity

Conditions 3
Paths 3

Size

Total Lines 16

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 16
c 0
b 0
f 0
rs 9.7333
cc 3
nc 3
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\PubSub\PubSubInterface;
14
use BeyondCode\LaravelWebSockets\PubSub\Redis\RedisClient;
15
use BeyondCode\LaravelWebSockets\Facades\StatisticsLogger;
16
use BeyondCode\LaravelWebSockets\Facades\WebSocketsRouter;
17
use BeyondCode\LaravelWebSockets\Server\Logger\HttpLogger;
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
        app()->singleton(StatisticsLoggerInterface::class, function () use ($browser) {
66
            return new HttpStatisticsLogger(app(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
    protected function configureHttpLogger()
77
    {
78
        app()->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
        app()->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
        app()->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
134
    protected function configurePubSubReplication()
135
    {
136
        if (config('websockets.replication.enabled') !== true) {
137
            return $this;
138
        }
139
140
        if (config('websockets.replication.driver') === 'redis') {
141
            $connection = (new RedisClient())->subscribe($this->loop);
142
        }
143
144
        app()->singleton(PubSubInterface::class, function () use ($connection) {
0 ignored issues
show
Bug introduced by
The variable $connection does not seem to be defined for all execution paths leading up to this point.

If you define a variable conditionally, it can happen that it is not defined for all execution paths.

Let’s take a look at an example:

function myFunction($a) {
    switch ($a) {
        case 'foo':
            $x = 1;
            break;

        case 'bar':
            $x = 2;
            break;
    }

    // $x is potentially undefined here.
    echo $x;
}

In the above example, the variable $x is defined if you pass “foo” or “bar” as argument for $a. However, since the switch statement has no default case statement, if you pass any other value, the variable $x would be undefined.

Available Fixes

  1. Check for existence of the variable explicitly:

    function myFunction($a) {
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
        }
    
        if (isset($x)) { // Make sure it's always set.
            echo $x;
        }
    }
    
  2. Define a default value for the variable:

    function myFunction($a) {
        $x = ''; // Set a default which gets overridden for certain paths.
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
        }
    
        echo $x;
    }
    
  3. Add a value for the missing path:

    function myFunction($a) {
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
    
            // We add support for the missing case.
            default:
                $x = '';
                break;
        }
    
        echo $x;
    }
    
Loading history...
145
            return $connection;
146
        });
147
148
        return $this;
149
    }
150
151
152
    protected function getDnsResolver(): ReactDnsResolver
153
    {
154
        if (! config('websockets.statistics.perform_dns_lookup')) {
155
            return new DnsResolver;
156
        }
157
158
        $dnsConfig = DnsConfig::loadSystemConfigBlocking();
159
160
        return (new DnsFactory)->createCached(
161
            $dnsConfig->nameservers
162
                ? reset($dnsConfig->nameservers)
163
                : '1.1.1.1',
164
            $this->loop
165
        );
166
    }
167
}
168