Completed
Push — master ( 618340...370d15 )
by Arthur
01:45
created

Connection::getPeerName()   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
85
            for ($i = 0; $i < 8; $i++) {
86
                $frameHead[$i + 2] = bindec($payloadLengthBin[$i]);
87
            }
88
89
            // most significant bit MUST be 0
90
            if ($frameHead[2] > self::MASK_127) {
91
                return [
92
                    'type'    => $type,
93
                    'payload' => $payload,
94
                    'error'   => WebSocketServerContract::ERR_FRAME_TOO_LARGE,
95
                ];
96
            }
97
        } elseif ($payloadLength > self::MASK_125) {
98
            $payloadLengthBin = str_split(sprintf('%016b', $payloadLength), self::PAYLOAD_CHUNK);
99
            $frameHead[1] = ($masked === true) ? self::MASK_254 : self::MASK_126;
100
            $frameHead[2] = bindec($payloadLengthBin[0]);
101
            $frameHead[3] = bindec($payloadLengthBin[1]);
102
        } else {
103
            $frameHead[1] = ($masked === true) ? $payloadLength + self::MASK_128 : $payloadLength;
104
        }
105
106
        return $this->getComposedFrame($frameHead, $payload, $payloadLength, $masked);
107
    }
108
109
    private function getComposedFrame(array $frameHead, string $payload, int $payloadLength, bool $masked)
110
    {
111
        // convert frame-head to string:
112
        foreach (array_keys($frameHead) as $i) {
113
            $frameHead[$i] = chr($frameHead[$i]);
114
        }
115
116
        // generate a random mask:
117
        $mask = [];
118
        if ($masked === true) {
119 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...
120
                $mask[$i] = chr(random_int(0, self::MASK_255));
121
            }
122
123
            $frameHead = array_merge($frameHead, $mask);
124
        }
125
        $frame = implode('', $frameHead);
126
127
        // append payload to frame:
128 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...
129
            $frame .= ($masked === true) ? $payload[$i] ^ $mask[$i % 4] : $payload[$i];
130
        }
131
132
        return $frame;
133
    }
134
135
    /**
136
     * Gets unique socket id from resource
137
     *
138
     * @return int
139
     */
140
    public function getUniqueSocketId(): int
141
    {
142
        return (int)$this->socketConnection;
143
    }
144
145
    /**
146
     *  Gets client socket address host/port or UNIX path
147
     *
148
     * @return string
149
     */
150
    public function getPeerName(): string
151
    {
152
        return stream_socket_get_name($this->socketConnection, true);
153
    }
154
}
155