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

Connection::processMessage()   B

Complexity

Conditions 6
Paths 10

Size

Total Lines 33
Code Lines 19

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 42

Importance

Changes 0
Metric Value
dl 0
loc 33
ccs 0
cts 26
cp 0
rs 8.439
c 0
b 0
f 0
cc 6
eloc 19
nc 10
nop 1
crap 42
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\Client;
13
14
15
use Nekland\Woketo\Core\AbstractConnection;
16
use Nekland\Woketo\Exception\Http\IncompleteHttpMessageException;
17
use Nekland\Woketo\Exception\RuntimeException;
18
use Nekland\Woketo\Exception\WebsocketException;
19
use Nekland\Woketo\Http\Response;
20
use Nekland\Woketo\Http\Url;
21
use Nekland\Woketo\Message\MessageHandlerInterface;
22
use Nekland\Woketo\Rfc6455\Frame;
23
use Nekland\Woketo\Rfc6455\Handshake\ClientHandshake;
24
use Nekland\Woketo\Rfc6455\MessageProcessor;
25
use React\Promise\PromiseInterface;
26
use React\Stream\Stream;
27
28
class Connection extends AbstractConnection
29
{
30
    /**
31
     * @var string|null
32
     */
33
    private $handshakeKey;
34
35
    /**
36
     * @var string
37
     */
38
    private $buffer;
39
40
    /**
41
     * @var Url
42
     */
43
    private $url;
44
45
    public function __construct(Url $url, PromiseInterface $clientPromise, MessageProcessor $messageProcessor, MessageHandlerInterface $handler)
46
    {
47
        parent::__construct($messageProcessor, new ClientHandshake());
48
49
        $this->url = $url;
50
        $this->uri = $this->url->getUri();
51
        $this->buffer = '';
52
        $this->handler = $handler;
53
54
        $clientPromise->then(function (Stream $stream) {
55
            $this->stream = $stream;
0 ignored issues
show
Documentation Bug introduced by
$stream is of type object<React\Stream\Stream>, 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...
56
            $this->onConnection($stream);
57
        }, function (\Exception $error){
58
            $this->onError($error);
59
        });
60
    }
61
62
    private function onConnection(Stream $stream)
63
    {
64
        $stream->on('data', function (string $data) {
65
            $this->onMessage($data);
66
        });
67
68
        // This is done because the handshake should come from the client.
69
        $this->processHandshake('');
70
    }
71
72
    /**
73
     * @param string $data
74
     */
75
    protected function processHandshake(string $data)
76
    {
77
        // Sending initialization request
78
        if (null === $this->handshakeKey) {
79
            $request = $this->handshake->getRequest($this->url);
0 ignored issues
show
Bug introduced by
The method getRequest does only exist in Nekland\Woketo\Rfc6455\Handshake\ClientHandshake, but not in Nekland\Woketo\Rfc6455\Handshake\ServerHandshake.

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...
80
            $this->stream->write($request->getRequestAsString());
81
            $this->handshakeKey = $request->getKey();
82
83
            return;
84
        }
85
86
        $this->buffer .= $data;
87
88
        // Receiving the response
89
        try {
90
            $response = Response::create($this->buffer);
91
        } catch (IncompleteHttpMessageException $e) {
92
            return;
93
        }
94
95
        // Verifying response data
96
        $this->handshake->verify($response, $this->handshakeKey);
97
98
        // Signaling the handshake is done to jump in the message exchange process
99
        $this->handshakeDone = true;
100
        $this->getHandler()->onConnection($this);
101
102
        if (!empty($this->buffer)) {
103
            $buffer = $this->buffer;
104
            $this->buffer = '';
105
            $this->onMessage($buffer);
106
        }
107
    }
108
109
    protected function processMessage(string $data)
110
    {
111
        // It may be a timeout going (we were waiting for data), let's clear it.
112
        if ($this->timeout !== null) {
113
            $this->timeout->cancel();
114
            $this->timeout = null;
115
        }
116
117
118
        foreach ($this->messageProcessor->onData($data, $this->stream, $this->currentMessage) as $message) {
119
            $this->currentMessage = $message;
120
121
            if ($this->currentMessage->isComplete()) {
122
                // Sending the message through the woketo API.
123
                switch($this->currentMessage->getOpcode()) {
124
                    case Frame::OP_TEXT:
125
                        $this->getHandler()->onMessage($this->currentMessage->getContent(), $this);
126
                        break;
127
                    case Frame::OP_BINARY:
128
                        $this->getHandler()->onBinary($this->currentMessage->getContent(), $this);
129
                        break;
130
                }
131
                $this->currentMessage = null;
132
133
            } else {
134
                // We wait for more data so we start a timeout.
135
                $this->timeout = $this->loop->addTimer(Connection::DEFAULT_TIMEOUT, function () {
136
                    $this->getLogger()->notice('Connection to ' . $this->getIp() . ' timed out.');
137
                    $this->messageProcessor->timeout($this->stream);
138
                });
139
            }
140
        }
141
    }
142
143
    /**
144
     * @param string|Frame $frame
145
     * @param int          $opCode An int representing binary or text data (const of Frame class)
146
     * @throws \Nekland\Woketo\Exception\RuntimeException
147
     */
148
    public function write($frame, int $opCode = Frame::OP_TEXT)
149
    {
150
        try {
151
            $this->messageProcessor->writeMasked($frame, $this->stream, $opCode);
152
        } catch (WebsocketException $e) {
153
            throw new RuntimeException($e);
154
        }
155
    }
156
157
    /**
158
     * @param \Exception|string $error
159
     */
160
    private function onError($error)
161
    {
162
        $error = $error instanceof \Exception ? $error->getMessage() : $error;
163
164
        $this->getLogger()->error(sprintf('An error occured: %s', $error));
165
    }
166
167
    /**
168
     * May return ip or hostname
169
     *
170
     * @return string
171
     */
172
    public function getIp()
173
    {
174
        return $this->url->getHost();
175
    }
176
}
177