Completed
Push — master ( 1d2ea6...1d4c49 )
by Valentin
03:23 queued 01:07
created

WebSocketServer::start()   B

Complexity

Conditions 4
Paths 3

Size

Total Lines 26
Code Lines 16

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 20

Importance

Changes 0
Metric Value
dl 0
loc 26
ccs 0
cts 17
cp 0
rs 8.5806
c 0
b 0
f 0
cc 4
eloc 16
nc 3
nop 0
crap 20
1
<?php
2
3
/**
4
 * This file is a part of Woketo package.
5
 *
6
 * (c) Nekland <[email protected]>
7
 *
8
 * For the full license, take a look to the LICENSE file
9
 * on the root directory of this project
10
 */
11
12
namespace Nekland\Woketo\Server;
13
14
use Nekland\Woketo\Exception\ConfigException;
15
use Nekland\Woketo\Exception\RuntimeException;
16
use Nekland\Woketo\Message\MessageHandlerInterface;
17
use Nekland\Woketo\Rfc6455\FrameFactory;
18
use Nekland\Woketo\Rfc6455\MessageFactory;
19
use Nekland\Woketo\Rfc6455\MessageHandler\CloseFrameHandler;
20
use Nekland\Woketo\Rfc6455\MessageHandler\RsvCheckFrameHandler;
21
use Nekland\Woketo\Rfc6455\MessageHandler\WrongOpcodeHandler;
22
use Nekland\Woketo\Rfc6455\MessageHandler\PingFrameHandler;
23
use Nekland\Woketo\Rfc6455\MessageProcessor;
24
use Nekland\Woketo\Rfc6455\ServerHandshake;
25
use Nekland\Woketo\Utils\SimpleLogger;
26
use Psr\Log\LoggerInterface;
27
use Psr\Log\LogLevel;
28
use React\EventLoop\LoopInterface;
29
use React\Socket\ConnectionInterface;
30
31
class WebSocketServer
32
{
33
    /**
34
     * @var int
35
     */
36
    private $port;
37
38
    /**
39
     * @var string
40
     */
41
    private $host;
42
43
    /**
44
     * @var ServerHandshake
45
     */
46
    private $handshake;
47
48
    /**
49
     * @var MessageHandlerInterface
50
     */
51
    private $messageHandler;
52
53
    /**
54
     * @var array
55
     */
56
    private $connections;
57
58
    /**
59
     * @var LoopInterface
60
     */
61
    private $loop;
62
63
    /**
64
     * @var MessageProcessor
65
     */
66
    private $messageProcessor;
67
68
    /**
69
     * @var array
70
     */
71
    private $config;
72
73
    /**
74
     * @var LoggerInterface
75
     */
76
    private $logger;
77
78
    /**
79
     * @param int    $port    The number of the port to bind
80
     * @param string $host    The host to listen on (by default 127.0.0.1)
81
     * @param array  $config
82
     */
83 4
    public function __construct($port, $host = '127.0.0.1', $config = [])
84
    {
85 4
        $this->setConfig($config);
86 3
        $this->host = $host;
87 3
        $this->port = $port;
88 3
        $this->handshake = new ServerHandshake();
89 3
        $this->connections = [];
90 3
        $this->buildMessageProcessor();
91
92
        // Some optimization
93 2
        \gc_enable();       // As the process never stops, the garbage collector will be usefull, you may need to call it manually sometimes for performance purpose
94 2
        \set_time_limit(0); // It's by default on most server for cli apps but better be sure of that fact
95 2
    }
96
97
    public function setMessageHandler($messageHandler)
98
    {
99
        if (!$messageHandler instanceof MessageHandlerInterface &&  !\is_string($messageHandler)) {
100
            throw new \InvalidArgumentException('The message handler must be an instance of MessageHandlerInterface or a string.');
101
        }
102
        if (\is_string($messageHandler)) {
103
            try {
104
                $reflection = new \ReflectionClass($messageHandler);
105
                if(!$reflection->implementsInterface('Nekland\Woketo\Message\MessageHandlerInterface')) {
106
                    throw new \InvalidArgumentException('The messageHandler must implement MessageHandlerInterface');
107
                }
108
            } catch (\ReflectionException $e) {
109
                throw new \InvalidArgumentException('The messageHandler must be a string representing a class.');
110
            }
111
        }
112
        $this->messageHandler = $messageHandler;
0 ignored issues
show
Documentation Bug introduced by
It seems like $messageHandler can also be of type string. However, the property $messageHandler is declared as type object<Nekland\Woketo\Me...essageHandlerInterface>. Maybe add an additional type check?

Our type inference engine has found a suspicous assignment of a value to a property. This check raises an issue when a value that can be of a mixed type is assigned to a property that is type hinted more strictly.

For example, imagine you have a variable $accountId that can either hold an Id object or false (if there is no account id yet). Your code now assigns that value to the id property of an instance of the Account class. This class holds a proper account, so the id value must no longer be false.

Either this assignment is in error or a type check should be added for that assignment.

class Id
{
    public $id;

    public function __construct($id)
    {
        $this->id = $id;
    }

}

class Account
{
    /** @var  Id $id */
    public $id;
}

$account_id = false;

if (starsAreRight()) {
    $account_id = new Id(42);
}

$account = new Account();
if ($account instanceof Id)
{
    $account->id = $account_id;
}
Loading history...
113
    }
114
115
    /**
116
     * Launch the websocket server.
117
     *
118
     * @throws \Exception
119
     */
120
    public function start()
121
    {
122
        if ($this->config['prod'] && \extension_loaded('xdebug')) {
123
            throw new \Exception('xdebug is enabled, it\'s a performance issue. Disable that extension or specify "prod" option to false.');
124
        }
125
        
126
        $this->loop = \React\EventLoop\Factory::create();
127
        $socket = new \React\Socket\Server($this->loop);
128
129
        if ($this->config['ssl']) {
130
            $socket = new \React\Socket\SecureServer($socket, $this->loop, array_merge([
131
                'local_cert' => $this->config['certFile'],
132
                'passphrase' => $this->config['passphrase'],
133
            ], $this->config['sslContextOptions']));
134
            $this->getLogger()->info('Enabled ssl');
135
        }
136
137
        $socket->on('connection', function ($socketStream) {
138
            $this->onNewConnection($socketStream);
139
        });
140
        $socket->listen($this->port);
141
142
        $this->getLogger()->info('Listening on ' . $this->host . ':' . $this->port);
143
144
        $this->loop->run();
145
    }
146
147
    /**
148
     * @param ConnectionInterface $socketStream
149
     */
150
    private function onNewConnection(ConnectionInterface $socketStream)
151
    {
152
        $messageHandler = $this->messageHandler;
153
        if (\is_string($messageHandler)) {
154
            $messageHandler = new $messageHandler;
155
        }
156
157
        $connection = new Connection($socketStream, $messageHandler, $this->loop, $this->messageProcessor);
158
        $connection->setLogger($this->getLogger());
159
        $this->connections[] = $connection;
160
    }
161
162
    /**
163
     * Build the message processor with configuration
164
     */
165 3
    private function buildMessageProcessor()
166
    {
167 3
        $this->messageProcessor = new MessageProcessor(
168 3
            new FrameFactory($this->config['frame']),
169 3
            new MessageFactory($this->config['message'])
170
        );
171 3
        $this->messageProcessor->addHandler(new PingFrameHandler());
172 3
        $this->messageProcessor->addHandler(new CloseFrameHandler());
173 3
        $this->messageProcessor->addHandler(new WrongOpcodeHandler());
174 3
        $this->messageProcessor->addHandler(new RsvCheckFrameHandler());
175
176 3
        foreach ($this->config['messageHandlers'] as $handler) {
177 1
            if (!$handler instanceof MessageHandlerInterface) {
178 1
                throw new RuntimeException(sprintf('%s is not an instance of MessageHandlerInterface but must be !', get_class($handler)));
179
            }
180
        }
181 2
    }
182
183
    /**
184
     * Sets the configuration
185
     *
186
     * @param array $config
187
     * @throws ConfigException
188
     */
189 4
    private function setConfig(array $config)
190
    {
191 4
        $this->config = \array_merge([
192 4
            'frame' => [],
193
            'message' => [],
194
            'messageHandlers' => [],
195
            'prod' => true,
196
            'ssl' => false,
197
            'certFile' => '',
198
            'passphrase' => '',
199
            'sslContextOptions' => [],
200
        ], $config);
201
202 4
        if ($this->config['ssl'] && !is_file($this->config['certFile'])) {
203 1
            throw new ConfigException('With ssl configuration, you need to specify a certificate file.');
204
        }
205 3
    }
206
207
    /**
208
     * @return SimpleLogger|LoggerInterface
209
     */
210
    public function getLogger()
211
    {
212
        if (null === $this->logger) {
213
            return $this->logger = new SimpleLogger(!$this->config['prod']);
214
        }
215
216
        return $this->logger;
217
    }
218
219
    /**
220
     * Allows you to set a custom logger
221
     *
222
     * @param LoggerInterface $logger
223
     * @return WebSocketServer
224
     */
225
    public function setLogger(LoggerInterface $logger)
226
    {
227
        $this->logger = $logger;
228
229
        return $this;
230
    }
231
}
232