Roster   A
last analyzed

Complexity

Total Complexity 29

Size/Duplication

Total Lines 252
Duplicated Lines 0 %

Coupling/Cohesion

Components 2
Dependencies 12

Test Coverage

Coverage 60.52%

Importance

Changes 0
Metric Value
dl 0
loc 252
ccs 46
cts 76
cp 0.6052
rs 10
c 0
b 0
f 0
wmc 29
lcom 2
cbo 12

20 Methods

Rating   Name   Duplication   Size   Complexity  
B setClient() 0 23 4
A handleSet() 0 12 3
A handleResult() 0 10 2
A offsetExists() 0 4 1
A offsetGet() 0 4 1
A offsetSet() 0 4 1
A offsetUnset() 0 4 1
A remove() 0 13 3
A update() 0 8 1
A add() 0 4 1
A getIterator() 0 4 1
A getItems() 0 4 1
A group() 0 4 1
A map() 0 4 1
A filter() 0 4 1
A asArray() 0 4 1
A fromArray() 0 4 1
A count() 0 4 1
A setItem() 0 5 1
A removeItem() 0 12 2
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\Highlighter\Utils\Console;
20
use Kadet\Xmpp\Exception\BadMethodCallException;
21
use Kadet\Xmpp\Exception\ReadOnlyException;
22
use Kadet\Xmpp\Jid;
23
use Kadet\Xmpp\Stanza\Iq;
24
use Kadet\Xmpp\Utils\Accessors;
25
use Kadet\Xmpp\Utils\BetterEmitter;
26
use Kadet\Xmpp\Utils\filter as with;
27
use Kadet\Xmpp\XmppClient;
28
use Traversable;
29
30
use function Kadet\Xmpp\Utils\helper\format;
31
32
/**
33
 * Class Roster
34
 * @package Kadet\Xmpp\Component
35
 *
36
 * @property-read Iq\Query\Roster\Item[] $items Copy of all roster items
37
 *
38
 * @event item(Iq\Query\Roster\Item $item)      Emitted on item update
39
 * @event remove(Iq\Query\Roster\Item $item)    Emitted on item removal
40
 * @event update()                              Emitted on roster update (after processing roster item)
41
 */
