Completed
Push — master ( 939cef...4aee11 )
by Kacper
03:59
created

Binding::setClient()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 8
Code Lines 4

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 5
CRAP Score 1

Importance

Changes 1
Bugs 0 Features 0
Metric Value
c 1
b 0
f 0
dl 0
loc 8
cc 1
eloc 4
nc 1
nop 1
ccs 5
cts 5
cp 1
crap 1
rs 9.4285
1
<?php
2
/**
3
 * Nucleus - XMPP Library for PHP
4
 *
5
 * Copyright (C) 2016, Some rights reserved.
6
 *
7
 * @author Kacper "Kadet" Donat <[email protected]>
8
 *
9
 * Contact with author:
10
 * Xmpp: [email protected]
11
 * E-mail: [email protected]
12
 *
13
 * From Kadet with love.
14
 */
15
16
namespace Kadet\Xmpp\Component;
17
18
19
use Kadet\Xmpp\Exception\Protocol\BindingException;
20
use Kadet\Xmpp\Stanza\Iq;
21
use Kadet\Xmpp\Stream\Features;
22
use Kadet\Xmpp\Xml\XmlElement;
23
use Kadet\Xmpp\XmppClient;
24
use \Kadet\Xmpp\Utils\filter as with;
25
26
class Binding extends Component
27
{
28
    const XMLNS = 'urn:ietf:params:xml:ns:xmpp-bind';
29
30 5
    public function setClient(XmppClient $client)
31
    {
32 5
        parent::setClient($client);
33
34
        $client->on('features', function (Features $features) {
35 5
            return !$this->bind($features);
36 5
        });
37 5
    }
38
39 5
    public function bind(Features $features)
40
    {
41 5
        if($features->has(with\element('bind', self::XMLNS))) {
42 4
            $stanza = new Iq(['type' => 'set']);
43 4
            $bind = $stanza->append(new Iq\Query(self::XMLNS, 'bind'));
44
45 4
            if(!$this->_client->jid->isBare()) {
46 2
                $bind->append(new XmlElement('resource', null, ['content' => $this->_client->jid->resource]));
47
            }
48
49 4
            $this->_client->once('element', function(Iq $element) {
50 4
                $this->handleResult($element);
51 4
            }, with\stanza\id($stanza->id));
52
53 4
            $this->_client->write($stanza);
54 4
            return true;
55
        }
56
57 1
        return false;
58
    }
59
60 4
    public function handleResult(Iq $stanza)
61
    {
62 4
        if($stanza->type === 'error') {
63 2
            throw BindingException::fromError($this->_client->jid, $stanza->error);
64
        }
65
66 2
        $this->_client->bind($stanza->element('bind', self::XMLNS)->element('jid')->innerXml);
67 2
    }
68
}
69