|
1
|
|
|
<?php |
|
2
|
|
|
|
|
3
|
|
|
declare(strict_types=1); |
|
4
|
|
|
|
|
5
|
|
|
namespace unreal4u\MQTT\Internals; |
|
6
|
|
|
|
|
7
|
|
|
use unreal4u\MQTT\DataTypes\Topic; |
|
8
|
|
|
use unreal4u\MQTT\Exceptions\MustContainTopic; |
|
9
|
|
|
|
|
10
|
|
|
/** |
|
11
|
|
|
* Trait ReadableContent |
|
12
|
|
|
* @package unreal4u\MQTT\Internals |
|
13
|
|
|
*/ |
|
14
|
|
|
trait TopicFunctionality |
|
15
|
|
|
{ |
|
16
|
|
|
/** |
|
17
|
|
|
* The list of topics, being a SplQueue ensures the order is correct |
|
18
|
|
|
* @var \SplQueue |
|
19
|
|
|
*/ |
|
20
|
|
|
private $topics; |
|
21
|
|
|
|
|
22
|
|
|
/** |
|
23
|
|
|
* Unordered list of topic names in order to avoid duplicates |
|
24
|
|
|
* @var array |
|
25
|
|
|
*/ |
|
26
|
|
|
private $topicHashTable = []; |
|
27
|
|
|
|
|
28
|
|
|
/** |
|
29
|
|
|
* A subscription is based on filters, this function allows us to pass on filters |
|
30
|
|
|
* |
|
31
|
|
|
* @param Topic[] $topics |
|
32
|
|
|
* @return self |
|
33
|
|
|
*/ |
|
34
|
10 |
|
final public function addTopics(Topic ...$topics): self |
|
35
|
|
|
{ |
|
36
|
10 |
|
foreach ($topics as $topic) { |
|
37
|
|
|
// Frequently used: topicName, make it an apart variable for easy access |
|
38
|
10 |
|
$topicName = $topic->getTopicName(); |
|
39
|
10 |
|
if (\in_array($topicName, $this->topicHashTable, true) === false) { |
|
40
|
|
|
// Personally, I find this hacky as hell. However, using the SPL library there seems to be no other way |
|
41
|
10 |
|
$this->topicHashTable[] = $topicName; |
|
42
|
10 |
|
$this->topics->enqueue($topic); |
|
43
|
|
|
} |
|
44
|
|
|
} |
|
45
|
|
|
|
|
46
|
10 |
|
return $this; |
|
47
|
|
|
} |
|
48
|
|
|
|
|
49
|
|
|
/** |
|
50
|
|
|
* Returns the current number of topics |
|
51
|
|
|
* |
|
52
|
|
|
* @return int |
|
53
|
|
|
*/ |
|
54
|
10 |
|
private function getNumberOfTopics(): int |
|
55
|
|
|
{ |
|
56
|
10 |
|
return $this->topics->count(); |
|
57
|
|
|
} |
|
58
|
|
|
|
|
59
|
|
|
/** |
|
60
|
|
|
* Returns the topics in the order they were inserted / requested |
|
61
|
|
|
* |
|
62
|
|
|
* The order is important because SUBACK will return the status code for each topic in this order, without |
|
63
|
|
|
* explicitly identifying which topic is which |
|
64
|
|
|
* |
|
65
|
|
|
* @return \Generator|Topic[] |
|
66
|
|
|
* @throws \unreal4u\MQTT\Exceptions\MustContainTopic |
|
67
|
|
|
*/ |
|
68
|
5 |
|
private function getTopics(): \Generator |
|
69
|
|
|
{ |
|
70
|
5 |
|
if ($this->getNumberOfTopics() === 0) { |
|
71
|
1 |
|
throw new MustContainTopic('Before getting a topic, you should set it'); |
|
72
|
|
|
} |
|
73
|
|
|
|
|
74
|
4 |
|
for ($this->topics->rewind(); $this->topics->valid(); $this->topics->next()) { |
|
75
|
4 |
|
yield $this->topics->current(); |
|
76
|
|
|
} |
|
77
|
4 |
|
} |
|
78
|
|
|
} |
|
79
|
|
|
|