Completed
Push — master ( 82da5d...012a80 )
by Charlotte
10s
created

WebSocketServer::getLogger()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 8
Code Lines 4

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 6

Importance

Changes 0
Metric Value
c 0
b 0
f 0
dl 0
loc 8
ccs 0
cts 4
cp 0
rs 9.4285
cc 2
eloc 4
nc 2
nop 0
crap 6
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
    public function start()
115
    {
116
        if ($this->config['prod'] && \extension_loaded('xdebug')) {
117
            throw new \Exception('xdebug is enabled, it\'s a performance issue. Disable that extension or specify "prod" option to false.');
118
        }
119
        
120
        $this->loop = \React\EventLoop\Factory::create();
121
122
        $socket = new \React\Socket\Server($this->loop);
123
        $socket->on('connection', function ($socketStream) {
124
            $this->onNewConnection($socketStream);
125
        });
126
        $socket->listen($this->port);
127
128
        $this->getLogger()->info('Listening on ' . $this->host . ':' . $this->port);
129
130
        $this->loop->run();
131
    }
132
133
    /**
134
     * @param ConnectionInterface $socketStream
135
     */
136
    private function onNewConnection(ConnectionInterface $socketStream)
137
    {
138
        $messageHandler = $this->messageHandler;
139
        if (\is_string($messageHandler)) {
140
            $messageHandler = new $messageHandler;
141
        }
142
143
        $connection = new Connection($socketStream, $messageHandler, $this->loop, $this->messageProcessor);
144
        $connection->setLogger($this->getLogger());
145
        $this->connections[] = $connection;
146
    }
147
148
    /**
149
     * Build the message processor with configuration
150
     */
151 3
    private function buildMessageProcessor()
152
    {
153 3
        $this->messageProcessor = new MessageProcessor(
154 3
            new FrameFactory($this->config['frame']),
155 3
            new MessageFactory($this->config['message'])
156
        );
157 3
        $this->messageProcessor->addHandler(new PingFrameHandler());
158 3
        $this->messageProcessor->addHandler(new CloseFrameHandler());
159 3
        $this->messageProcessor->addHandler(new WrongOpcodeHandler());
160 3
        $this->messageProcessor->addHandler(new RsvCheckFrameHandler());
161
162 3
        foreach ($this->config['messageHandlers'] as $handler) {
163 1
            if (!$handler instanceof MessageHandlerInterface) {
164 1
                throw new RuntimeException(sprintf('%s is not an instance of MessageHandlerInterface but must be !', get_class($handler)));
165
            }
166
        }
167 2
    }
168
169
    /**
170
     * Sets the configuration
171
     *
172
     * @param array $config
173
     */
174 3
    private function setConfig(array $config)
175
    {
176 3
        $this->config = \array_merge([
177 3
            'frame' => [],
178
            'message' => [],
179
            'messageHandlers' => [],
180
            'prod' => true
181
        ], $config);
182 3
    }
183
184
    /**
185
     * @return SimpleLogger|LoggerInterface
186
     */
187
    public function getLogger()
188
    {
189
        if (null === $this->logger) {
190
            return $this->logger = new SimpleLogger(!$this->config['prod']);
191
        }
192
193
        return $this->logger;
194
    }
195
196
    /**
197
     * Allows you to set a custom logger
198
     *
199
     * @param LoggerInterface $logger
200
     * @return WebSocketServer
201
     */
202
    public function setLogger(LoggerInterface $logger)
203
    {
204
        $this->logger = $logger;
205
206
        return $this;
207
    }
208
}
209