Connection   A
last analyzed

Complexity

Total Complexity 41

Size/Duplication

Total Lines 291
Duplicated Lines 9.97 %

Coupling/Cohesion

Components 1
Dependencies 4

Importance

Changes 0
Metric Value
dl 29
loc 291
rs 9.1199
c 0
b 0
f 0
wmc 41
lcom 1
cbo 4

5 Methods

Rating   Name   Duplication   Size   Complexity  
B onRead() 8 25 6
F onUdpPacket() 21 126 26
A getMessageByRcode() 0 8 2
B get() 0 47 6
A onFinish() 0 5 1

How to fix   Duplicated Code    Complexity   

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:

Complex Class

 Tip:   Before tackling complexity, make sure that you eliminate any duplication first. This often can reduce the size of classes significantly.

Complex classes like Connection often do a lot of different things. To break such a class down, we need to identify a cohesive component within that class. A common approach to find such a component is to look for fields/methods that share the same prefixes, or suffixes. You can also have a look at the cohesion graph to spot any un-connected, or weakly-connected components.

Once you have determined the fields that belong together, you can apply the Extract Class refactoring. If the component makes sense as a sub-class, Extract Subclass is also a candidate, and is often faster.

While breaking up the class, it is a good idea to analyze how other classes use Connection, and based on these observations, apply Extract Interface, too.

1
<?php
2
namespace PHPDaemon\Clients\DNS;
3
4
use PHPDaemon\Network\ClientConnection;
5
use PHPDaemon\Utils\Binary;
6
7
/**
8
 * @package    NetworkClients
9
 * @subpackage DNSClient
10
 * @author     Vasily Zorin <[email protected]>
11
 */
