Completed
Pull Request — master (#235)
by
unknown
04:22
created

Connection   B

Complexity

Total Complexity 40

Size/Duplication

Total Lines 297
Duplicated Lines 12.79 %

Coupling/Cohesion

Components 1
Dependencies 4

Importance

Changes 3
Bugs 2 Features 0
Metric Value
c 3
b 2
f 0
dl 38
loc 297
rs 8.2608
wmc 40
lcom 1
cbo 4

5 Methods

Rating   Name   Duplication   Size   Complexity  
A getMessageByRcode() 0 7 2
F onUdpPacket() 21 127 25
B onRead() 17 26 6
B get() 0 43 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\Clients\DNS\Pool;
5
use PHPDaemon\Network\ClientConnection;
6
use PHPDaemon\Utils\Binary;
7
use PHPDaemon\Core\Daemon;
8
use PHPDaemon\Core\Debug;
9
10
/**
11
 * @package    NetworkClients
12
 * @subpackage DNSClient
13
 * @author     Vasily Zorin <[email protected]>
14
 */
15
class Connection extends ClientConnection
16
{
17
    
18
    /**
19
     * @TODO DESCR
0 ignored issues
show
Coding Style introduced by
Comment refers to a TODO task

This check looks TODO comments that have been left in the code.

``TODO``s show that something is left unfinished and should be attended to.

Loading history...
20
     */
21
    const STATE_PACKET = 1;
22
23
    /**
24
     * @var integer Sequence
25
     */
26
    protected $seq = 0;
27
28
    /**
29
     * @var boolean Keepalive?
30
     */
31
    protected $keepalive = false;
32
33
    /**
34
     * @var array Response
35
     */
36
    public $response = [];
37
38
    /**
39
     * @var boolean Current packet size
40
     */
41
    protected $pctSize = 0;
42
43
    /**
44
     * @var integer Default low mark. Minimum number of bytes in buffer.
45
     */
46
    protected $lowMark = 2;
47
48
    /**
49
     * @var integer Default high mark. Maximum number of bytes in buffer.
50
     */
51
    protected $highMark = 512;
52
53
    private $rcodeMessages = [
54
        0       => 'Success',
55
        1       => 'Format Error',
56
        2       => 'Server Failure',
57
        3       => 'Non-Existent Domain',
58
        4       => 'Not Implemented',
59
        5       => 'Query Refused',
60
        6       => 'Name Exists when it should not',
61
        7       => 'RR Set Exists when it should not',
62
        8       => 'RR Set that should exist does not',
63
        9       => 'Not Authorized',
64
        10      => 'Name not contained in zone',
65
        16      => 'TSIG Signature Failure',
66
        17      => 'Key not recognized',
67
        18      => 'Signature out of time window',
68
        19      => 'Bad TKEY Mode', 
69
        20      => 'Duplicate key name',
70
        21      => 'Algorithm not supported',
71
        22      => 'Bad Truncation',
72
        23      => 'Bad/missing server cookie'
73
    ];
74
    
75
    /**
76
     * @param  int $rcode
77
     * @return string
78
     */
79
    private function getMessageByRcode($rcode){
80
        if(!empty($this->rcodeMessages[$rcode])){
81
            return $this->rcodeMessages[$rcode];
82
        }else{
83
            return 'UNKNOWN ERROR';
84
        }
85
    }
86
    
87
    /**
88
     * Called when new UDP packet received.
89
     * @param  string $pct
90
     * @return void
91
     */
92
    public function onUdpPacket($pct)
93
    {
94
        if(strlen($pct) < 10){
95
            return;
96
        }
97
        $orig           = $pct;
98
        $this->response = [];
99
        /*$id = */
100
        Binary::getWord($pct);
101
        $bitmap = Binary::getBitmap(Binary::getByte($pct)) . Binary::getBitmap(Binary::getByte($pct));
102
        //$qr = (int) $bitmap[0];
0 ignored issues
show
Unused Code Comprehensibility introduced by
64% of this comment could be valid code. Did you maybe forget this after debugging?

Sometimes obsolete code just ends up commented out instead of removed. In this case it is better to remove the code once you have checked you do not need it.

The code might also have been commented out for debugging purposes. In this case it is vital that someone uncomments it again or your project may behave in very unexpected ways in production.

This check looks for comments that seem to be mostly valid code and reports them.

Loading history...
103
        $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...
104
        //$aa = (int) $bitmap[5];
0 ignored issues
show
Unused Code Comprehensibility introduced by
64% of this comment could be valid code. Did you maybe forget this after debugging?

Sometimes obsolete code just ends up commented out instead of removed. In this case it is better to remove the code once you have checked you do not need it.

The code might also have been commented out for debugging purposes. In this case it is vital that someone uncomments it again or your project may behave in very unexpected ways in production.

This check looks for comments that seem to be mostly valid code and reports them.

Loading history...
105
        //$tc = (int) $bitmap[6];
0 ignored issues
show
Unused Code Comprehensibility introduced by
64% of this comment could be valid code. Did you maybe forget this after debugging?

Sometimes obsolete code just ends up commented out instead of removed. In this case it is better to remove the code once you have checked you do not need it.

The code might also have been commented out for debugging purposes. In this case it is vital that someone uncomments it again or your project may behave in very unexpected ways in production.

This check looks for comments that seem to be mostly valid code and reports them.

Loading history...
106
        //$rd = (int) $bitmap[7];
0 ignored issues
show
Unused Code Comprehensibility introduced by
64% of this comment could be valid code. Did you maybe forget this after debugging?

Sometimes obsolete code just ends up commented out instead of removed. In this case it is better to remove the code once you have checked you do not need it.

The code might also have been commented out for debugging purposes. In this case it is vital that someone uncomments it again or your project may behave in very unexpected ways in production.

This check looks for comments that seem to be mostly valid code and reports them.

Loading history...
107
        //$ra = (int) $bitmap[8];
0 ignored issues
show
Unused Code Comprehensibility introduced by
64% of this comment could be valid code. Did you maybe forget this after debugging?

Sometimes obsolete code just ends up commented out instead of removed. In this case it is better to remove the code once you have checked you do not need it.

The code might also have been commented out for debugging purposes. In this case it is vital that someone uncomments it again or your project may behave in very unexpected ways in production.

This check looks for comments that seem to be mostly valid code and reports them.

Loading history...
108
        //$z = bindec(substr($bitmap, 9, 3));
0 ignored issues
show
Unused Code Comprehensibility introduced by
62% of this comment could be valid code. Did you maybe forget this after debugging?

Sometimes obsolete code just ends up commented out instead of removed. In this case it is better to remove the code once you have checked you do not need it.

The code might also have been commented out for debugging purposes. In this case it is vital that someone uncomments it again or your project may behave in very unexpected ways in production.

This check looks for comments that seem to be mostly valid code and reports them.

Loading history...
109
        $rcode = bindec(substr($bitmap, 12));
110
        $this->response['status'] = [
111
            'rcode' => $rcode,
112
            'msg'   => $this->getMessageByRcode($rcode)
113
        ];
114
        $qdcount = Binary::getWord($pct);
115
        $ancount = Binary::getWord($pct);
116
        $nscount = Binary::getWord($pct);
117
        $arcount = Binary::getWord($pct);
118
        for ($i = 0; $i < $qdcount; ++$i) {
119
            $name     = Binary::parseLabels($pct, $orig);
120
            $typeInt  = Binary::getWord($pct);
121
            $type     = isset(Pool::$type[$typeInt]) ? Pool::$type[$typeInt] : 'UNK(' . $typeInt . ')';
122
            $classInt = Binary::getWord($pct);
123
            $class    = isset(Pool::$class[$classInt]) ? Pool::$class[$classInt] : 'UNK(' . $classInt . ')';
124
            if (!isset($this->response[$type])) {
125
                $this->response[$type] = [];
126
            }
127
            $record                    = [
128
                'name'  => $name,
129
                'type'  => $type,
130
                'class' => $class,
131
            ];
132
            $this->response['query'][] = $record;
133
        }
134
        $getResRecord = function (&$pct) use ($orig) {
135
            $name     = Binary::parseLabels($pct, $orig);
136
            $typeInt  = Binary::getWord($pct);
137
            $type     = isset(Pool::$type[$typeInt]) ? Pool::$type[$typeInt] : 'UNK(' . $typeInt . ')';
138
            $classInt = Binary::getWord($pct);
139
            $class    = isset(Pool::$class[$classInt]) ? Pool::$class[$classInt] : 'UNK(' . $classInt . ')';
140
            $ttl      = Binary::getDWord($pct);
141
            $length   = Binary::getWord($pct);
142
            $data     = mb_orig_substr($pct, 0, $length);
143
            $pct      = mb_orig_substr($pct, $length);
144
145
            $record = [
146
                'name'  => $name,
147
                'type'  => $type,
148
                'class' => $class,
149
                'ttl'   => $ttl,
150
            ];
151
152
            if (($type === 'A') OR ($type === 'AAAA')) {
0 ignored issues
show
Comprehensibility Best Practice introduced by
Using logical operators such as or instead of || is generally not recommended.

PHP has two types of connecting operators (logical operators, and boolean operators):

  Logical Operators Boolean Operator
AND - meaning and &&
OR - meaning or ||

The difference between these is the order in which they are executed. In most cases, you would want to use a boolean operator like &&, or ||.

Let’s take a look at a few examples:

// Logical operators have lower precedence:
$f = false or true;

// is executed like this:
($f = false) or true;


// Boolean operators have higher precedence:
$f = false || true;

// is executed like this:
$f = (false || true);

Logical Operators are used for Control-Flow

One case where you explicitly want to use logical operators is for control-flow such as this:

$x === 5
    or die('$x must be 5.');

// Instead of
if ($x !== 5) {
    die('$x must be 5.');
}

Since die introduces problems of its own, f.e. it makes our code hardly testable, and prevents any kind of more sophisticated error handling; you probably do not want to use this in real-world code. Unfortunately, logical operators cannot be combined with throw at this point:

// The following is currently a parse error.
$x === 5
    or throw new RuntimeException('$x must be 5.');

These limitations lead to logical operators rarely being of use in current PHP code.

Loading history...
153
                if ($data === "\x00") {
154
                    $record['ip']  = false;
155
                    $record['ttl'] = 5;
156
                } else {
157
                    $record['ip'] = inet_ntop($data);
158
                }
159
            }elseif ($type === 'NS') {
160
                $record['ns'] = Binary::parseLabels($data, $orig);
161
            }elseif ($type === 'CNAME') {
162
                $record['cname'] = Binary::parseLabels($data, $orig);
163
            }
164
            elseif ($type == 'SOA') {
165
                $record['mname']     = Binary::parseLabels($data, $orig);
166
                $record['rname']     = Binary::parseLabels($data, $orig);
167
                $record['serial']     = Binary::getDWord($data);
168
                $record['refresh']     = Binary::getDWord($data);
169
                $record['retry']     = Binary::getDWord($data);
170
                $record['expire']    = Binary::getDWord($data);
171
                $record['nx']        = Binary::getDWord($data);
172
            }elseif ($type == 'MX') {
173
                $record['preference'] = Binary::getWord($data);
174
                $record['exchange'] = Binary::parseLabels($data, $orig);
175
            } elseif ($type == 'TXT') {
176
                $txt = [];
177
                while(strlen($data) > 0) {
178
                    $txt[] = Binary::parseLabels($data, $orig);
179
                }
180
                $record['text'] = implode('', $txt);
181
            } elseif ($type == 'SRV') {
182
                $record['priority']        = Binary::getWord($data);
183
                $record['weight']        = Binary::getWord($data);
184
                $record['port']        = Binary::getWord($data);
185
                $record['target'] = Binary::parseLabels($data, $orig);
186
            }
187
188
            return $record;
189
        };
190 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...
191
            $record = $getResRecord($pct);
192
            if (!isset($this->response[$record['type']])) {
193
                $this->response[$record['type']] = [];
194
            }
195
            $this->response[$record['type']][] = $record;
196
        }
197 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...
198
            $record = $getResRecord($pct);
199
            if (!isset($this->response[$record['type']])) {
200
                $this->response[$record['type']] = [];
201
            }
202
            $this->response[$record['type']][] = $record;
203
        }
204 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...
205
            $record = $getResRecord($pct);
206
            if (!isset($this->response[$record['type']])) {
207
                $this->response[$record['type']] = [];
208
            }
209
            $this->response[$record['type']][] = $record;
210
        }
