Passed
Push — master ( fc052b...13a97b )
by Camilo
02:52
created

Utilities   A

Complexity

Total Complexity 5

Size/Duplication

Total Lines 51
Duplicated Lines 0 %

Test Coverage

Coverage 100%

Importance

Changes 0
Metric Value
wmc 5
dl 0
loc 51
ccs 13
cts 13
cp 1
rs 10
c 0
b 0
f 0

3 Methods

Rating   Name   Duplication   Size   Complexity  
A convertBinaryStringToNumber() 0 3 1
A convertNumberToBinaryString() 0 7 2
A convertEndianness() 0 14 2
1
<?php
2
3
declare(strict_types=1);
4
5
namespace unreal4u\MQTT;
6
7
final class Utilities
8
{
9
    /**
10
     * Swaps the given number from endian format (INT16, not to be confused with UINT16)
11
     *
12
     * @param int $number
13
     * @return int
14
     * @throws \OutOfRangeException
15
     */
16 21
    public static function convertEndianness(int $number): int
17
    {
18 21
        if ($number > 65535) {
19 1
            throw new \OutOfRangeException('This is an INT16 conversion, so the maximum is 65535');
20
        }
21
22 20
        $finalNumber = hexdec(
23
            // Invert first byte and make it a complete hexadecimal number
24 20
            str_pad(dechex($number & 255), 2, '0', STR_PAD_LEFT) .
25
            // Invert second byte and make a complete hexadecimal number
26 20
            str_pad(dechex($number >> 8), 2, '0', STR_PAD_LEFT)
27
        );
28
29 20
        return (int)$finalNumber;
30
    }
31
32
    /**
33
     * Converts a number to a binary string that the MQTT protocol understands
34
     *
35
     * @param int $number
36
     * @return string
37
     * @throws \OutOfRangeException
38
     */
39 20
    public static function convertNumberToBinaryString(int $number): string
40
    {
41 20
        if ($number > 65535) {
42 1
            throw new \OutOfRangeException('This is an INT16 conversion, so the maximum is 65535');
43
        }
44
45 19
        return \chr($number >> 8) . \chr($number & 255);
46
    }
47
48
    /**
49
     * Converts a binary representation of a number to an actual int
50
     *
51
     * @param string $binaryString
52
     * @return int
53
     * @throws \OutOfRangeException
54
     */
55 12
    public static function convertBinaryStringToNumber(string $binaryString): int
56
    {
57 12
        return self::convertEndianness((\ord($binaryString{1}) << 8) + (\ord($binaryString{0}) & 255));
58
    }
59
}
60