Completed
Push — master ( d37c8b...c70816 )
by Camilo
02:32
created

TopicFilterFunctionality::getNumberOfTopics()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 3
Code Lines 1

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 2
CRAP Score 1

Importance

Changes 0
Metric Value
dl 0
loc 3
ccs 2
cts 2
cp 1
rs 10
c 0
b 0
f 0
cc 1
eloc 1
nc 1
nop 0
crap 1
1
<?php
2
3
declare(strict_types=1);
4
5
namespace unreal4u\MQTT\Internals;
6
7
use unreal4u\MQTT\DataTypes\TopicFilter;
8
use unreal4u\MQTT\Exceptions\MustContainTopic;
9
10
/**
11
 * Trait ReadableContent
12
 * @package unreal4u\MQTT\Internals
13
 */
14
trait TopicFilterFunctionality
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 TopicFilter[] $topics
32
     * @return self
33
     */
34 10
    final public function addTopics(TopicFilter ...$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->getTopicFilter();
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|TopicFilter[]
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