PriorityCollection   A
last analyzed

Complexity

Total Complexity 5

Size/Duplication

Total Lines 60
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 0

Test Coverage

Coverage 100%

Importance

Changes 0
Metric Value
dl 0
loc 60
ccs 18
cts 18
cp 1
rs 10
c 0
b 0
f 0
wmc 5
lcom 1
cbo 0

5 Methods

Rating   Name   Duplication   Size   Complexity  
A getIterator() 0 4 1
A count() 0 4 1
A insert() 0 6 1
A remove() 0 8 1
A rebuildCache() 0 8 1
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\Utils;
17
18
use Traversable;
19
20
class PriorityCollection implements \IteratorAggregate, \Countable
21
{
22
    /**
23
     * @var array[]
24
     */
25
    private $_collection = [];
26
    private $_cache;
27
28
29
    /**
30
     * Retrieve an external iterator
31
     * @link  http://php.net/manual/en/iteratoraggregate.getiterator.php
32
     * @return Traversable An instance of an object implementing <b>Iterator</b> or
33
     * <b>Traversable</b>
34
     * @since 5.0.0
35
     */
36 7
    public function getIterator()
37
    {
38 7
        return new \ArrayIterator($this->_cache);
39
    }
40
41
    /**
42
     * Count elements of an object
43
     * @link  http://php.net/manual/en/countable.count.php
44
     * @return int The custom count as an integer.
45
     * </p>
46
     * <p>
47
     * The return value is cast to an integer.
48
     * @since 5.1.0
49
     */
50 1
    public function count()
51
    {
52 1
        return count($this->_cache);
53
    }
54
55 11
    public function insert($value, int $priority)
56
    {
57 11
        $this->_collection[] = [$priority, $value];
58
59 11
        $this->rebuildCache();
60 11
    }
61
62 1
    public function remove($value)
63
    {
64
        $this->_collection = array_filter($this->_collection, function ($e) use ($value) {
65 1
            return $e[1] !== $value;
66 1
        });
67
68 1
        $this->rebuildCache();
69 1
    }
70
71
    private function rebuildCache()
72
    {
73 11
        usort($this->_collection, function ($a, $b) {
74 11
            return $b[0] <=> $a[0];
75 11
        });
76
77 11
        $this->_cache = array_column($this->_collection, 1);
78 11
    }
79
}
80