Completed
Push — master ( 1dbcfc...df021a )
by Arthur
02:20
created

Connection::getUniqueSocketId()   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 0
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
     * @throws \Exception
23
     */
24
    public function close()
25
    {
26
        if (is_resource($this->socketConnection)) {
27
            fwrite($this->socketConnection, $this->encode('', self::EVENT_TYPE_CLOSE));
28
            fclose($this->socketConnection);
29
        }
30
    }
31
32
    /**
33
     * This method is invoked when user implementation call $conn->send($data)
34
     * writes data to the clients stream socket
35
     *
36
     * @param string $data pure decoded data from server
37
     * @throws \Exception
38
     */
39
    public function send($data)
40
    {
41
        fwrite($this->socketConnection, $this->encode($data));
42
    }
43
44
    /**
45
     * Encodes data before writing to the client socket stream
46
     *
47
     * @param string $payload
48
     * @param string $type
49
     * @param boolean $masked
50
     * @return mixed
51
     * @throws \Exception
52
     */
53
    private function encode($payload, string $type = self::EVENT_TYPE_TEXT, bool $masked = false)
54
    {
55
        $frameHead = [];
56
        $payloadLength = strlen($payload);
57
58
        switch ($type) {
59
            case self::EVENT_TYPE_TEXT:
60
                // first byte indicates FIN, Text-Frame (10000001):
61
                $frameHead[0] = self::ENCODE_TEXT;
62
                break;
63
64
            case self::EVENT_TYPE_CLOSE:
65
                // first byte indicates FIN, Close Frame(10001000):
66
                $frameHead[0] = self::ENCODE_CLOSE;
67
                break;
68
69
            case self::EVENT_TYPE_PING:
70
                // first byte indicates FIN, Ping frame (10001001):
71
                $frameHead[0] = self::ENCODE_PING;
72
                break;
73
74
            case self::EVENT_TYPE_PONG:
75
                // first byte indicates FIN, Pong frame (10001010):
76
                $frameHead[0] = self::ENCODE_PONG;
77
                break;
78
        }
79
80
        // set mask and payload length (using 1, 3 or 9 bytes)
81
        if ($payloadLength > self::PAYLOAD_MAX_BITS) {
82
            $payloadLengthBin = str_split(sprintf('%064b', $payloadLength), self::PAYLOAD_CHUNK);
83
            $frameHead[1] = ($masked === true) ? self::MASK_255 : self::MASK_127;
84
            for ($i = 0; $i < 8; $i++) {
85
                $frameHead[$i + 2] = bindec($payloadLengthBin[$i]);
86
            }
87
            // most significant bit MUST be 0
88
            if ($frameHead[2] > self::MASK_127) {
89
                return ['type'    => $type,
90
                        'payload' => $payload,
91
                        'error'   => WebSocketServerContract::ERR_FRAME_TOO_LARGE,
92
                ];
93
            }
94
        } elseif ($payloadLength > self::MASK_125) {
95
            $payloadLengthBin = str_split(sprintf('%016b', $payloadLength), self::PAYLOAD_CHUNK);
96
            $frameHead[1] = ($masked === true) ? self::MASK_254 : self::MASK_126;
97
            $frameHead[2] = bindec($payloadLengthBin[0]);
98
            $frameHead[3] = bindec($payloadLengthBin[1]);
99
        } else {
100
            $frameHead[1] = ($masked === true) ? $payloadLength + self::MASK_128 : $payloadLength;
101
        }
102
103
        return $this->getComposedFrame($frameHead, $payload, $payloadLength, $masked);
104
    }
105
106
    private function getComposedFrame(array $frameHead, string $payload, int $payloadLength, bool $masked)
107
    {
108
        // convert frame-head to string:
109
        foreach (array_keys($frameHead) as $i) {
110
            $frameHead[$i] = chr($frameHead[$i]);
111
        }
112
        // generate a random mask:
113
        $mask = [];
114
        if ($masked === true) {
115 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...
116
                $mask[$i] = chr(random_int(0, self::MASK_255));
117
            }
118
119
            $frameHead = array_merge($frameHead, $mask);
120
        }
121
        $frame = implode('', $frameHead);
122
123
        // append payload to frame:
124 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...
125
            $frame .= ($masked === true) ? $payload[$i] ^ $mask[$i % 4] : $payload[$i];
126
        }
127
128
        return $frame;
129
    }
130
131
    /**
132
     * Gets unique socket id from resource
133
     *
134
     * @return int
135
     */
136
    public function getUniqueSocketId(): int
137
    {
138
        return (int)$this->socketConnection;
139
    }
140
}
141