Completed
Push — master ( 94a773...ff8a0b )
by Charlotte
9s
created

WebSocketServer::setConfig()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 9
Code Lines 7

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 4
CRAP Score 1

Importance

Changes 0
Metric Value
dl 0
loc 9
ccs 4
cts 4
cp 1
rs 9.6666
c 0
b 0
f 0
cc 1
eloc 7
nc 1
nop 1
crap 1
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 React\EventLoop\LoopInterface;
25
use React\Socket\ConnectionInterface;
26
27
class WebSocketServer
28
{
29
    /**
30
     * @var int Store the port for debug purpose.
31
     */
32
    private $port;
33
34
    /**
35
     * @var string
36
     */
37
    private $address;
38
39
    /**
40
     * @var ServerHandshake
41
     */
42
    private $handshake;
43
44
    /**
45
     * @var MessageHandlerInterface
46
     */
47
    private $messageHandler;
48
49
    /**
50
     * @var array
51
     */
52
    private $connections;
53
54
    /**
55
     * @var LoopInterface
56
     */
57
    private $loop;
58
59
    /**
60
     * @var MessageProcessor
61
     */
62
    private $messageProcessor;
63
64
    /**
65
     * @var array
66
     */
67
    private $config;
68
69
    /**
70
     * Websocket constructor.
71
     *
72
     * @param int    $port    The number of the port to bind
73
     * @param string $address The address to listen on (by default 127.0.0.1)
74
     * @param array  $config
75
     */
76 3
    public function __construct($port, $address = '127.0.0.1', $config = [])
77
    {
78 3
        $this->setConfig($config);
79 3
        $this->address = $address;
80 3
        $this->port = $port;
81 3
        $this->handshake = new ServerHandshake();
82 3
        $this->connections = [];
83 3
        $this->buildMessageProcessor();
84
85
        // Some optimization
86 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
87 2
        \set_time_limit(0); // It's by default on most server for cli apps but better be sure of that fact
88 2
    }
89
90
    public function setMessageHandler($messageHandler)
91
    {
92
        if (!$messageHandler instanceof MessageHandlerInterface &&  !\is_string($messageHandler)) {
93
            throw new \InvalidArgumentException('The message handler must be an instance of MessageHandlerInterface or a string.');
94
        }
95
        if (\is_string($messageHandler)) {
96
            try {
97
                $reflection = new \ReflectionClass($messageHandler);
98
                if(!$reflection->implementsInterface('Nekland\Woketo\Message\MessageHandlerInterface')) {
99
                    throw new \InvalidArgumentException('The messageHandler must implement MessageHandlerInterface');
100
                }
101
            } catch (\ReflectionException $e) {
102
                throw new \InvalidArgumentException('The messageHandler must be a string representing a class.');
103
            }
104
        }
105
        $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...
106
    }
107
108
    public function start()
109
    {
110
        if ($this->config['prod'] && \extension_loaded('xdebug')) {
111
            throw new \Exception('xdebug is enabled, it\'s a performance issue. Disable that extension or specify "prod" option to false.');
112
        }
113
        
114
        $this->loop = \React\EventLoop\Factory::create();
115
116
        $socket = new \React\Socket\Server($this->loop);
117
        $socket->on('connection', function ($socketStream) {
118
            $this->onNewConnection($socketStream);
119
        });
120
        $socket->listen($this->port);
121
122
        $this->loop->run();
123
    }
124
125
    /**
126
     * @param ConnectionInterface $socketStream
127
     */
128
    private function onNewConnection(ConnectionInterface $socketStream)
129
    {
130
        $messageHandler = $this->messageHandler;
131
        if (\is_string($messageHandler)) {
132
            $messageHandler = new $messageHandler;
133
        }
134
135
        $this->connections[] = new Connection($socketStream, $messageHandler, $this->loop, $this->messageProcessor);
136
    }
137
138
    /**
139
     * Build the message processor with configuration
140
     */
141 3
    private function buildMessageProcessor()
142
    {
143 3
        $this->messageProcessor = new MessageProcessor(
144 3
            new FrameFactory($this->config['frame']),
145 3
            new MessageFactory($this->config['message'])
146
        );
147 3
        $this->messageProcessor->addHandler(new PingFrameHandler());
148 3
        $this->messageProcessor->addHandler(new CloseFrameHandler());
149 3
        $this->messageProcessor->addHandler(new WrongOpcodeHandler());
150 3
        $this->messageProcessor->addHandler(new RsvCheckFrameHandler());
151
152 3
        foreach ($this->config['messageHandlers'] as $handler) {
153 1
            if (!$handler instanceof MessageHandlerInterface) {
154 1
                throw new RuntimeException(sprintf('%s is not an instance of MessageHandlerInterface but must be !', get_class($handler)));
155
            }
156
        }
157 2
    }
158
159
    /**
160
     * Sets the configuration
161
     *
162
     * @param array $config
163
     */
164 3
    private function setConfig(array $config)
165
    {
166 3
        $this->config = \array_merge([
167 3
            'frame' => [],
168
            'message' => [],
169
            'messageHandlers' => [],
170
            'prod' => true
171
        ], $config);
172 3
    }
173
}
174