211
        $this->onResponse->executeOne($this->response);
212
        if (!$this->keepalive) {
213
            $this->finish();
214
            return;
215
        } else {
216
            $this->checkFree();
217
        }
218
    }
219
220
    /**
221
     * Called when new data received
222
     * @return void
223
     */
224
    public function onRead()
225
    {
226
        start:
227
        if ($this->type === 'udp') {
228
            $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...
229
             return;
230
        }
231 View Code Duplication
        if ($this->state === self::STATE_ROOT) {
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...
232
            if (false === ($hdr = $this->readExact(2))) {
233
                return; // not enough data
234
            }
235
            $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...
236
            $this->setWatermark($this->pctSize);
237
            $this->state = self::STATE_PACKET;
238
        }
239 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...
240
            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...
241
                return; // not enough data
242
            }
243
            $this->state = self::STATE_ROOT;
244
            $this->setWatermark(2);
245
            $this->onUdpPacket($pct);
246
            return;
247
        }
248
        goto start;
249
    }
250
251
    /**
252
     * Gets the host information
253
     * @param  string   $hostname Hostname
254
     * @param  callable $cb       Callback
255
     * @callback $cb ( )
256
     * @return void
257
     */
258
    public function get($hostname, $cb)
259
    {
260
        $this->onResponse->push($cb);
261
        $this->setFree(false);
262
        $e         = explode(':', $hostname, 3);
263
        $hostname  = $e[0];
264
        $qtype     = isset($e[1]) ? $e[1] : 'A';
265
        $qclass    = isset($e[2]) ? $e[2] : 'IN';
266
        $QD        = [];
267
        $qtypeInt  = array_search($qtype, Pool::$type, true);
268
        $qclassInt = array_search($qclass, Pool::$class, true);
269
        if (($qtypeInt === false) || ($qclassInt === false)) {
270
            $cb(false);
271
            return;
272
        }
273
        $q      = Binary::labels($hostname) . // domain
274
                Binary::word($qtypeInt) .
275
                Binary::word($qclassInt);
276
        $QD[]   = $q;
277
        $packet =
278
                Binary::word(++$this->seq) . // Query ID
279
                Binary::bitmap2bytes(
280
                    '0' . // QR = 0
281
                    '0000' . // OPCODE = 0000 (standard query)
282
                    '0' . // AA = 0
283
                    '0' . // TC = 0
284
                    '1' . // RD = 1
285
286
                    '0' . // RA = 0, 
287
                    '000' . // reserved
288
                    '0000' // RCODE
289
, 2) .
290
                Binary::word(sizeof($QD)) . // QDCOUNT
291
                Binary::word(0) . // ANCOUNT
292
                Binary::word(0) . // NSCOUNT
293
                Binary::word(0) . // ARCOUNT
294
                implode('', $QD);
295
        if ($this->type === 'udp') {
296
            $this->write($packet);
297
        } else {
298
            $this->write(Binary::word(mb_orig_strlen($packet)) . $packet);
299
        }
300
    }
301
302
    /**
303
     * Called when connection finishes
304
     * @return void
305
     */
306
    public function onFinish()
307
    {
308
        $this->onResponse->executeAll(false);
309
        parent::onFinish();
310
    }
311
}
312