Passed
Push — master ( d00047...c0d95e )
by Camilo
02:17
created

DebugTools::convertToBinaryRepresentation()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 11
Code Lines 7

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 8
CRAP Score 2

Importance

Changes 0
Metric Value
dl 0
loc 11
ccs 8
cts 8
cp 1
rs 9.4285
c 0
b 0
f 0
cc 2
eloc 7
nc 2
nop 1
crap 2
1
<?php
2
3
declare(strict_types=1);
4
5
namespace unreal4u\MQTT;
6
7
final class DebugTools
8
{
9
    /**
10
     * Handy debugging function
11
     *
12
     * @param string $rawString
13
     * @return string
14
     */
15 1
    public static function convertToBinaryRepresentation(string $rawString): string
16
    {
17 1
        $out = null;
18 1
        $strLength = \strlen($rawString);
19 1
        for ($a = 0; $a < $strLength; $a++) {
20 1
            $dec = \ord($rawString[$a]); //determine symbol ASCII-code
21 1
            $bin = sprintf('%08d', base_convert($dec, 10, 2)); //convert to binary representation and add leading zeros
22 1
            $out .= $bin;
23
        }
24
25 1
        return $out;
0 ignored issues
show
Bug Best Practice introduced by
The expression return $out could return the type null which is incompatible with the type-hinted return string. Consider adding an additional type-check to rule them out.
Loading history...
26
    }
27
28
    /**
29
     * Handy debugging function
30
     *
31
     * @param string $binaryRepresentation
32
     * @param bool $applyBase64
33
     * @return string
34
     */
35 2
    public static function convertBinaryToString(string $binaryRepresentation, bool $applyBase64 = false): string
36
    {
37 2
        $output = '';
38 2
        $binaryStringLength = \strlen($binaryRepresentation);
39 2
        for ($i = 0; $i < $binaryStringLength; $i += 8) {
40 2
            $output .= \chr((int)base_convert(substr($binaryRepresentation, $i, 8), 2, 10));
41
        }
42
43 2
        if ($applyBase64 === true) {
44 1
            return base64_encode($output);
45
        }
46
47 1
        return $output;
48
    }
49
}
50