Passed
Push — master ( 92cd79...812748 )
by Camilo
03:00
created

PacketIdentifierFunctionality   A

Complexity

Total Complexity 9

Size/Duplication

Total Lines 94
Duplicated Lines 0 %

Test Coverage

Coverage 93.55%

Importance

Changes 0
Metric Value
wmc 9
eloc 27
c 0
b 0
f 0
dl 0
loc 94
ccs 29
cts 31
cp 0.9355
rs 10

6 Methods

Rating   Name   Duplication   Size   Complexity  
A setPacketIdentifierFromRawHeaders() 0 7 1
A controlPacketIdentifiers() 0 20 2
A getPacketIdentifier() 0 7 2
A generateRandomPacketIdentifier() 0 15 2
A getPacketIdentifierBinaryRepresentation() 0 3 1
A setPacketIdentifier() 0 4 1
1
<?php
2
3
declare(strict_types=1);
4
5
namespace unreal4u\MQTT\Internals;
6
7
use Exception;
8
use OutOfRangeException;
9
use unreal4u\MQTT\DataTypes\PacketIdentifier;
10
use unreal4u\MQTT\Exceptions\NonMatchingPacketIdentifiers;
11
use unreal4u\MQTT\Utilities;
12
13
use function mt_rand;
14
15
/**
16
 * Trait ReadableContent
17
 * @package unreal4u\MQTT\Internals
18
 */
19
trait PacketIdentifierFunctionality
20
{
21
    /**
22
     * The packet identifier variable
23
     * @var PacketIdentifier
24
     */
25
    private $packetIdentifier;
26
27 24
    final public function setPacketIdentifier(PacketIdentifier $packetIdentifier): self
28
    {
29 24
        $this->packetIdentifier = $packetIdentifier;
30 24
        return $this;
31
    }
32
33 27
    final public function getPacketIdentifier(): int
34
    {
35 27
        if ($this->packetIdentifier === null) {
36 2
            $this->generateRandomPacketIdentifier();
37
        }
38
39 27
        return $this->packetIdentifier->getPacketIdentifierValue();
40
    }
41
42
    /**
43
     * Returns the binary representation of the packet identifier
44
     *
45
     * @return string
46
     * @throws OutOfRangeException
47
     */
48 11
    final public function getPacketIdentifierBinaryRepresentation(): string
49
    {
50 11
        return Utilities::convertNumberToBinaryString($this->getPacketIdentifier());
51
    }
52
53
    /**
54
     * Sets the packet identifier straight from the raw MQTT headers
55
     *
56
     * @param string $rawMQTTHeaders
57
     * @return self
58
     * @throws OutOfRangeException
59
     */
60 12
    final public function setPacketIdentifierFromRawHeaders(string $rawMQTTHeaders): self
61
    {
62 12
        $this->packetIdentifier = new PacketIdentifier(
63 12
            Utilities::convertBinaryStringToNumber($rawMQTTHeaders{2} . $rawMQTTHeaders{3})
64
        );
65
66 12
        return $this;
67
    }
68
69 2
    final public function generateRandomPacketIdentifier(): self
70
    {
71
        try {
72 2
            $this->packetIdentifier = new PacketIdentifier(random_int(1, 65535));
73
        } catch (Exception $e) {
74
            /*
75
             * Default to an older method, there should be no security issues here I believe.
76
             *
77
             * If I am mistaken, please contact me at https://t.me/unreal4u
78
             */
79
            /** @noinspection ExceptionsAnnotatingAndHandlingInspection */
80
            /** @noinspection RandomApiMigrationInspection */
81
            $this->packetIdentifier = new PacketIdentifier(mt_rand(1, 65535));
82
        }
83 2
        return $this;
84
    }
85
86
    /**
87
     * Checks whether the original request with the current stored packet identifier matches
88
     *
89
     * @param WritableContentInterface $originalRequest
90
     * @throws NonMatchingPacketIdentifiers
91
     * @return bool
92
     */
93 6
    private function controlPacketIdentifiers(WritableContentInterface $originalRequest): bool
94
    {
95
        /** @var PacketIdentifierFunctionality $originalRequest */
96 6
        if ($this->getPacketIdentifier() !== $originalRequest->getPacketIdentifier()) {
97 1
            $this->logger->critical('Non matching packet identifiers found, throwing exception', [
98 1
                'original' => $originalRequest->getPacketIdentifier(),
99 1
                'response' => $this->getPacketIdentifier(),
100
            ]);
101
102 1
            $e = new NonMatchingPacketIdentifiers(sprintf(
103 1
                'Packet identifiers do not match: %d (original) vs %d (response)',
104 1
                $originalRequest->getPacketIdentifier(),
105 1
                $this->getPacketIdentifier()
106
            ));
107 1
            $e->setOriginPacketIdentifier(new PacketIdentifier($originalRequest->getPacketIdentifier()));
108 1
            $e->setReturnedPacketIdentifier($this->packetIdentifier);
109 1
            throw $e;
110
        }
111
112 5
        return true;
113
    }
114
}
115