DebugTools   A
last analyzed

Complexity

Total Complexity 5

Size/Duplication

Total Lines 42
Duplicated Lines 0 %

Test Coverage

Coverage 100%

Importance

Changes 1
Bugs 0 Features 0
Metric Value
wmc 5
eloc 14
dl 0
loc 42
ccs 16
cts 16
cp 1
rs 10
c 1
b 0
f 0

2 Methods

Rating   Name   Duplication   Size   Complexity  
A convertToBinaryRepresentation() 0 12 2
A convertBinaryToString() 0 13 3
1
<?php
2
3
declare(strict_types=1);
4
5
namespace unreal4u\MQTT;
6
7
use function base64_encode;
8
use function base_convert;
9
use function chr;
10
use function ord;
11
use function sprintf;
12
use function strlen;
13
use function substr;
14
15
/**
16
 * Collection of function that have proven useful while debugging issues and creating unit tests
17
 * @package unreal4u\MQTT
18
 */
19
final class DebugTools
20
{
21
    /**
22
     * Handy debugging function
23
     *
24
     * @param string $rawString
25
     * @return string
26
     */
27 3
    public static function convertToBinaryRepresentation(string $rawString): string
28
    {
29 3
        $out = '';
30 3
        $strLength = strlen($rawString);
31 3
        for ($a = 0; $a < $strLength; $a++) {
32 3
            $dec = ord($rawString[$a]); //determine symbol ASCII-code
33
            //convert to binary representation and add leading zeros
34 3
            $bin = sprintf('%08d', base_convert((string)$dec, 10, 2));
35 3
            $out .= $bin;
36
        }
37
38 3
        return $out;
39
    }
40
41
    /**
42
     * Handy debugging function
43
     *
44
     * @param string $binaryRepresentation
45
     * @param bool $applyBase64
46
     * @return string
47
     */
48 2
    public static function convertBinaryToString(string $binaryRepresentation, bool $applyBase64 = false): string
49
    {
50 2
        $output = '';
51 2
        $binaryStringLength = strlen($binaryRepresentation);
52 2
        for ($i = 0; $i < $binaryStringLength; $i += 8) {
53 2
            $output .= chr((int)base_convert(substr($binaryRepresentation, $i, 8), 2, 10));
54
        }
55
56 2
        if ($applyBase64 === true) {
57 1
            return base64_encode($output);
58
        }
59
60 1
        return $output;
61
    }
62
}
63