Completed
Push — master ( 4b839d...94a773 )
by Valentin
02:14
created

src/Server/Websocket.php (1 issue)

Upgrade to new PHP Analysis Engine

These results are based on our legacy PHP analysis, consider migrating to our new PHP analysis engine instead. Learn more

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 Websocket
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
    public function __construct($port, $address = '127.0.0.1', $config = [])
77
    {
78
        $this->address = $address;
79
        $this->port = $port;
80
        $this->handshake = new ServerHandshake();
81
        $this->connections = [];
82
        $this->setConfig($config);
83
        $this->buildMessageProcessor();
84
    }
85
86
    public function setMessageHandler($messageHandler)
87
    {
88
        if (!$messageHandler instanceof MessageHandlerInterface &&  !\is_string($messageHandler)) {
89
            throw new \InvalidArgumentException('The message handler must be an instance of MessageHandlerInterface or a string.');
90
        }
91
        if (\is_string($messageHandler)) {
92
            try {
93
                $reflection = new \ReflectionClass($messageHandler);
94
                if(!$reflection->implementsInterface('Nekland\Woketo\Message\MessageHandlerInterface')) {
95
                    throw new \InvalidArgumentException('The messageHandler must implement MessageHandlerInterface');
96
                }
97
            } catch (\ReflectionException $e) {
98
                throw new \InvalidArgumentException('The messageHandler must be a string representing a class.');
99
            }
100
        }
101
        $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...
102
    }
103
104
    public function start()
105
    {
106
        $this->loop = \React\EventLoop\Factory::create();
107
108
        $socket = new \React\Socket\Server($this->loop);
109
        $socket->on('connection', function ($socketStream) {
110
            $this->onNewConnection($socketStream);
111
        });
112
        $socket->listen($this->port);
113
114
        $this->loop->run();
115
    }
116
117
    /**
118
     * @param ConnectionInterface $socketStream
119
     */
120
    private function onNewConnection(ConnectionInterface $socketStream)
121
    {
122
        $messageHandler = $this->messageHandler;
123
        if (\is_string($messageHandler)) {
124
            $messageHandler = new $messageHandler;
125
        }
126
127
        $this->connections[] = new Connection($socketStream, $messageHandler, $this->loop, $this->messageProcessor);
128
    }
129
130
    /**
131
     * Build the message processor with configuration
132
     */
133
    private function buildMessageProcessor()
134
    {
135
        $this->messageProcessor = new MessageProcessor(
136
            new FrameFactory($this->config['frame']),
137
            new MessageFactory($this->config['message'])
138
        );
139
        $this->messageProcessor->addHandler(new PingFrameHandler());
140
        $this->messageProcessor->addHandler(new CloseFrameHandler());
141
        $this->messageProcessor->addHandler(new WrongOpcodeHandler());
142
        $this->messageProcessor->addHandler(new RsvCheckFrameHandler());
143
144
        foreach ($this->config['messageHandlers'] as $handler) {
145
            if (!$handler instanceof MessageHandlerInterface) {
146
                throw new RuntimeException(sprintf('%s is not an instance of MessageHandlerInterface but must be !', get_class($handler)));
147
            }
148
        }
149
    }
150
151
    /**
152
     * Sets the configuration
153
     *
154
     * @param array $config
155
     */
156
    private function setConfig(array $config)
157
    {
158
        $this->config = \array_merge([
159
            'frame' => [],
160
            'message' => [],
161
            'messageHandlers' => []
162
        ], $config);
163
    }
164
}
165