Completed
Push — master ( 629445...184782 )
by Vasily
9s
created

Connection   B

Complexity

Total Complexity 41

Size/Duplication

Total Lines 291
Duplicated Lines 12.71 %

Coupling/Cohesion

Components 1
Dependencies 4

Importance

Changes 5
Bugs 4 Features 0
Metric Value
c 5
b 4
f 0
dl 37
loc 291
rs 8.2769
wmc 41
lcom 1
cbo 4

5 Methods

Rating   Name   Duplication   Size   Complexity  
A getMessageByRcode() 0 7 2
F onUdpPacket() 21 127 26
B onRead() 16 25 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 array Response
30
     */
31
    public $response = [];
32
33
    /**
34
     * @var boolean Current packet size
35
     */
36
    protected $pctSize = 0;
37
38
    /**
39
     * @var integer Default low mark. Minimum number of bytes in buffer.
40
     */
41
    protected $lowMark = 2;
42
43
    /**
44
     * @var integer Default high mark. Maximum number of bytes in buffer.
45
     */
46
    protected $highMark = 512;
47
48
    protected $rcodeMessages = [
49
        0       => 'Success',
50
        1       => 'Format Error',
51
        2       => 'Server Failure',
52
        3       => 'Non-Existent Domain',
53
        4       => 'Not Implemented',
54
        5       => 'Query Refused',
55
        6       => 'Name Exists when it should not',
56
        7       => 'RR Set Exists when it should not',
57
        8       => 'RR Set that should exist does not',
58
        9       => 'Not Authorized',
59
        10      => 'Name not contained in zone',
60
        16      => 'TSIG Signature Failure',
61
        17      => 'Key not recognized',
62
        18      => 'Signature out of time window',
63
        19      => 'Bad TKEY Mode', 
64
        20      => 'Duplicate key name',
65
        21      => 'Algorithm not supported',
66
        22      => 'Bad Truncation',
67
        23      => 'Bad/missing server cookie'
68
    ];
69
    
70
    /**
71
     * @param  int $rcode
72
     * @return string
73
     */
74
    protected function getMessageByRcode($rcode){
75
        if(isset($this->rcodeMessages[$rcode])){
76
            return $this->rcodeMessages[$rcode];
77
        }else{
78
            return 'UNKNOWN ERROR';
79
        }
80
    }
81
    
82
    /**
83
     * Called when new UDP packet received.
84
     * @param  string $pct
85
     * @return void
86
     */
87
    public function onUdpPacket($pct)
88
    {
89
        if(mb_orig_strlen($pct) < 10){
90
            return;
91
        }
92
        $orig           = $pct;
93
        $this->response = [];
94
        /*$id = */
95
        Binary::getWord($pct);
96
        $bitmap = Binary::getBitmap(Binary::getByte($pct)) . Binary::getBitmap(Binary::getByte($pct));
97
        //$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...
98
        $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...
99
        //$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...
100
        //$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...
101
        //$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...
102
        //$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...
103
        //$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...
104
        $rcode = bindec(mb_orig_substr($bitmap, 12));
105
        $this->response['status'] = [
106
            'rcode' => $rcode,
107
            'msg'   => $this->getMessageByRcode($rcode)
108
        ];
109
        $qdcount = Binary::getWord($pct);
110
        $ancount = Binary::getWord($pct);
111
        $nscount = Binary::getWord($pct);
112
        $arcount = Binary::getWord($pct);
113
        for ($i = 0; $i < $qdcount; ++$i) {
114
            $name     = Binary::parseLabels($pct, $orig);
115
            $typeInt  = Binary::getWord($pct);
116
            $type     = isset(Pool::$type[$typeInt]) ? Pool::$type[$typeInt] : 'UNK(' . $typeInt . ')';
117
            $classInt = Binary::getWord($pct);
118
            $class    = isset(Pool::$class[$classInt]) ? Pool::$class[$classInt] : 'UNK(' . $classInt . ')';
119
            if (!isset($this->response[$type])) {
120
                $this->response[$type] = [];
121
            }
122
            $record                    = [
123
                'name'  => $name,
124
                'type'  => $type,
125
                'class' => $class,
126
            ];
127
            $this->response['query'][] = $record;
128
        }
129
        $getResRecord = function (&$pct) use ($orig) {
130
            $name     = Binary::parseLabels($pct, $orig);
131
            $typeInt  = Binary::getWord($pct);
132
            $type     = isset(Pool::$type[$typeInt]) ? Pool::$type[$typeInt] : 'UNK(' . $typeInt . ')';
133
            $classInt = Binary::getWord($pct);
134
            $class    = isset(Pool::$class[$classInt]) ? Pool::$class[$classInt] : 'UNK(' . $classInt . ')';
135
            $ttl      = Binary::getDWord($pct);
136
            $length   = Binary::getWord($pct);
137
            $data     = mb_orig_substr($pct, 0, $length);
138
            $pct      = mb_orig_substr($pct, $length);
139
140
            $record = [
141
                'name'  => $name,
142
                'type'  => $type,
143
                'class' => $class,
144
                'ttl'   => $ttl,
145
            ];
146
147
            if (($type === 'A') || ($type === 'AAAA')) {
148
                if ($data === "\x00") {
149
                    $record['ip']  = false;
150
                    $record['ttl'] = 5;
151
                } else {
152
                    $record['ip'] = inet_ntop($data);
153
                }
154
            }elseif ($type === 'NS') {
155
                $record['ns'] = Binary::parseLabels($data, $orig);
156
            }elseif ($type === 'CNAME') {
157
                $record['cname'] = Binary::parseLabels($data, $orig);
158
            }
159
            elseif ($type === 'SOA') {
160
                $record['mname']    = Binary::parseLabels($data, $orig);
161
                $record['rname']    = Binary::parseLabels($data, $orig);
162
                $record['serial']   = Binary::getDWord($data);
163
                $record['refresh']  = Binary::getDWord($data);
164
                $record['retry']    = Binary::getDWord($data);
165
                $record['expire']   = Binary::getDWord($data);
166
                $record['nx']       = Binary::getDWord($data);
167
            }elseif ($type === 'MX') {
168
                $record['preference'] = Binary::getWord($data);
169
                $record['exchange'] = Binary::parseLabels($data, $orig);
170
            } elseif ($type === 'TXT') {
171
                $txt = [];
172
                while(mb_orig_strlen($data) > 0 && count($txt) < 1000) {
173
                    $txt[] = Binary::parseLabels($data, $orig);
174
                }
175
                $record['text'] = implode('', $txt);
176
            } elseif ($type === 'SRV') {
177
                $record['priority']        = Binary::getWord($data);
178
                $record['weight']        = Binary::getWord($data);
179
                $record['port']        = Binary::getWord($data);
180
                $record['target'] = Binary::parseLabels($data, $orig);
181
            }
182
183
            return $record;
184
        };
185 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...
186
            $record = $getResRecord($pct);
187
            if (!isset($this->response[$record['type']])) {
188
                $this->response[$record['type']] = [];
189
            }
190
            $this->response[$record['type']][] = $record;
191
        }
