Unsubscribe::initializeObject()   A
last analyzed

Complexity

Conditions 1
Paths 1

Size

Total Lines 4
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 3
CRAP Score 1

Importance

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