Connection   B
last analyzed

Complexity

Total Complexity 52

Size/Duplication

Total Lines 428
Duplicated Lines 8.88 %

Coupling/Cohesion

Components 1
Dependencies 5

Importance

Changes 0
Metric Value
dl 38
loc 428
rs 7.44
c 0
b 0
f 0
wmc 52
lcom 1
cbo 5

18 Methods

Rating   Name   Duplication   Size   Complexity  
A getId() 0 5 1
A onReady() 0 8 1
A onFinish() 0 12 3
A sendXML() 0 5 1
A startXMLStream() 0 7 1
A iqSet() 9 10 2
A iqSetTo() 10 10 2
A iqGet() 9 10 2
A iqGetTo() 10 10 2
A ping() 0 11 3
A queryGet() 0 4 1
A querySet() 0 4 1
A querySetTo() 0 4 1
C createXMLStream() 0 67 11
A message() 0 22 4
C presence() 0 40 9
A getVCard() 0 28 5
A onRead() 0 7 2

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\XMPP;
3
4
use PHPDaemon\Core\Daemon;
5
use PHPDaemon\Core\Timer;
6
use PHPDaemon\Network\ClientConnection;
7
use PHPDaemon\XMLStream\XMLStream;
8
9
/**
10
 * @package    NetworkClients
11
 * @subpackage XMPPClient
12
 * @author     Vasily Zorin <[email protected]>
13
 */
