Passed
Push — master ( f9782b...101280 )
by Camilo
02:34
created

PacketIdentifier::getBinaryRepresentation()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 3
Code Lines 1

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 2

Importance

Changes 0
Metric Value
dl 0
loc 3
ccs 0
cts 2
cp 0
rs 10
c 0
b 0
f 0
cc 1
eloc 1
nc 1
nop 0
crap 2
1
<?php
2
3
declare(strict_types=1);
4
5
namespace unreal4u\MQTT\Internals;
6
7
use unreal4u\MQTT\DataTypes\PacketIdentifier as PacketIdentifierDataType;
8
use unreal4u\MQTT\Utilities;
9
10
/**
11
 * Trait ReadableContent
12
 * @package unreal4u\MQTT\Internals
13
 */
14
trait PacketIdentifier
15
{
16
    /**
17
     * The packet identifier variable
18
     * @var PacketIdentifierDataType
19
     */
20
    private $packetIdentifier = 0;
21
22
    final public function setPacketIdentifier(PacketIdentifierDataType $packetIdentifier): self
23
    {
24
        $this->packetIdentifier = $packetIdentifier;
25
        return $this;
26
    }
27
28
    final public function getPacketIdentifier(): int
29
    {
30
        return $this->packetIdentifier->getPacketIdentifierValue();
31
    }
32
33
    /**
34
     * Returns the binary representation of the packet identifier
35
     *
36
     * @return string
37
     * @throws \OutOfRangeException
38
     */
39
    final public function getBinaryRepresentation(): string
40
    {
41
        return Utilities::convertNumberToBinaryString($this->packetIdentifier->getPacketIdentifierValue());
42
    }
43
44
    final public function generateRandomPacketIdentifier(): self
45
    {
46
        try {
47
            $this->packetIdentifier = new PacketIdentifierDataType(random_int(1, 65535));
48
        } catch (\Exception $e) {
49
            /*
50
             * Default to an older method, there should be no security issues here I believe.
51
             *
52
             * If I am mistaken, please contact me at https://t.me/unreal4u
53
             */
54
            /** @noinspection ExceptionsAnnotatingAndHandlingInspection */
55
            /** @noinspection RandomApiMigrationInspection */
56
            $this->packetIdentifier = new PacketIdentifierDataType(mt_rand(1, 65535));
57
        }
58
        return $this;
59
    }
60
}
61