Completed
Push — master ( 7c9e4e...388b15 )
by Arthur
02:59
created

Connection::__construct()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 4

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 4
rs 10
c 0
b 0
f 0
cc 1
nc 1
nop 1
1
<?php
2
3
namespace WSSC\Components;
4
5
use WSSC\Contracts\CommonsContract;
6
use WSSC\Contracts\ConnectionContract;
7
use WSSC\Contracts\WebSocketServerContract;
8
9
class Connection implements ConnectionContract, CommonsContract
10
{
11
12
    private $socketConnection;
13
14
    public function __construct($sockConn)
15
    {
16
        $this->socketConnection = $sockConn;
17
    }
18
19
    /**
20
     * Closes clients socket stream
21
     */
22
    public function close()
23
    {
24
        if (is_resource($this->socketConnection)) {
25
            fclose($this->socketConnection);
26
        }
27
    }
28
29
    /**
30
     * This method is invoked when user implementation call $conn->send($data)
31
     * writes data to the clients stream socket
32
     *
33
     * @param string $data pure decoded data from server
34
     * @throws \Exception
35
     */
36
    public function send($data)
37
    {
38
        fwrite($this->socketConnection, $this->encode($data));
39
    }
40
41
    /**
42
     * Encodes data before writing to the client socket stream
43
     *
44
     * @param string $payload
45
     * @param string $type
46
     * @param boolean $masked
47
     * @return mixed
48
     * @throws \Exception
49
     */
50
    private function encode($payload, string $type = self::EVENT_TYPE_TEXT, bool $masked = false)
51
    {
52
        $frameHead = [];
53
        $payloadLength = strlen($payload);
54
55
        switch ($type) {
56
            case self::EVENT_TYPE_TEXT:
57
                // first byte indicates FIN, Text-Frame (10000001):
58
                $frameHead[0] = self::ENCODE_TEXT;
59
                break;
60
61
            case self::EVENT_TYPE_CLOSE:
62
                // first byte indicates FIN, Close Frame(10001000):
63
                $frameHead[0] = self::ENCODE_CLOSE;
64
                break;
65
66
            case self::EVENT_TYPE_PING:
67
                // first byte indicates FIN, Ping frame (10001001):
68
                $frameHead[0] = self::ENCODE_PING;
69
                break;
70
71
            case self::EVENT_TYPE_PONG:
72
                // first byte indicates FIN, Pong frame (10001010):
73
                $frameHead[0] = self::ENCODE_PONG;
74
                break;
75
        }
76
77
        // set mask and payload length (using 1, 3 or 9 bytes)
78
        if ($payloadLength > self::PAYLOAD_MAX_BITS) {
79
            $payloadLengthBin = str_split(sprintf('%064b', $payloadLength), self::PAYLOAD_CHUNK);
80
            $frameHead[1] = ($masked === true) ? self::MASK_255 : self::MASK_127;
81
            for ($i = 0; $i < 8; $i++) {
82
                $frameHead[$i + 2] = bindec($payloadLengthBin[$i]);
83
            }
84
            // most significant bit MUST be 0
85
            if ($frameHead[2] > self::MASK_127) {
86
                return ['type' => $type, 'payload' => $payload, 'error' => WebSocketServerContract::ERR_FRAME_TOO_LARGE];
87
            }
88
        } elseif ($payloadLength > self::MASK_125) {
89
            $payloadLengthBin = str_split(sprintf('%016b', $payloadLength), self::PAYLOAD_CHUNK);
90
            $frameHead[1] = ($masked === true) ? self::MASK_254 : self::MASK_126;
91
            $frameHead[2] = bindec($payloadLengthBin[0]);
92
            $frameHead[3] = bindec($payloadLengthBin[1]);
93
        } else {
94
            $frameHead[1] = ($masked === true) ? $payloadLength + self::MASK_128 : $payloadLength;
95
        }
96
97
        return $this->getComposedFrame($frameHead, $payload, $payloadLength, $masked);
98
    }
99
100
    private function getComposedFrame(array $frameHead, string $payload, int $payloadLength, bool $masked)
101
    {
102
        // convert frame-head to string:
103
        foreach (array_keys($frameHead) as $i) {
104
            $frameHead[$i] = chr($frameHead[$i]);
105
        }
106
        // generate a random mask:
107
        $mask = [];
108
        if ($masked === true) {
109 View Code Duplication
            for ($i = 0; $i < 4; $i++) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
110
                $mask[$i] = chr(random_int(0, self::MASK_255));
111
            }
112
113
            $frameHead = array_merge($frameHead, $mask);
114
        }
115
        $frame = implode('', $frameHead);
116
117
        // append payload to frame:
118 View Code Duplication
        for ($i = 0; $i < $payloadLength; $i++) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
119
            $frame .= ($masked === true) ? $payload[$i] ^ $mask[$i % 4] : $payload[$i];
120
        }
121
122
        return $frame;
123
    }
124
125
}
126