Completed
Push — master ( 45b50c...f7bb89 )
by Maxime
11s
created

Connection::processHandshake()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 16

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 11
CRAP Score 2.0023

Importance

Changes 0
Metric Value
dl 0
loc 16
ccs 11
cts 12
cp 0.9167
rs 9.7333
c 0
b 0
f 0
cc 2
nc 2
nop 1
crap 2.0023
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 8
    public function __construct(
29
        ConnectionInterface $socketStream,
30
        \Closure $messageHandler,
31
        LoopInterface $loop,
32
        MessageProcessor $messageProcessor,
33
        ServerHandshake $handshake = null
34
    ) {
35 8
        parent::__construct($messageProcessor, $loop, $handshake ?: new ServerHandshake);
36 8
        $this->stream = $socketStream;
37 8
        $this->initListeners();
38 8
        $this->handler = $messageHandler;
39 8
    }
40
41
    private function initListeners()
42
    {
43 8
        $this->stream->on('data', function ($data) {
44 7
            $this->processData($data);
45 8
        });
46 8
        $this->stream->once('end', function() {
47 2
            $this->getHandler()->onDisconnect($this);
48 8
        });
49 8
        $this->stream->on('error', function ($data) {
50
            $this->error($data);
51 8
        });
52 8
    }
53
54 7
    private function processData($data)
55
    {
56
        try {
57 7
            if (!$this->handshakeDone) {
58 7
                $this->processHandshake($data);
59
            } else {
60 2
                $this->processMessage($data);
61
            }
62
63 6
            return;
64 1
        } catch (WebsocketException $e) {
65
            $this->messageProcessor->close($this->stream);
66
            $this->logger->notice('Connection to ' . $this->getIp() . ' closed with error : ' . $e->getMessage());
67
            $this->getHandler()->onError($e, $this);
68 1
        } catch (NoHandlerException $e) {
69 1
            $this->getLogger()->info(sprintf('No handler found for uri %s. Connection closed.', $this->uri));
70 1
            $this->close(Frame::CLOSE_WRONG_DATA);
71
        }
72 1
    }
73
74
    /**
75
     * This method build a message and buffer data in case of incomplete data.
76
     *
77
     * @param string $data
78
     */
79 2
    protected function processMessage(string $data)
80
    {
81
        // It may be a timeout going (we were waiting for data), let's clear it.
82 2
        if ($this->timeout !== null) {
83
            $this->loop->cancelTimer($this->timeout);
84
            $this->timeout = null;
85
        }
86
87 2
        foreach ($this->messageProcessor->onData($data, $this->stream, $this->currentMessage) as $message) {
88 2
            $this->currentMessage = $message;
89 2
            if ($this->currentMessage->isComplete()) {
90
                // Sending the message through the woketo API.
91 2
                switch($this->currentMessage->getOpcode()) {
92 2
                    case Frame::OP_TEXT:
93 1
                        $this->getHandler()->onMessage($this->currentMessage->getContent(), $this);
94 1
                        break;
95 1
                    case Frame::OP_BINARY:
96 1
                        $this->getHandler()->onBinary($this->currentMessage->getContent(), $this);
97 1
                        break;
98
                }
99 2
                $this->currentMessage = null;
100
101
            } else {
102
                // We wait for more data so we start a timeout.
103 2
                $this->timeout = $this->loop->addTimer(Connection::DEFAULT_TIMEOUT, function () {
0 ignored issues
show
Coding Style introduced by
As per coding style, self should be used for accessing local static members.

This check looks for accesses to local static members using the fully qualified name instead of self::.

<?php

class Certificate {
    const TRIPLEDES_CBC = 'ASDFGHJKL';

    private $key;

    public function __construct()
    {
        $this->key = Certificate::TRIPLEDES_CBC;
    }
}

While this is perfectly valid, the fully qualified name of Certificate::TRIPLEDES_CBC could just as well be replaced by self::TRIPLEDES_CBC. Referencing local members with self:: assured the access will still work when the class is renamed, makes it perfectly clear that the member is in fact local and will usually be shorter.

Loading history...
104
                    $this->logger->notice('Connection to ' . $this->getIp() . ' timed out.');
105
                    $this->messageProcessor->timeout($this->stream);
106 2
                });
107
            }
108
        }
109 2
    }
110
111
    public function write($frame, int $opCode = Frame::OP_TEXT)
112
    {
113
        try {
114
            $this->messageProcessor->write($frame, $this->stream, $opCode);
115
        } catch (WebsocketException $e) {
116
            throw new RuntimeException($e);
117
        }
118
    }
119
120
    /**
121
     * @param mixed $data
122
     */
123
    protected function error($data)
124
    {
125
        $message = "A connectivity error occurred: " . $data;
126
        $this->logger->error($message);
127
        $this->getHandler()->onError(new WebsocketException($message), $this);
128
    }
129
130
    /**
131
     * If it's a new client, we need to make some special actions named the handshake.
132
     *
133
     * @param string $data
134
     */
135 7
    protected function processHandshake(string $data)
136
    {
137 7
        if ($this->handshakeDone) {
138
            return;
139
        }
140
141 7
        $request = Request::create($data);
142 7
        $this->handshake->verify($request);
143 7
        $this->uri = $request->getUri();
144 7
        $response = Response::createSwitchProtocolResponse();
145 7
        $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...
146 7
        $response->send($this->stream);
147
148 7
        $this->handshakeDone = true;
149 7
        $this->getHandler()->onConnection($this);
150 6
    }
151
152
    /**
153
     * @return string
154
     */
155 5
    public function getIp()
156
    {
157 5
        return $this->stream->getRemoteAddress();
158
    }
159
}
160