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

WebSocketServer::buildMessageProcessor()   A

Complexity

Conditions 3
Paths 3

Size

Total Lines 17
Code Lines 11

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 12
CRAP Score 3

Importance

Changes 0
Metric Value
dl 0
loc 17
ccs 12
cts 12
cp 1
rs 9.4285
c 0
b 0
f 0
cc 3
eloc 11
nc 3
nop 0
crap 3
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
            $this->getLogger()->info('Enabled ssl');
134
        }
135
136
        $socket->on('connection', function ($socketStream) {
137
            $this->onNewConnection($socketStream);
138
        });
139
        $socket->listen($this->port);
140
141
        $this->getLogger()->info('Listening on ' . $this->host . ':' . $this->port);
142
143
        $this->loop->run();
144
    }
145
146
    /**
147
     * @param ConnectionInterface $socketStream
148
     */
149
    private function onNewConnection(ConnectionInterface $socketStream)
150
    {
151
        $messageHandler = $this->messageHandler;
152
        if (\is_string($messageHandler)) {
153
            $messageHandler = new $messageHandler;
154
        }
155
156
        $connection = new Connection($socketStream, $messageHandler, $this->loop, $this->messageProcessor);
157
        $connection->setLogger($this->getLogger());
158
        $this->connections[] = $connection;
159
    }
160
161
    /**
162
     * Build the message processor with configuration
163
     */
164 3
    private function buildMessageProcessor()
165
    {
166 3
        $this->messageProcessor = new MessageProcessor(
167 3
            new FrameFactory($this->config['frame']),
168 3
            new MessageFactory($this->config['message'])
169
        );
170 3
        $this->messageProcessor->addHandler(new PingFrameHandler());
171 3
        $this->messageProcessor->addHandler(new CloseFrameHandler());
172 3
        $this->messageProcessor->addHandler(new WrongOpcodeHandler());
173 3
        $this->messageProcessor->addHandler(new RsvCheckFrameHandler());
174
175 3
        foreach ($this->config['messageHandlers'] as $handler) {
176 1
            if (!$handler instanceof MessageHandlerInterface) {
177 1
                throw new RuntimeException(sprintf('%s is not an instance of MessageHandlerInterface but must be !', get_class($handler)));
178
            }
179
        }
180 2
    }
181
182
    /**
183
     * Sets the configuration
184
     *
185
     * @param array $config
186
     */
187 3
    private function setConfig(array $config)
188
    {
189 3
        $this->config = \array_merge([
190 3
            'frame' => [],
191
            'message' => [],
192
            'messageHandlers' => [],
193
            'prod' => true,
194
            'ssl' => false,
195
            'certFile' => '',
196
            'passphrase' => '',
197
            'ssl_context_options' => [],
198
        ], $config);
199 3
    }
200
201
    /**
202
     * @return SimpleLogger|LoggerInterface
203
     */
204
    public function getLogger()
205
    {
206
        if (null === $this->logger) {
207
            return $this->logger = new SimpleLogger(!$this->config['prod']);
208
        }
209
210
        return $this->logger;
211
    }
212
213
    /**
214
     * Allows you to set a custom logger
215
     *
216
     * @param LoggerInterface $logger
217
     * @return WebSocketServer
218
     */
219
    public function setLogger(LoggerInterface $logger)
220
    {
221
        $this->logger = $logger;
222
223
        return $this;
224
    }
225
}
226