12
class Connection extends ClientConnection
13
{
14
    /**
15
     * @TODO DESCR
16
     */
17
    const STATE_PACKET = 1;
18
    /**
19
     * @var array Response
20
     */
21
    public $response = [];
22
    /**
23
     * @var integer Sequence
24
     */
25
    protected $seq = 0;
26
    /**
27
     * @var boolean Current packet size
28
     */
29
    protected $pctSize = 0;
30
31
    /**
32
     * @var integer Default low mark. Minimum number of bytes in buffer.
33
     */
34
    protected $lowMark = 2;
35
36
    /**
37
     * @var integer Default high mark. Maximum number of bytes in buffer.
38
     */
39
    protected $highMark = 512;
40
41
    protected $rcodeMessages = [
42
        0 => 'Success',
43
        1 => 'Format Error',
44
        2 => 'Server Failure',
45
        3 => 'Non-Existent Domain',
46
        4 => 'Not Implemented',
47
        5 => 'Query Refused',
48
        6 => 'Name Exists when it should not',
49
        7 => 'RR Set Exists when it should not',
50
        8 => 'RR Set that should exist does not',
51
        9 => 'Not Authorized',
52
        10 => 'Name not contained in zone',
53
        16 => 'TSIG Signature Failure',
54
        17 => 'Key not recognized',
55
        18 => 'Signature out of time window',
56
        19 => 'Bad TKEY Mode',
57
        20 => 'Duplicate key name',
58
        21 => 'Algorithm not supported',
59
        22 => 'Bad Truncation',
60
        23 => 'Bad/missing server cookie'
61
    ];
62
63
    /**
64
     * Called when new data received
65
     * @return void
66
     */
67
    public function onRead()
68
    {
69
        start:
70
        if ($this->type === 'udp') {
71
            $this->onUdpPacket($this->read($this->getInputLength()));
0 ignored issues
show
Security Bug introduced by
It seems like $this->read($this->getInputLength()) targeting PHPDaemon\Network\IOStream::read() can also be of type false; however, PHPDaemon\Clients\DNS\Connection::onUdpPacket() does only seem to accept string, did you maybe forget to handle an error condition?
Loading history...
72
            return;
73
        }
74
        if ($this->state === self::STATE_ROOT) {
75
            if (false === ($hdr = $this->readExact(2))) {
76
                return; // not enough data
77
            }
78
            $this->pctSize = Binary::bytes2int($hdr);
0 ignored issues
show
Documentation Bug introduced by
It seems like \PHPDaemon\Utils\Binary::bytes2int($hdr) of type integer or double is incompatible with the declared type boolean of property $pctSize.

Our type inference engine has found an assignment to a property that is incompatible with the declared type of that property.

Either this assignment is in error or the assigned type should be added to the documentation/type hint for that property..

Loading history...
79
            $this->setWatermark($this->pctSize);
80
            $this->state = self::STATE_PACKET;
81
        }
82 View Code Duplication
        if ($this->state === self::STATE_PACKET) {
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...
83
            if (false === ($pct = $this->readExact($this->pctSize))) {
0 ignored issues
show
Bug introduced by
It seems like $this->pctSize can also be of type boolean or double; however, PHPDaemon\Network\IOStream::readExact() does only seem to accept integer, maybe add an additional type check?

If a method or function can return multiple different values and unless you are sure that you only can receive a single value in this context, we recommend to add an additional type check:

/**
 * @return array|string
 */
function returnsDifferentValues($x) {
    if ($x) {
        return 'foo';
    }

    return array();
}

$x = returnsDifferentValues($y);
if (is_array($x)) {
    // $x is an array.
}

If this a common case that PHP Analyzer should handle natively, please let us know by opening an issue.

Loading history...
84
                return; // not enough data
85
            }
86
            $this->state = self::STATE_ROOT;
87
            $this->setWatermark(2);
88
            $this->onUdpPacket($pct);
89
        }
90
        goto start;
91
    }
92
93
    /**
94
     * Called when new UDP packet received.
95
     * @param  string $pct
96
     * @return void
97
     */
98
    public function onUdpPacket($pct)
99
    {
100
        if (mb_orig_strlen($pct) < 10) {
101
            return;
102
        }
103
        $orig = $pct;
104
        $this->response = [];
105
        Binary::getWord($pct); // ID
106
        $bitmap = Binary::getBitmap(Binary::getByte($pct)) . Binary::getBitmap(Binary::getByte($pct));
107
        //$qr = (int) $bitmap[0];
108
        $opcode = bindec(substr($bitmap, 1, 4));
0 ignored issues
show
Unused Code introduced by
$opcode is not used, you could remove the assignment.

This check looks for variable assignements that are either overwritten by other assignments or where the variable is not used subsequently.

$myVar = 'Value';
$higher = false;

if (rand(1, 6) > 3) {
    $higher = true;
} else {
    $higher = false;
}

Both the $myVar assignment in line 1 and the $higher assignment in line 2 are dead. The first because $myVar is never used and the second because $higher is always overwritten for every possible time line.

Loading history...
109
        //$aa = (int) $bitmap[5];
110
        //$tc = (int) $bitmap[6];
111
        //$rd = (int) $bitmap[7];
112
        //$ra = (int) $bitmap[8];
113
        //$z = bindec(substr($bitmap, 9, 3));
114
        $rcode = bindec(mb_orig_substr($bitmap, 12));
115
        $this->response['status'] = [
116
            'rcode' => $rcode,
117
            'msg' => $this->getMessageByRcode($rcode)
118
        ];
119
        $qdcount = Binary::getWord($pct);
120
        $ancount = Binary::getWord($pct);
121
        $nscount = Binary::getWord($pct);
122
        $arcount = Binary::getWord($pct);
123
        for ($i = 0; $i < $qdcount; ++$i) {
124
            $name = Binary::parseLabels($pct, $orig);
125
            $typeInt = Binary::getWord($pct);
126
            $type = isset(Pool::$type[$typeInt]) ? Pool::$type[$typeInt] : 'UNK(' . $typeInt . ')';
127
            $classInt = Binary::getWord($pct);
128
            $class = isset(Pool::$class[$classInt]) ? Pool::$class[$classInt] : 'UNK(' . $classInt . ')';
129
            if (!isset($this->response[$type])) {
130
                $this->response[$type] = [];
131
            }
132
            $record = [
133
                'name' => $name,
134
                'type' => $type,
135
                'class' => $class,
136
            ];
137
            $this->response['query'][] = $record;
138
        }
139
        $getResRecord = function (&$pct) use ($orig) {
140
            $name = Binary::parseLabels($pct, $orig);
141
            $typeInt = Binary::getWord($pct);
142
            $type = isset(Pool::$type[$typeInt]) ? Pool::$type[$typeInt] : 'UNK(' . $typeInt . ')';
143
            $classInt = Binary::getWord($pct);
144
            $class = isset(Pool::$class[$classInt]) ? Pool::$class[$classInt] : 'UNK(' . $classInt . ')';
145
            $ttl = Binary::getDWord($pct);
146
            $length = Binary::getWord($pct);
147
            $data = mb_orig_substr($pct, 0, $length);
148
            $pct = mb_orig_substr($pct, $length);
149
150
            $record = [
151
                'name' => $name,
152
                'type' => $type,
153
                'class' => $class,
154
                'ttl' => $ttl,
155
            ];
156
157
            if (($type === 'A') || ($type === 'AAAA')) {
158
                if ($data === "\x00") {
159
                    $record['ip'] = false;
160
                    $record['ttl'] = 5;
161
                } else {
162
                    $record['ip'] = inet_ntop($data);
163
                }
164
            } elseif ($type === 'NS') {
165
                $record['ns'] = Binary::parseLabels($data, $orig);
166
            } elseif ($type === 'CNAME') {
167
                $record['cname'] = Binary::parseLabels($data, $orig);
168
            } elseif ($type === 'SOA') {
169
                $record['mname'] = Binary::parseLabels($data, $orig);
170
                $record['rname'] = Binary::parseLabels($data, $orig);
171
                $record['serial'] = Binary::getDWord($data);
172
                $record['refresh'] = Binary::getDWord($data);
173
                $record['retry'] = Binary::getDWord($data);
174
                $record['expire'] = Binary::getDWord($data);
175
                $record['nx'] = Binary::getDWord($data);
176
            } elseif ($type === 'MX') {
177
                $record['preference'] = Binary::getWord($data);
178
                $record['exchange'] = Binary::parseLabels($data, $orig);
179
            } elseif ($type === 'TXT') {
180
                $record['text'] = '';
181
                $lastLength = -1;
182
                while (($length = mb_orig_strlen($data)) > 0 && ($length !== $lastLength)) {
183
                    $record['text'] .= Binary::parseLabels($data, $orig);
184
                    $lastLength = $length;
185
                }
186
            } elseif ($type === 'SRV') {
187
                $record['priority'] = Binary::getWord($data);
188
                $record['weight'] = Binary::getWord($data);
189
                $record['port'] = Binary::getWord($data);
190
                $record['target'] = Binary::parseLabels($data, $orig);
191
            }
192
193
            return $record;
194
        };
195 View Code Duplication
        for ($i = 0; $i < $ancount; ++$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...
196
            $record = $getResRecord($pct);
197
            if (!isset($this->response[$record['type']])) {
198
                $this->response[$record['type']] = [];
199
            }
200
            $this->response[$record['type']][] = $record;
201
        }
202 View Code Duplication
        for ($i = 0; $i < $nscount; ++$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...
203
            $record = $getResRecord($pct);
204
            if (!isset($this->response[$record['type']])) {
205
                $this->response[$record['type']] = [];
206
            }
207
            $this->response[$record['type']][] = $record;
208
        }
209 View Code Duplication
        for ($i = 0; $i < $arcount; ++$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...
210
            $record = $getResRecord($pct);
211
            if (!isset($this->response[$record['type']])) {
212
                $this->response[$record['type']] = [];
213
            }
214
            $this->response[$record['type']][] = $record;
215
        }
216
        $this->onResponse->executeOne($this->response);
217
        if (!$this->keepalive) {
218
            $this->finish();
219
            return;
220
        } else {
221
            $this->checkFree();
222
        }
223
    }
224
225
    /**
226
     * @param  int $rcode
227
     * @return string
228
     */
229
    protected function getMessageByRcode($rcode)
230
    {
231
        if (isset($this->rcodeMessages[$rcode])) {
232
            return $this->rcodeMessages[$rcode];
233
        } else {
234
            return 'UNKNOWN ERROR';
235
        }
236
    }
237
238
    /**
239
     * Gets the host information
240
     * @param  string $hostname Hostname
241
     * @param  callable $cb Callback
242
     * @callback $cb ( )
243
     * @return void
244
     */
245
    public function get($hostname, $cb)
246
    {
247
        $this->onResponse->push($cb);
248
        $this->setFree(false);
249
        $e = explode(':', $hostname, 3);
250
        $hostname = $e[0];
251
        $qtype = isset($e[1]) ? $e[1] : 'A';
252
        $qclass = isset($e[2]) ? $e[2] : 'IN';
253
        $QD = [];
254
        $qtypeInt = array_search($qtype, Pool::$type, true);
255
        $qclassInt = array_search($qclass, Pool::$class, true);
256
257
        if (($qtypeInt === false) || ($qclassInt === false)) {
258
            $cb(false);
259
            return;
260
        }
261
262
        $q = Binary::labels($hostname) . // domain
263
            Binary::word($qtypeInt) .
264
            Binary::word($qclassInt);
265
266
        $QD[] = $q;
267
268
        $packet = Binary::word(++$this->seq) . // Query ID
269
            Binary::bitmap2bytes(
270
                '0' . // QR = 0
271
                '0000' . // OPCODE = 0000 (standard query)
272
                '0' . // AA = 0
273
                '0' . // TC = 0
274
                '1' . // RD = 1
275
                '0' . // RA = 0,
276
                '000' . // reserved
277
                '0000', // RCODE
278
                2
279
            ) .
280
            Binary::word(sizeof($QD)) . // QDCOUNT
281
            Binary::word(0) . // ANCOUNT
282
            Binary::word(0) . // NSCOUNT
283
            Binary::word(0) . // ARCOUNT
284
            implode('', $QD);
285
286
        if ($this->type === 'udp') {
287
            $this->write($packet);
288
        } else {
289
            $this->write(Binary::word(mb_orig_strlen($packet)) . $packet);
290
        }
291
    }
292
293
    /**
294
     * Called when connection finishes
295
     * @return void
296
     */
297
    public function onFinish()
298
    {
299
        $this->onResponse->executeAll(false);
300
        parent::onFinish();
301
    }
302
}
303