42
class Roster extends Component implements \IteratorAggregate, \ArrayAccess
43
{
44
    use BetterEmitter, Accessors;
45
46
    private $_items = [];
47
48 5
    public function setClient(XmppClient $client)
49
    {
50 5
        if($this->_client !== null) {
51
            throw new BadMethodCallException("You cannot change rosters XmppClient instance.");
52
        }
53
54 5
        parent::setClient($client);
55
        $this->_client->on('init', function(\SplQueue $queue) {
56 1
            $queue->enqueue($this->_client->send(new Iq('get', ['query' => new Iq\Query\Roster()])));
57 5
        });
58
59 5
        $this->_client->on('iq', function(Iq $iq) {
60
            /** @var Roster $iq->query */
61 3
            switch ($iq->type) {
62 3
                case "result":
63 3
                    $this->handleResult($iq->query);
0 ignored issues
show
Documentation introduced by
$iq->query is of type object<Kadet\Xmpp\Component\Roster>, but the function expects a object<Kadet\Xmpp\Stanza\Iq\Query\Roster>.

It seems like the type of the argument is not accepted by the function/method which you are calling.

In some cases, in particular if PHP’s automatic type-juggling kicks in this might be fine. In other cases, however this might be a bug.

We suggest to add an explicit type cast like in the following example:

function acceptsInteger($int) { }

$x = '123'; // string "123"

// Instead of
acceptsInteger($x);

// we recommend to use
acceptsInteger((integer) $x);
Loading history...
64 3
                    break;
65
                case "set":
66
                    $this->handleSet($iq->query);
0 ignored issues
show
Documentation introduced by
$iq->query is of type object<Kadet\Xmpp\Component\Roster>, but the function expects a object<Kadet\Xmpp\Stanza\Iq\Query\Roster>.

It seems like the type of the argument is not accepted by the function/method which you are calling.

In some cases, in particular if PHP’s automatic type-juggling kicks in this might be fine. In other cases, however this might be a bug.

We suggest to add an explicit type cast like in the following example:

function acceptsInteger($int) { }

$x = '123'; // string "123"

// Instead of
acceptsInteger($x);

// we recommend to use
acceptsInteger((integer) $x);
Loading history...
67
                    break;
68
            }
69 5
        }, with\iq\query(Iq\Query\Roster::class));
70 5
    }
71
72 3
    private function handleSet(Iq\Query\Roster $query)
73
    {
74 3
        foreach ($query->items as $item) {
75 3
            if($item->subscription == 'remove') {
76
                $this->removeItem($item->jid);
77
            } else {
78 3
                $this->setItem($item);
79
            }
80
        }
81
82 3
        $this->emit('update');
83 3
    }
84
85 3
    private function handleResult(Iq\Query\Roster $query)
86
    {
87 3
        $this->_client->getLogger()->debug(format('Received roster (version: {version}) update with {no} roster items.', [
88 3
            'no' => count($query->items),
89 3
            'version' => $query->version ?: 'no version'
90
        ]));
91
92 3
        $this->_items = [];
93 3
        $this->handleSet($query);
94 3
    }
95
96
    /**
97
     * Whether a offset exists
98
     * @link  http://php.net/manual/en/arrayaccess.offsetexists.php
99
     * @param mixed $offset <p>
100
     *                      An offset to check for.
101
     *                      </p>
102
     * @return boolean true on success or false on failure.
103
     *                      </p>
104
     *                      <p>
105
     *                      The return value will be casted to boolean if non-boolean was returned.
106
     * @since 5.0.0
107
     */
108
    public function offsetExists($offset)
109
    {
110
        return array_key_exists($offset, $this->_items);
111
    }
112
113
    /**
114
     * Offset to retrieve
115
     * @link  http://php.net/manual/en/arrayaccess.offsetget.php
116
     * @param mixed $offset <p>
117
     *                      The offset to retrieve.
118
     *                      </p>
119
     * @return mixed Can return all value types.
120
     * @since 5.0.0
121
     */
122 1
    public function offsetGet($offset)
123
    {
124 1
        return clone ($this->_items[(string)$offset] ?? null);
125
    }
126
127
    /**
128
     * Offset to set
129
     * @link  http://php.net/manual/en/arrayaccess.offsetset.php
130
     * @param mixed $offset <p>
131
     *                      The offset to assign the value to.
132
     *                      </p>
133
     * @param mixed $value  <p>
134
     *                      The value to set.
135
     *                      </p>
136
     * @return void
137
     * @since 5.0.0
138
     */
139
    public function offsetSet($offset, $value)
140
    {
141
        throw new ReadOnlyException('You should not modify roster directly, use update() method.');
142
    }
143
144
    /**
145
     * Offset to unset
146
     * @link  http://php.net/manual/en/arrayaccess.offsetunset.php
147
     * @param mixed $offset <p>
148
     *                      The offset to unset.
149
     *                      </p>
150
     * @return void
151
     * @since 5.0.0
152
     */
153
    public function offsetUnset($offset)
154
    {
155
        throw new ReadOnlyException('You should not modify roster directly, use remove() method.');
156
    }
157
158
    /**
159
     * Removes item from servers roster.
160
     *
161
     * @param Jid|string|\Closure $what Predicate used to determine items.
162
     *
163
     * @return \React\Promise\ExtendedPromiseInterface Removal result promise.
164
     */
165 1
    public function remove($what)
166
    {
167 1
        $predicate = $what instanceof \Closure ? $what : with\property('jid', with\equals($what));
168 1
        $remove    = array_filter($this->_items, $predicate);
169
170 1
        $iq = new Iq('remove', ['query' => new Iq\Query\Roster()]);
171
        /** @var Iq\Query\Roster\Item $item */
172 1
        foreach($remove as $item) {
173 1
            $iq->query->append(new Iq\Query\Roster\Item($item->jid, ['subscription' => 'remove']));
174
        }
175
176 1
        return $this->_client->send($iq);
177
    }
178
179
    /**
180
     * Saves item to roster.
181
     *
182
     * @param Iq\Query\Roster\Item $item Item to save.
183
     *
184
     * @return \React\Promise\ExtendedPromiseInterface Update result promise.
185
     */
186 2
    public function update(Iq\Query\Roster\Item $item)
187
    {
188 2
        $iq = new Iq('set', ['query' => new Iq\Query\Roster([
189 2
            'items' => [ $item ]
190
        ])]);
191
192 2
        return $this->_client->send($iq);
193
    }
194
195
    /**
196
     * Adds item to roster.
197
     *
198
     * @param Iq\Query\Roster\Item $item Item to add.
199
     *
200
     * @return \React\Promise\ExtendedPromiseInterface Addition result promise.
201
     */
202 1
    public function add(Iq\Query\Roster\Item $item)
203
    {
204 1
        return $this->update($item); // From XMPPs perspective adding is same as updating non existent item.
205
    }
206
207
    /**
208
     * Retrieve an external iterator
209
     * @link  http://php.net/manual/en/iteratoraggregate.getiterator.php
210
     * @return Traversable An instance of an object implementing <b>Iterator</b> or
211
     * <b>Traversable</b>
212
     * @since 5.0.0
213
     */
214
    public function getIterator(): Traversable
215
    {
216
        return new \ArrayIterator($this->_items);
217
    }
218
219
    /**
220
     * @return Iq\Query\Roster\Item[]
221
     */
222 1
    public function getItems()
223
    {
224 1
        return \Kadet\Xmpp\Utils\helper\copy($this->_items);
225
    }
226
227
    public static function group($name)
228
    {
229
        return with\property('groups', with\contains($name));
230
    }
231
232
    /**
233
     * @param callable(Item $item) $mapper
0 ignored issues
show
Documentation introduced by
The doc-type callable(Item could not be parsed: Expected "|" or "end of type", but got "(" at position 8. (view supported doc-types)

This check marks PHPDoc comments that could not be parsed by our parser. To see which comment annotations we can parse, please refer to our documentation on supported doc-types.

Loading history...
Bug introduced by
There is no parameter named $item). Was it maybe removed?

This check looks for PHPDoc comments describing methods or function parameters that do not exist on the corresponding method or function.

Consider the following example. The parameter $italy is not defined by the method finale(...).

/**
 * @param array $germany
 * @param array $island
 * @param array $italy
 */
function finale($germany, $island) {
    return "2:1";
}

The most likely cause is that the parameter was removed, but the annotation was not.

Loading history...
234
     * @return array
235
     */
236
    public function map(callable $mapper)
237
    {
238
        return array_map($mapper, $this->items);
239
    }
240
241
    /**
242
     * @param callable $predicate
243
     * @return Iq\Query\Roster\Item[]
244
     */
245
    public function filter(callable $predicate)
246
    {
247
        return array_filter($this->items, $predicate);
248
    }
249
250
    public function asArray() : array
251
    {
252
        return $this->items;
253
    }
254
255
    public static function fromArray(array $array)
0 ignored issues
show
Unused Code introduced by
The parameter $array 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...
256
    {
257
        // TODO: Implement fromArray() method.
258
    }
259
260
    /**
261
     * Count elements of an object
262
     * @link  http://php.net/manual/en/countable.count.php
263
     * @return int The custom count as an integer.
264
     * </p>
265
     * <p>
266
     * The return value is cast to an integer.
267
     * @since 5.1.0
268
     */
269
    public function count()
270
    {
271
        return count($this->items);
272
    }
273
274
275 3
    private function setItem(Iq\Query\Roster\Item $item)
276
    {
277 3
        $this->emit('item', [ $item ]);
278 3
        $this->_items[(string)$item->jid] = $item;
279 3
    }
280
281
    private function removeItem(Jid $jid)
282
    {
283
        if (!isset($this->_items[(string)$jid])) {
284
            $this->_client->getLogger()->warning(format('Trying to remove non-existing roster item {jid}', [
285
                'item' => Console::styled(['color' => 'green'], (string)$jid)
286
            ]));
287
            return;
288
        }
289
290
        $this->emit('remove', [ $this->_items[(string)$jid] ]);
291
        unset($this->_items[(string)$jid]);
292
    }
293
}
294