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

Connection   A

Complexity

Total Complexity 23

Size/Duplication

Total Lines 132
Duplicated Lines 4.55 %

Coupling/Cohesion

Components 1
Dependencies 0

Importance

Changes 0
Metric Value
wmc 23
lcom 1
cbo 0
dl 6
loc 132
rs 10
c 0
b 0
f 0

6 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 4 1
A close() 0 7 2
A send() 0 4 1
C encode() 0 52 12
B getComposedFrame() 6 24 6
A getUniqueSocketId() 0 4 1

How to fix   Duplicated Code   

Duplicated Code

Duplicate code is one of the most pungent code smells. A rule that is often used is to re-structure code once it is duplicated in three or more places.

Common duplication problems, and corresponding solutions are:

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