14
class Connection extends ClientConnection
15
{
16
17
    /**
18
     * @var boolean
19
     */
20
    public $use_encryption = false;
21
22
    /**
23
     * @var boolean
24
     */
25
    public $authorized;
26
27
    /**
28
     * @var integer
29
     */
30
    public $lastId = 0;
31
32
    /**
33
     * @var XMPPRoster
34
     */
35
    public $roster;
36
37
    /**
38
     * @var XMLStream
39
     */
40
    public $xml;
41
42
    /**
43
     * @var string
44
     */
45
    public $fulljid;
46
47
    /**
48
     * @var integer|string Timer ID
49
     */
50
    public $keepaliveTimer;
51
52
    /**
53
     * Get next ID
54
     * @return string
55
     */
56
    public function getId()
57
    {
58
        $id = ++$this->lastId;
59
        return dechex($id);
60
    }
61
62
    /**
63
     * Called when the connection is handshaked (at low-level), and peer is ready to recv. data
64
     * @return void
65
     */
66
    public function onReady()
67
    {
68
        $this->createXMLStream();
69
        $this->startXMLStream();
70
        $this->keepaliveTimer = setTimeout(function ($timer) {
0 ignored issues
show
Unused Code introduced by
The parameter $timer is not used and could be removed.

This check looks from parameters that have been defined for a function or method, but which are not used in the method body.

Loading history...
71
            $this->ping();
72
        }, 1e6 * 30);
73
    }
74
75
    /**
76
     * Called when session finishes
77
     * @return void
78
     */
79
    public function onFinish()
80
    {
81
        parent::onFinish();
82
        $this->event('disconnect');
83
        if (isset($this->xml)) {
84
            $this->xml->finish();
85
        }
86
        unset($this->roster);
87
        if ($this->keepaliveTimer) {
88
            Timer::remove($this->keepaliveTimer);
89
        }
90
    }
91
92
    /**
93
     * @TODO DESCR
94
     * @param string $s
95
     */
96
    public function sendXML($s)
97
    {
98
        //Daemon::log(Debug::dump(['send', $s]));
99
        $this->write($s);
100
    }
101
102
    /**
103
     * @TODO DESCR
104
     */
105
    public function startXMLStream()
106
    {
107
        $this->sendXML(
108
            '<?xml version="1.0"?>' .
109
            '<stream:stream xmlns:stream="http://etherx.jabber.org/streams" version="1.0" xmlns="jabber:client" to="' . $this->host . '" xml:lang="en" xmlns:xml="http://www.w3.org/XML/1998/namespace">'
110
        );
111
    }
112
113
    /**
114
     * @TODO DESCR
115
     * @param  string $xml
116
     * @param  callable $cb
117
     * @callback $cb ( )
118
     * @return boolean
119
     */
120 View Code Duplication
    public function iqSet($xml, $cb)
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in 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...
121
    {
122
        if (!isset($this->xml)) {
123
            return false;
124
        }
125
        $id = $this->getId();
126
        $this->xml->addIdHandler($id, $cb);
127
        $this->sendXML('<iq xmlns="jabber:client" type="set" id="' . $id . '">' . $xml . '</iq>');
128
        return true;
129
    }
130
131
    /**
132
     * @TODO DESCR
133
     * @param  string $to
134
     * @param  string $xml
135
     * @param  callable $cb
136
     * @callback $cb ( )
137
     * @return boolean
138
     */
139 View Code Duplication
    public function iqSetTo($to, $xml, $cb)
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in 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...
140
    {
141
        if (!isset($this->xml)) {
142
            return false;
143
        }
144
        $id = $this->getId();
145
        $this->xml->addIdHandler($id, $cb);
146
        $this->sendXML('<iq xmlns="jabber:client" type="set" id="' . $id . '" to="' . htmlspecialchars($to) . '">' . $xml . '</iq>');
147
        return true;
148
    }
149
150
    /**
151
     * @TODO DESCR
152
     * @param  string $xml
153
     * @param  callable $cb
154
     * @callback $cb ( )
155
     * @return boolean
156
     */
157 View Code Duplication
    public function iqGet($xml, $cb)
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in 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...
158
    {
159
        if (!isset($this->xml)) {
160
            return false;
161
        }
162
        $id = $this->getId();
163
        $this->xml->addIdHandler($id, $cb);
164
        $this->sendXML('<iq xmlns="jabber:client" type="get" id="' . $id . '">' . $xml . '</iq>');
165
        return true;
166
    }
167
168
    /**
169
     * @TODO DESCR
170
     * @param  string $to
171
     * @param  string $xml
172
     * @param  callable $cb
173
     * @callback $cb ( )
174
     * @return boolean
175
     */
176 View Code Duplication
    public function iqGetTo($to, $xml, $cb)
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in 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...
177
    {
178
        if (!isset($this->xml)) {
179
            return false;
180
        }
181
        $id = $this->getId();
182
        $this->xml->addIdHandler($id, $cb);
183
        $this->sendXML('<iq xmlns="jabber:client" type="get" id="' . $id . '" to="' . htmlspecialchars($to) . '">' . $xml . '</iq>');
184
        return true;
185
    }
186
187
    /**
188
     * @TODO DESCR
189
     * @param  string $to
0 ignored issues
show
Documentation introduced by
Should the type for parameter $to not be string|null?

This check looks for @param annotations where the type inferred by our type inference engine differs from the declared type.

It makes a suggestion as to what type it considers more descriptive.

Most often this is a case of a parameter that can be null in addition to its declared types.

Loading history...
190
     * @param  callable $cb
0 ignored issues
show
Documentation introduced by
Should the type for parameter $cb not be callable|null?

This check looks for @param annotations where the type inferred by our type inference engine differs from the declared type.

It makes a suggestion as to what type it considers more descriptive.

Most often this is a case of a parameter that can be null in addition to its declared types.

Loading history...
191
     * @callback $cb ( )
192
     * @return boolean
193
     */
194
    public function ping($to = null, $cb = null)
195
    {
196
        if (!isset($this->xml)) {
197
            return false;
198
        }
199
        if ($to === null) {
200
            $to = $this->host;
201
        }
202
        //Daemon::log('Sending ping to '.$to);
203
        return $this->iqGetTo($to, '<ping xmlns="urn:xmpp:ping"/>', $cb);
0 ignored issues
show
Bug introduced by
It seems like $cb defined by parameter $cb on line 194 can also be of type null; however, PHPDaemon\Clients\XMPP\Connection::iqGetTo() does only seem to accept callable, maybe add an additional type check?

This check looks at variables that have been passed in as parameters and are passed out again to other methods.

If the outgoing method call has stricter type requirements than the method itself, an issue is raised.

An additional type check may prevent trouble.

Loading history...
204
    }
205
206
    /**
207
     * @TODO DESCR
208
     * @param  string $ns
209
     * @param  callable $cb
210
     * @callback $cb ( )
211
     * @return boolean
212
     */
213
    public function queryGet($ns, $cb)
214
    {
215
        return $this->iqGet('<query xmlns="' . $ns . '" />', $cb);
216
    }
217
218
    /**
219
     * @TODO DESCR
220
     * @param  string $ns
221
     * @param  string $xml
222
     * @param  callable $cb
223
     * @callback $cb ( )
224
     * @return boolean
225
     */
226
    public function querySet($ns, $xml, $cb)
227
    {
228
        return $this->iqSet('<query xmlns="' . $ns . '">' . $xml . '</query>', $cb);
229
    }
230
231
    /**
232
     * @TODO DESCR
233
     * @param  string $to
234
     * @param  string $ns
235
     * @param  string $xml
236
     * @param  callable $cb
237
     * @callback $cb ( )
238
     * @return boolean
239
     */
240
    public function querySetTo($to, $ns, $xml, $cb)
241
    {
242
        return $this->iqSetTo($to, '<query xmlns="' . $ns . '">' . $xml . '</query>', $cb);
243
    }
244
245
    /**
246
     * @TODO DESCR
247
     */
248
    public function createXMLStream()
249
    {
250
        $this->xml = new XMLStream;
251
        $this->xml->setDefaultNS('jabber:client');
252
        $this->xml->addXPathHandler('{http://etherx.jabber.org/streams}features', function ($xml) {
253
            /** @var XMLStream $xml */
254
            if ($xml->hasSub('starttls') and $this->use_encryption) {
255
                $this->sendXML("<starttls xmlns='urn:ietf:params:xml:ns:xmpp-tls'><required /></starttls>");
256
            } elseif ($xml->hasSub('bind') and $this->authorized) {
257
                $id = $this->getId();
0 ignored issues
show
Unused Code introduced by
$id 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...
258
                $this->iqSet('<bind xmlns="urn:ietf:params:xml:ns:xmpp-bind"><resource>' . $this->path . '</resource></bind>',
259
                    function ($xml) {
260
                        if ($xml->attrs['type'] === 'result') {
261
                            $this->fulljid = $xml->sub('bind')->sub('jid')->data;
262
                            $jidarray = explode('/', $this->fulljid);
263
                            $this->jid = $jidarray[0];
0 ignored issues
show
Documentation introduced by
The property jid does not exist on object<PHPDaemon\Clients\XMPP\Connection>. Since you implemented __set, maybe consider adding a @property annotation.

Since your code implements the magic setter _set, this function will be called for any write access on an undefined variable. You can add the @property annotation to your class or interface to document the existence of this variable.

<?php

/**
 * @property int $x
 * @property int $y
 * @property string $text
 */
class MyLabel
{
    private $properties;

    private $allowedProperties = array('x', 'y', 'text');

    public function __get($name)
    {
        if (isset($properties[$name]) && in_array($name, $this->allowedProperties)) {
            return $properties[$name];
        } else {
            return null;
        }
    }

    public function __set($name, $value)
    {
        if (in_array($name, $this->allowedProperties)) {
            $properties[$name] = $value;
        } else {
            throw new \LogicException("Property $name is not defined.");
        }
    }

}

Since the property has write access only, you can use the @property-write annotation instead.

Of course, you may also just have mistyped another name, in which case you should fix the error.

See also the PhpDoc documentation for @property.

Loading history...
264
                        }
265
                        $this->iqSet('<session xmlns="urn:ietf:params:xml:ns:xmpp-session" />', function ($xml) {
0 ignored issues
show
Unused Code introduced by
The parameter $xml is not used and could be removed.

This check looks from parameters that have been defined for a function or method, but which are not used in the method body.

Loading history...
266
                            $this->roster = new XMPPRoster($this);
267
                            if ($this->onConnected) {
268
                                $this->connected = true;
269
                                $this->onConnected->executeAll($this);
270
                                $this->onConnected = null;
271
                            }
272
                            $this->event('connected');
273
                        });
274
                    });
275
            } else {
276
                if (mb_orig_strlen($this->password)) {
277
                    $this->sendXML("<auth xmlns='urn:ietf:params:xml:ns:xmpp-sasl' mechanism='PLAIN'>" . base64_encode("\x00" . $this->user . "\x00" . $this->password) . "</auth>");
278
                } else {
279
                    $this->sendXML("<auth xmlns='urn:ietf:params:xml:ns:xmpp-sasl' mechanism='ANONYMOUS'/>");
280
                }
281
            }
282
        });
283
        $this->xml->addXPathHandler('{urn:ietf:params:xml:ns:xmpp-sasl}success', function ($xml) {
0 ignored issues
show
Unused Code introduced by
The parameter $xml is not used and could be removed.

This check looks from parameters that have been defined for a function or method, but which are not used in the method body.

Loading history...
284
            $this->authorized = true;
285
            $this->xml->finish();
286
            $this->createXMLStream();
287
            $this->startXMLStream();
288
        });
289
        $this->xml->addXPathHandler('{urn:ietf:params:xml:ns:xmpp-sasl}failure', function ($xml) {
0 ignored issues
show
Unused Code introduced by
The parameter $xml is not used and could be removed.

This check looks from parameters that have been defined for a function or method, but which are not used in the method body.

Loading history...
290
            if ($this->onConnected) {
291
                $this->connected = false;
292
                $func = $this->onConnected;
293
                $func($this);
294
                $this->onConnected = null;
295
            }
296
            $this->finish();
297
        });
298
        $this->xml->addXPathHandler('{urn:ietf:params:xml:ns:xmpp-tls}proceed', function ($xml) {
0 ignored issues
show
Unused Code introduced by
The parameter $xml is not used and could be removed.

This check looks from parameters that have been defined for a function or method, but which are not used in the method body.

Loading history...
299
            Daemon::log("XMPPClient: TLS not supported.");
300
        });
301
        $this->xml->addXPathHandler('{jabber:client}message', function ($xml) {
302
            if (isset($xml->attrs['type'])) {
303
                $payload['type'] = $xml->attrs['type'];
0 ignored issues
show
Coding Style Comprehensibility introduced by
$payload was never initialized. Although not strictly required by PHP, it is generally a good practice to add $payload = array(); before regardless.

Adding an explicit array definition is generally preferable to implicit array definition as it guarantees a stable state of the code.

Let’s take a look at an example:

foreach ($collection as $item) {
    $myArray['foo'] = $item->getFoo();

    if ($item->hasBar()) {
        $myArray['bar'] = $item->getBar();
    }

    // do something with $myArray
}

As you can see in this example, the array $myArray is initialized the first time when the foreach loop is entered. You can also see that the value of the bar key is only written conditionally; thus, its value might result from a previous iteration.

This might or might not be intended. To make your intention clear, your code more readible and to avoid accidental bugs, we recommend to add an explicit initialization $myArray = array() either outside or inside the foreach loop.

Loading history...
304
            } else {
305
                $payload['type'] = 'chat';
0 ignored issues
show
Coding Style Comprehensibility introduced by
$payload was never initialized. Although not strictly required by PHP, it is generally a good practice to add $payload = array(); before regardless.

Adding an explicit array definition is generally preferable to implicit array definition as it guarantees a stable state of the code.

Let’s take a look at an example:

foreach ($collection as $item) {
    $myArray['foo'] = $item->getFoo();

    if ($item->hasBar()) {
        $myArray['bar'] = $item->getBar();
    }

    // do something with $myArray
}

As you can see in this example, the array $myArray is initialized the first time when the foreach loop is entered. You can also see that the value of the bar key is only written conditionally; thus, its value might result from a previous iteration.

This might or might not be intended. To make your intention clear, your code more readible and to avoid accidental bugs, we recommend to add an explicit initialization $myArray = array() either outside or inside the foreach loop.

Loading history...
306
            }
307
            $payload['xml'] = $xml;
308
            $payload['from'] = $xml->attrs['from'];
309
            if ($xml->hasSub('body')) {
310
                $payload['body'] = $xml->sub('body')->data;
311
                $this->event('message', $payload);
312
            }
313
        });
314
    }
315
316
    /**
317
     * Send XMPP Message
318
     * @param string $to
319
     * @param string $body
320
     * @param string $type
321
     * @param string $subject
0 ignored issues
show
Documentation introduced by
Should the type for parameter $subject not be string|null?

This check looks for @param annotations where the type inferred by our type inference engine differs from the declared type.

It makes a suggestion as to what type it considers more descriptive.

Most often this is a case of a parameter that can be null in addition to its declared types.

Loading history...
322
     */
323
    public function message($to, $body, $type = 'chat', $subject = null, $payload = null)
324
    {
325
        if ($type === null) {
326
            $type = 'chat';
327
        }
328
329
        $to = htmlspecialchars($to);
330
        $body = htmlspecialchars($body);
331
        $subject = htmlspecialchars($subject);
332
333
        $out = '<message from="' . $this->fulljid . '" to="' . $to . '" type="' . $type . '">';
334
        if ($subject) {
335
            $out .= '<subject>' . $subject . '</subject>';
336
        }
337
        $out .= '<body>' . $body . '</body>';
338
        if ($payload) {
339
            $out .= $payload;
340
        }
341
        $out .= "</message>";
342
343
        $this->sendXML($out);
344
    }
345
346
    /**
347
     * Set Presence
348
     * @param string $status
0 ignored issues
show
Documentation introduced by
Should the type for parameter $status not be string|null?

This check looks for @param annotations where the type inferred by our type inference engine differs from the declared type.

It makes a suggestion as to what type it considers more descriptive.

Most often this is a case of a parameter that can be null in addition to its declared types.

Loading history...
349
     * @param string $show
350
     * @param string $to
0 ignored issues
show
Documentation introduced by
Should the type for parameter $to not be string|null?

This check looks for @param annotations where the type inferred by our type inference engine differs from the declared type.

It makes a suggestion as to what type it considers more descriptive.

Most often this is a case of a parameter that can be null in addition to its declared types.

Loading history...
351
     * @param string $type
352
     * @param integer $priority
353
     */
354
    public function presence($status = null, $show = 'available', $to = null, $type = 'available', $priority = 0)
355
    {
356
        if ($type === 'available') {
357
            $type = '';
358
        }
359
        $to = htmlspecialchars($to);
360
        $status = htmlspecialchars($status);
361
        $show = htmlspecialchars($show);
362
        $type = htmlspecialchars($type);
363
        $priority = htmlspecialchars($priority);
364
        if ($show === 'unavailable') {
365
            $type = 'unavailable';
366
        }
367
368
        $out = "<presence";
369
        $out .= ' from="' . $this->fulljid . '"';
370
        if ($to) {
371
            $out .= ' to="' . $to . '"';
372
        }
373
        if ($type) {
374
            $out .= ' type="' . $type . '"';
375
        }
376
        $inner = '';
377
        if ($show !== 'available') {
378
            $inner .= "<show>$show</show>";
379
        }
380
        if ($status) {
381
            $inner .= "<status>$status</status>";
382
        }
383
        if ($priority) {
384
            $inner .= "<priority>$priority</priority>";
385
        }
386
        if ($inner === '') {
387
            $out .= "/>";
388
        } else {
389
            $out .= '>' . $inner . '</presence>';
390
        }
391
392
        $this->sendXML($out);
393
    }
394
395
    /**
396
     * @TODO DESCR
397
     * @param string $jid
398
     * @param callable $cb
399
     * @callback $cb ( )
400
     */
401
    public function getVCard($jid, $cb)
402
    {
403
        $id = $this->getId();
404
        $this->xml->addIdHandler($id, function ($xml) use ($cb) {
405
            $vcard = [];
406
            $vcardXML = $xml->sub('vcard');
407
            foreach ($vcardXML->subs as $sub) {
408
                if ($sub->subs) {
409
                    $vcard[$sub->name] = [];
410
                    foreach ($sub->subs as $sub_child) {
411
                        $vcard[$sub->name][$sub_child->name] = $sub_child->data;
412
                    }
413
                } else {
414
                    $vcard[$sub->name] = $sub->data;
415
                }
416
            }
417
            $vcard['from'] = $xml->attrs['from'];
418
            $cb($vcard);
419
        });
420
        $id = htmlspecialchars($id);
421
422
        if ($jid != null) {
423
            $jid = htmlspecialchars($jid);
424
            $this->send('<iq type="get" id="' . $id . '" to="' . $jid . '"><vCard xmlns="vcard-temp" /></iq>');
0 ignored issues
show
Documentation Bug introduced by
The method send does not exist on object<PHPDaemon\Clients\XMPP\Connection>? Since you implemented __call, maybe consider adding a @method annotation.

If you implement __call and you know which methods are available, you can improve IDE auto-completion and static analysis by adding a @method annotation to the class.

This is often the case, when __call is implemented by a parent class and only the child class knows which methods exist:

class ParentClass {
    private $data = array();

    public function __call($method, array $args) {
        if (0 === strpos($method, 'get')) {
            return $this->data[strtolower(substr($method, 3))];
        }

        throw new \LogicException(sprintf('Unsupported method: %s', $method));
    }
}

/**
 * If this class knows which fields exist, you can specify the methods here:
 *
 * @method string getName()
 */
class SomeClass extends ParentClass { }
Loading history...
425
        } else {
426
            $this->send('<iq type="get" id="' . $id . '"><vCard xmlns="vcard-temp" /></iq>');
0 ignored issues
show
Documentation Bug introduced by
The method send does not exist on object<PHPDaemon\Clients\XMPP\Connection>? Since you implemented __call, maybe consider adding a @method annotation.

If you implement __call and you know which methods are available, you can improve IDE auto-completion and static analysis by adding a @method annotation to the class.

This is often the case, when __call is implemented by a parent class and only the child class knows which methods exist:

class ParentClass {
    private $data = array();

    public function __call($method, array $args) {
        if (0 === strpos($method, 'get')) {
            return $this->data[strtolower(substr($method, 3))];
        }

        throw new \LogicException(sprintf('Unsupported method: %s', $method));
    }
}

/**
 * If this class knows which fields exist, you can specify the methods here:
 *
 * @method string getName()
 */
class SomeClass extends ParentClass { }
Loading history...
427
        }
428
    }
429
430
    /**
431
     * Called when new data received
432
     * @return void
433
     */
434
    public function onRead()
435
    {
436
        Timer::setTimeout($this->keepaliveTimer);
437
        if (isset($this->xml)) {
438
            $this->xml->feed($this->readUnlimited());
439
        }
440
    }
441
}
442