Completed
Pull Request — master (#100)
by Maxime
03:08
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\Request;
20
use Nekland\Woketo\Http\Response;
21
use Nekland\Woketo\Http\Url;
22
use Nekland\Woketo\Message\MessageHandlerInterface;
23
use Nekland\Woketo\Rfc6455\Frame;
24
use Nekland\Woketo\Rfc6455\Handshake\ClientHandshake;
25
use Nekland\Woketo\Rfc6455\MessageProcessor;
26
use React\Promise\PromiseInterface;
27
use React\Stream\Stream;
28
29
class Connection extends AbstractConnection
30
{
31
    /**
32
     * @var bool
33
     */
34
    private $requestSent;
35
36
    /**
37
     * @var string
38
     */
39
    private $buffer;
40
41
    /**
42
     * @var Url
43
     */
44
    private $url;
45
46
    public function __construct(Url $url, PromiseInterface $clientPromise, MessageProcessor $messageProcessor, MessageHandlerInterface $handler)
47
    {
48
        parent::__construct($messageProcessor, new ClientHandshake());
49
50
        $this->requestSent = false;
51
        $this->url = $url;
52
        $this->uri = $this->url->getUri();
53
        $this->buffer = '';
54
        $this->handler = $handler;
55
56
        $clientPromise->then(function (Stream $stream) {
57
            $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...
58
            $this->onConnection($stream);
59
        }, function (\Exception $error){
60
            $this->onError($error);
61
        });
62
    }
63
64
    private function onConnection(Stream $stream)
65
    {
66
        $stream->on('data', function (string $data) {
67
            $this->onMessage($data);
68
        });
69
70
        // This is done because the handshake should come from the client.
71
        $this->processHandshake('');
72
    }
73
74
    /**
75
     * @param string $data
76
     */
77
    protected function processHandshake(string $data)
78
    {
79
        // Sending initialization request
80
        if (!$this->requestSent) {
81
            $request = $this->handshake->getRequest($this->url->getUri(), $this->url->getHost());
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...
82
            $this->stream->write($request->getRequestAsString());
83
            $this->requestSent = true;
84
            return;
85
        }
86
87
        $this->buffer .= $data;
88
89
        // Receiving the response
90
        try {
91
            $response = Response::create($data);
92
        } catch (IncompleteHttpMessageException $e) {
93
            return;
94
        }
95
96
        // Verifying response data
97
        $this->handshake->verify($response);
98
99
        // Signaling the handshake is done to jump in the message exchange process
100
        $this->handshakeDone = true;
101
        $this->getHandler()->onConnection($this);
102
    }
103
104
    protected function processMessage(string $data)
105
    {
106
        // It may be a timeout going (we were waiting for data), let's clear it.
107
        if ($this->timeout !== null) {
108
            $this->timeout->cancel();
109
            $this->timeout = null;
110
        }
111
112
113
        foreach ($this->messageProcessor->onData($data, $this->stream, $this->currentMessage) as $message) {
114
            $this->currentMessage = $message;
115
116
            if ($this->currentMessage->isComplete()) {
117
                // Sending the message through the woketo API.
118
                switch($this->currentMessage->getOpcode()) {
119
                    case Frame::OP_TEXT:
120
                        $this->getHandler()->onMessage($this->currentMessage->getContent(), $this);
121
                        break;
122
                    case Frame::OP_BINARY:
123
                        $this->getHandler()->onBinary($this->currentMessage->getContent(), $this);
124
                        break;
125
                }
126
                $this->currentMessage = null;
127
128
            } else {
129
                // We wait for more data so we start a timeout.
130
                $this->timeout = $this->loop->addTimer(Connection::DEFAULT_TIMEOUT, function () {
131
                    $this->logger->notice('Connection to ' . $this->getIp() . ' timed out.');
132
                    $this->messageProcessor->timeout($this->stream);
133
                });
134
            }
135
        }
136
    }
137
138
    /**
139
     * @param string|Frame $frame
140
     * @param int          $opCode An int representing binary or text data (const of Frame class)
141
     * @throws \Nekland\Woketo\Exception\RuntimeException
142
     */
143
    public function write($frame, int $opCode = Frame::OP_TEXT)
144
    {
145
        try {
146
            $this->messageProcessor->writeMasked($frame, $this->stream, $opCode);
147
        } catch (WebsocketException $e) {
148
            throw new RuntimeException($e);
149
        }
150
    }
151
152
    /**
153
     * @param \Exception|string $error
154
     */
155
    private function onError($error)
156
    {
157
        $error = $error instanceof \Exception ? $error->getMessage() : $error;
158
159
        $this->logger->error(sprintf('An error occured: %s', $error));
160
    }
161
162
    /**
163
     * May return ip or hostname
164
     *
165
     * @return string
166
     */
167
    public function getIp()
168
    {
169
        return $this->url->getHost();
170
    }
171
}
172