Completed
Pull Request — master (#100)
by Maxime
02:21
created

Connection::processHandcheck()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 16
Code Lines 11

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 6

Importance

Changes 1
Bugs 0 Features 0
Metric Value
dl 0
loc 16
ccs 0
cts 14
cp 0
rs 9.4285
c 1
b 0
f 0
cc 2
eloc 11
nc 2
nop 1
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\Core\AbstractConnection;
15
use Nekland\Woketo\Exception\NoHandlerException;
16
use Nekland\Woketo\Exception\RuntimeException;
17
use Nekland\Woketo\Exception\WebsocketException;
18
use Nekland\Woketo\Http\Request;
19
use Nekland\Woketo\Http\Response;
20
use Nekland\Woketo\Rfc6455\Frame;
21
use Nekland\Woketo\Rfc6455\MessageProcessor;
22
use Nekland\Woketo\Rfc6455\Handshake\ServerHandshake;
23
use React\EventLoop\LoopInterface;
24
use React\Socket\ConnectionInterface;
25
26
class Connection extends AbstractConnection
27
{
28
    public function __construct(
29
        ConnectionInterface $socketStream,
30
        \Closure $messageHandler,
31
        LoopInterface $loop,
32
        MessageProcessor $messageProcessor,
33
        ServerHandshake $handshake = null
34
    ) {
35
        parent::__construct($messageProcessor, $handshake ?: new ServerHandshake);
36
        $this->stream = $socketStream;
0 ignored issues
show
Documentation Bug introduced by
$socketStream is of type object<React\Socket\ConnectionInterface>, but the property $stream was declared to be of type object<React\Socket\Connection>. Are you sure that you always receive this specific sub-class here, or does it make sense to add an instanceof 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 given class or a super-class is assigned to a property that is type hinted more strictly.

Either this assignment is in error or an instanceof check should be added for that assignment.

class Alien {}

class Dalek extends Alien {}

class Plot
{
    /** @var  Dalek */
    public $villain;
}

$alien = new Alien();
$plot = new Plot();
if ($alien instanceof Dalek) {
    $plot->villain = $alien;
}
Loading history...
37
        $this->initListeners();
38
        $this->handler = $messageHandler;
39
        $this->loop = $loop;
40
    }
41
42
    private function initListeners()
43
    {
44
        $this->stream->on('data', function ($data) {
45
            $this->processData($data);
46
        });
47
        $this->stream->on('error', function ($data) {
48
            $this->error($data);
49
        });
50
    }
51
52
    private function processData($data)
53
    {
54
        try {
55
            if (!$this->handshakeDone) {
56
                $this->processHandshake($data);
57
            } else {
58
                $this->processMessage($data);
59
            }
60
61
            return;
62
        } catch (WebsocketException $e) {
63
            $this->messageProcessor->close($this->stream);
64
            $this->logger->notice('Connection to ' . $this->getIp() . ' closed with error : ' . $e->getMessage());
65
            $this->getHandler()->onError($e, $this);
66
        } catch (NoHandlerException $e) {
67
            $this->getLogger()->info(sprintf('No handler found for uri %s. Connection closed.', $this->uri));
68
            $this->close();
69
        }
70
    }
71
72
    /**
73
     * This method build a message and buffer data in case of incomplete data.
74
     *
75
     * @param string $data
76
     */
77
    protected function processMessage(string $data)
78
    {
79
        // It may be a timeout going (we were waiting for data), let's clear it.
80
        if ($this->timeout !== null) {
81
            $this->timeout->cancel();
82
            $this->timeout = null;
83
        }
84
85
        foreach ($this->messageProcessor->onData($data, $this->stream, $this->currentMessage) as $message) {
86
            $this->currentMessage = $message;
87
            if ($this->currentMessage->isComplete()) {
88
                // Sending the message through the woketo API.
89
                switch($this->currentMessage->getOpcode()) {
90
                    case Frame::OP_TEXT:
91
                        $this->getHandler()->onMessage($this->currentMessage->getContent(), $this);
92
                        break;
93
                    case Frame::OP_BINARY:
94
                        $this->getHandler()->onBinary($this->currentMessage->getContent(), $this);
95
                        break;
96
                }
97
                $this->currentMessage = null;
98
99
            } else {
100
                // We wait for more data so we start a timeout.
101
                $this->timeout = $this->loop->addTimer(Connection::DEFAULT_TIMEOUT, function () {
102
                    $this->logger->notice('Connection to ' . $this->getIp() . ' timed out.');
103
                    $this->messageProcessor->timeout($this->stream);
104
                });
105
            }
106
        }
107
    }
108
109
    /**
110
     * @param string|Frame $frame
111
     * @param int          $opCode An int representing binary or text data (const of Frame class)
112
     * @throws \Nekland\Woketo\Exception\RuntimeException
113
     */
114
    public function write($frame, int $opCode = Frame::OP_TEXT)
115
    {
116
        try {
117
            $this->messageProcessor->write($frame, $this->stream, $opCode);
118
        } catch (WebsocketException $e) {
119
            throw new RuntimeException($e);
120
        }
121
    }
122
123
    /**
124
     * @param mixed $data
125
     */
126
    protected function error($data)
127
    {
128
        $message = "A connectivity error occurred: " . $data;
129
        $this->logger->error($message);
130
        $this->getHandler()->onError(new WebsocketException($message), $this);
131
    }
132
133
    /**
134
     * If it's a new client, we need to make some special actions named the handshake.
135
     *
136
     * @param string $data
137
     */
138
    protected function processHandshake(string $data)
139
    {
140
        if ($this->handshakeDone) {
141
            return;
142
        }
143
144
        $request = Request::create($data);
145
        $this->handshake->verify($request);
146
        $this->uri = $request->getUri();
147
        $response = Response::createSwitchProtocolResponse();
148
        $this->handshake->sign($response, $this->handshake->extractKeyFromRequest($request));
0 ignored issues
show
Bug introduced by
The method extractKeyFromRequest does only exist in Nekland\Woketo\Rfc6455\Handshake\ServerHandshake, but not in Nekland\Woketo\Rfc6455\Handshake\ClientHandshake.

It seems like the method you are trying to call exists only in some of the possible types.

Let’s take a look at an example:

class A
{
    public function foo() { }
}

class B extends A
{
    public function bar() { }
}

/**
 * @param A|B $x
 */
function someFunction($x)
{
    $x->foo(); // This call is fine as the method exists in A and B.
    $x->bar(); // This method only exists in B and might cause an error.
}

Available Fixes

  1. Add an additional type-check:

    /**
     * @param A|B $x
     */
    function someFunction($x)
    {
        $x->foo();
    
        if ($x instanceof B) {
            $x->bar();
        }
    }
    
  2. Only allow a single type to be passed if the variable comes from a parameter:

    function someFunction(B $x) { /** ... */ }
    
Loading history...
149
        $response->send($this->stream);
150
151
        $this->handshakeDone = true;
152
        $this->getHandler()->onConnection($this);
153
    }
154
155
    /**
156
     * Close the connection with normal close.
157
     */
158
    public function close()
159
    {
160
        $this->messageProcessor->close($this->stream);
161
    }
162
}
163