Passed
Push — master ( d36af8...d37c8b )
by Camilo
02:15
created

Unsubscribe::createPayload()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 8
Code Lines 4

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 5
CRAP Score 2

Importance

Changes 0
Metric Value
dl 0
loc 8
ccs 5
cts 5
cp 1
rs 9.4285
c 0
b 0
f 0
cc 2
eloc 4
nc 2
nop 0
crap 2
1
<?php
2
3
declare(strict_types=1);
4
5
namespace unreal4u\MQTT\Protocol;
6
7
use unreal4u\MQTT\Internals\PacketIdentifierFunctionality;
8
use unreal4u\MQTT\Internals\ProtocolBase;
9
use unreal4u\MQTT\Internals\TopicFunctionality;
10
use unreal4u\MQTT\Internals\WritableContent;
11
use unreal4u\MQTT\Internals\WritableContentInterface;
12
13
/**
14
 * An UNSUBSCRIBE Packet is sent by the Client to the Server, to unsubscribe from topics.
15
 */
16
final class Unsubscribe extends ProtocolBase implements WritableContentInterface
17
{
18
    use WritableContent, PacketIdentifierFunctionality, TopicFunctionality;
19
20
    const CONTROL_PACKET_VALUE = 10;
21
22 7
    protected function initializeObject(): ProtocolBase
23
    {
24 7
        $this->topics = new \SplQueue();
25 7
        return parent::initializeObject();
26
    }
27
28
    /**
29
     * @return string
30
     * @throws \unreal4u\MQTT\Exceptions\MustContainTopic
31
     * @throws \OutOfRangeException
32
     */
33 2
    public function createVariableHeader(): string
34
    {
35
        // Unsubscribe must always send a 2 flag
36 2
        $this->specialFlags = 2;
37
38 2
        return $this->getPacketIdentifierBinaryRepresentation();
39
    }
40
41
    /**
42
     * @return string
43
     * @throws \unreal4u\MQTT\Exceptions\MustContainTopic
44
     * @throws \OutOfRangeException
45
     */
46 3
    public function createPayload(): string
47
    {
48 3
        $output = '';
49 3
        foreach ($this->getTopics() as $topic) {
50
            // chr on QoS level is safe because it will create an 8-bit flag where the first 6 are only 0's
51 3
            $output .= $this->createUTF8String($topic->getTopicName());
52
        }
53 3
        return $output;
54
    }
55
56
    /**
57
     * When the Server receives a SUBSCRIBE Packet from a Client, the Server MUST respond with a SUBACK Packet
58
     *
59
     * This can however not be in the same order, as we may be able to receive PUBLISH packets before getting a SUBACK
60
     * back
61
     *
62
     * @see http://docs.oasis-open.org/mqtt/mqtt/v3.1.1/os/mqtt-v3.1.1-os.html#_Toc398718134 (MQTT-3.8.4-1)
63
     * @return bool
64
     */
65 1
    public function shouldExpectAnswer(): bool
66
    {
67 1
        return true;
68
    }
69
}
70