Completed
Pull Request — master (#101)
by Maxime
02:49
created

WebSocketServer::start()   B

Complexity

Conditions 4
Paths 3

Size

Total Lines 25
Code Lines 15

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 20

Importance

Changes 0
Metric Value
dl 0
loc 25
ccs 0
cts 16
cp 0
rs 8.5806
c 0
b 0
f 0
cc 4
eloc 15
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\RuntimeException;
15
use Nekland\Woketo\Message\MessageHandlerInterface;
16
use Nekland\Woketo\Rfc6455\FrameFactory;
17
use Nekland\Woketo\Rfc6455\MessageFactory;
18
use Nekland\Woketo\Rfc6455\MessageHandler\CloseFrameHandler;
19
use Nekland\Woketo\Rfc6455\MessageHandler\RsvCheckFrameHandler;
20
use Nekland\Woketo\Rfc6455\MessageHandler\WrongOpcodeHandler;
21
use Nekland\Woketo\Rfc6455\MessageHandler\PingFrameHandler;
22
use Nekland\Woketo\Rfc6455\MessageProcessor;
23
use Nekland\Woketo\Rfc6455\ServerHandshake;
24
use Nekland\Woketo\Utils\SimpleLogger;
25
use Psr\Log\LoggerInterface;
26
use Psr\Log\LogLevel;
27
use React\EventLoop\LoopInterface;
28
use React\Socket\ConnectionInterface;
29
30
class WebSocketServer
31
{
32
    /**
33
     * @var int
34
     */
35
    private $port;
36
37
    /**
38
     * @var string
39
     */
40
    private $host;
41
42
    /**
43
     * @var ServerHandshake
44
     */
45
    private $handshake;
46
47
    /**
48
     * @var MessageHandlerInterface
49
     */
50
    private $messageHandler;
51
52
    /**
53
     * @var array
54
     */
55
    private $connections;
56
57
    /**
58
     * @var LoopInterface
59
     */
60
    private $loop;
61
62
    /**
63
     * @var MessageProcessor
64
     */
65
    private $messageProcessor;
66
67
    /**
68
     * @var array
69
     */
70
    private $config;
71
72
    /**
73
     * @var LoggerInterface
74
     */
75
    private $logger;
76
77
    /**
78
     * @param int    $port    The number of the port to bind
79
     * @param string $host    The host to listen on (by default 127.0.0.1)
80
     * @param array  $config
81
     */
82 3
    public function __construct($port, $host = '127.0.0.1', $config = [])
83
    {
84 3
        $this->setConfig($config);
85 3
        $this->host = $host;
86 3
        $this->port = $port;
87 3
        $this->handshake = new ServerHandshake();
88 3
        $this->connections = [];
89 3
        $this->buildMessageProcessor();
90
91
        // Some optimization
92 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
93 2
        \set_time_limit(0); // It's by default on most server for cli apps but better be sure of that fact
94 2
    }
95
96
    public function setMessageHandler($messageHandler)
97
    {
98
        if (!$messageHandler instanceof MessageHandlerInterface &&  !\is_string($messageHandler)) {
99
            throw new \InvalidArgumentException('The message handler must be an instance of MessageHandlerInterface or a string.');
100
        }
101
        if (\is_string($messageHandler)) {
102
            try {
103
                $reflection = new \ReflectionClass($messageHandler);
104
                if(!$reflection->implementsInterface('Nekland\Woketo\Message\MessageHandlerInterface')) {
105
                    throw new \InvalidArgumentException('The messageHandler must implement MessageHandlerInterface');
106
                }
107
            } catch (\ReflectionException $e) {
108
                throw new \InvalidArgumentException('The messageHandler must be a string representing a class.');
109
            }
110
        }
111
        $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...
112
    }
113
114
    /**
115
     * Launch the websocket server.
116
     *
117
     * @throws \Exception
118
     */
119
    public function start()
120
    {
121
        if ($this->config['prod'] && \extension_loaded('xdebug')) {
122
            throw new \Exception('xdebug is enabled, it\'s a performance issue. Disable that extension or specify "prod" option to false.');
123
        }
124
        
125
        $this->loop = \React\EventLoop\Factory::create();
126
        $socket = new \React\Socket\Server($this->loop);
127
128
        if ($this->config['ssl']) {
129
            $socket = new \React\Socket\SecureServer($socket, $this->loop, array_merge([
130
                'local_cert' => $this->config['certFile'],
131
                'passphrase' => $this->config['passphrase'],
132
            ], $this->config['ssl_context_options']));
133
        }
134
135
        $socket->on('connection', function ($socketStream) {
136
            $this->onNewConnection($socketStream);
137
        });
138
        $socket->listen($this->port);
139
140
        $this->getLogger()->info('Listening on ' . $this->host . ':' . $this->port);
141
142
        $this->loop->run();
143
    }
144
145
    /**
146
     * @param ConnectionInterface $socketStream
147
     */
148
    private function onNewConnection(ConnectionInterface $socketStream)
149
    {
150
        $messageHandler = $this->messageHandler;
151
        if (\is_string($messageHandler)) {
152
            $messageHandler = new $messageHandler;
153
        }
154
155
        $connection = new Connection($socketStream, $messageHandler, $this->loop, $this->messageProcessor);
156
        $connection->setLogger($this->getLogger());
157
        $this->connections[] = $connection;
158
    }
159
160
    /**
161
     * Build the message processor with configuration
162
     */
163 3
    private function buildMessageProcessor()
164
    {
165 3
        $this->messageProcessor = new MessageProcessor(
166 3
            new FrameFactory($this->config['frame']),
167 3
            new MessageFactory($this->config['message'])
168
        );
169 3
        $this->messageProcessor->addHandler(new PingFrameHandler());
170 3
        $this->messageProcessor->addHandler(new CloseFrameHandler());
171 3
        $this->messageProcessor->addHandler(new WrongOpcodeHandler());
172 3
        $this->messageProcessor->addHandler(new RsvCheckFrameHandler());
173
174 3
        foreach ($this->config['messageHandlers'] as $handler) {
175 1
            if (!$handler instanceof MessageHandlerInterface) {
176 1
                throw new RuntimeException(sprintf('%s is not an instance of MessageHandlerInterface but must be !', get_class($handler)));
177
            }
178
        }
179 2
    }
180
181
    /**
182
     * Sets the configuration
183
     *
184
     * @param array $config
185
     */
186 3
    private function setConfig(array $config)
187
    {
188 3
        $this->config = \array_merge([
189 3
            'frame' => [],
190
            'message' => [],
191
            'messageHandlers' => [],
192
            'prod' => true,
193
            'ssl' => false,
194
            'certFile' => '',
195
            'passphrase' => '',
196
            'ssl_context' => [],
197
        ], $config);
198 3
    }
199
200
    /**
201
     * @return SimpleLogger|LoggerInterface
202
     */
203
    public function getLogger()
204
    {
205
        if (null === $this->logger) {
206
            return $this->logger = new SimpleLogger(!$this->config['prod']);
207
        }
208
209
        return $this->logger;
210
    }
211
212
    /**
213
     * Allows you to set a custom logger
214
     *
215
     * @param LoggerInterface $logger
216
     * @return WebSocketServer
217
     */
218
    public function setLogger(LoggerInterface $logger)
219
    {
220
        $this->logger = $logger;
221
222
        return $this;
223
    }
224
}
225