|
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
|
|
|
|