192 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...
193
            $record = $getResRecord($pct);
194
            if (!isset($this->response[$record['type']])) {
195
                $this->response[$record['type']] = [];
196
            }
197
            $this->response[$record['type']][] = $record;
198
        }
199 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...
200
            $record = $getResRecord($pct);
201
            if (!isset($this->response[$record['type']])) {
202
                $this->response[$record['type']] = [];
203
            }
204
            $this->response[$record['type']][] = $record;
205
        }
206
        $this->onResponse->executeOne($this->response);
207
        if (!$this->keepalive) {
208
            $this->finish();
209
            return;
210
        } else {
211
            $this->checkFree();
212
        }
213
    }
214
215
    /**
216
     * Called when new data received
217
     * @return void
218
     */
219
    public function onRead()
220
    {
221
        start:
222
        if ($this->type === 'udp') {
223
            $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...
224
             return;
225
        }
226 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...
227
            if (false === ($hdr = $this->readExact(2))) {
228
                return; // not enough data
229
            }
230
            $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...
231
            $this->setWatermark($this->pctSize);
232
            $this->state = self::STATE_PACKET;
233
        }
234 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...
235
            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...
236
                return; // not enough data
237
            }
238
            $this->state = self::STATE_ROOT;
239
            $this->setWatermark(2);
240
            $this->onUdpPacket($pct);
241
        }
242
        goto start;
243
    }
244
245
    /**
246
     * Gets the host information
247
     * @param  string   $hostname Hostname
248
     * @param  callable $cb       Callback
249
     * @callback $cb ( )
250
     * @return void
251
     */
252
    public function get($hostname, $cb)
253
    {
254
        $this->onResponse->push($cb);
255
        $this->setFree(false);
256
        $e         = explode(':', $hostname, 3);
257
        $hostname  = $e[0];
258
        $qtype     = isset($e[1]) ? $e[1] : 'A';
259
        $qclass    = isset($e[2]) ? $e[2] : 'IN';
260
        $QD        = [];
261
        $qtypeInt  = array_search($qtype, Pool::$type, true);
262
        $qclassInt = array_search($qclass, Pool::$class, true);
263
        if (($qtypeInt === false) || ($qclassInt === false)) {
264
            $cb(false);
265
            return;
266
        }
267
        $q      = Binary::labels($hostname) . // domain
268
                Binary::word($qtypeInt) .
269
                Binary::word($qclassInt);
270
        $QD[]   = $q;
271
        $packet =
272
                Binary::word(++$this->seq) . // Query ID
273
                Binary::bitmap2bytes(
274
                    '0' . // QR = 0
275
                    '0000' . // OPCODE = 0000 (standard query)
276
                    '0' . // AA = 0
277
                    '0' . // TC = 0
278
                    '1' . // RD = 1
279
280
                    '0' . // RA = 0, 
281
                    '000' . // reserved
282
                    '0000' // RCODE
283
, 2) .
284
                Binary::word(sizeof($QD)) . // QDCOUNT
285
                Binary::word(0) . // ANCOUNT
286
                Binary::word(0) . // NSCOUNT
287
                Binary::word(0) . // ARCOUNT
288
                implode('', $QD);
289
        if ($this->type === 'udp') {
290
            $this->write($packet);
291
        } else {
292
            $this->write(Binary::word(mb_orig_strlen($packet)) . $packet);
293
        }
294
    }
295
296
    /**
297
     * Called when connection finishes
298
     * @return void
299
     */
300
    public function onFinish()
301
    {
302
        $this->onResponse->executeAll(false);
303
        parent::onFinish();
304
    }
305
}
306