WebSocketProtocol::handshake()   A
last analyzed

Complexity

Conditions 2
Paths 2

Size

Total Lines 8
Code Lines 5

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 8
rs 9.4285
c 0
b 0
f 0
cc 2
eloc 5
nc 2
nop 1
1
<?php
2
namespace Fructify\Reload\Protocol;
3
4
use Fructify\Reload\Application\ServerApplication;
5
use React\Socket\Connection as SocketConnection;
6
use Symfony\Component\HttpFoundation;
7
use Fructify\Reload\Response\Response;
8
use Symfony\Component\Console\Output\OutputInterface;
9
10
class WebSocketProtocol
11
{
12
    protected $websocket;
13
    protected $conn;
14
    protected $app;
15
16
    public function __construct(SocketConnection $conn, ServerApplication $app, HttpFoundation\Request $request)
17
    {
18
        $this->app = $app;
19
        $this->conn = $conn;
20
        $this->initEvent();
21
        $this->handshake($request);
22
        $this->app->getOutput()->writeln(strftime('%T')." - info - Browser connected", OutputInterface::VERBOSITY_VERBOSE);
23
        new LivereloadProtocol($conn, $app);
24
    }
25
26
    protected function handshake(HttpFoundation\Request $request)
27
    {
28
        if (!($handshakeResponse = $this->websocket->handshake($request))) {
29
            $this->conn->write(new Response('bad protocol', 400), true);
0 ignored issues
show
Unused Code introduced by
The call to Connection::write() has too many arguments starting with true.

This check compares calls to functions or methods with their respective definitions. If the call has more arguments than are defined, it raises an issue.

If a function is defined several times with a different number of parameters, the check may pick up the wrong definition and report false positives. One codebase where this has been known to happen is Wordpress.

In this case you can add the @ignore PhpDoc annotation to the duplicate definition and it will be ignored.

Loading history...
30
            return;
31
        }
32
        $this->conn->write($handshakeResponse);
33
    }
34
35
    protected function initEvent()
36
    {
37
        $this->websocket = new WebSocket\WebSocket();
38
        $this->conn->on('data', function($data){
39
            $this->onData($data);
40
        });
41
    }
42
43
    protected function onData($data)
44
    {
45
        $frame = $this->websocket->onMessage($data);
46
        if(!($frame instanceof WebSocket\Frame)) {
47
            return;
48
        }
49
        if(($command = json_decode($frame->getData(), true)) === null){
50
            return;
51
        }
52
        $this->conn->emit('command', array($command));
53
    }
54
}
55