Completed
Push — master ( b7c903...d00047 )
by Camilo
02:08
created

DebugTools::convertToBinaryRepresentation()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 11
Code Lines 7

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 6

Importance

Changes 0
Metric Value
dl 0
loc 11
ccs 0
cts 8
cp 0
rs 9.4285
c 0
b 0
f 0
cc 2
eloc 7
nc 2
nop 1
crap 6
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
    public static function convertToBinaryRepresentation(string $rawString): string
16
    {
17
        $out = null;
18
        $strLength = \strlen($rawString);
19
        for ($a = 0; $a < $strLength; $a++) {
20
            $dec = \ord($rawString[$a]); //determine symbol ASCII-code
21
            $bin = sprintf('%08d', base_convert($dec, 10, 2)); //convert to binary representation and add leading zeros
22
            $out .= $bin;
23
        }
24
25
        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
    public static function convertBinaryToString(string $binaryRepresentation, bool $applyBase64 = false): string
36
    {
37
        $output = '';
38
        $binaryStringLength = \strlen($binaryRepresentation);
39
        for ($i = 0; $i < $binaryStringLength; $i += 8) {
40
            $output .= \chr(base_convert(substr($binaryRepresentation, $i, 8), 2, 10));
0 ignored issues
show
Bug introduced by
base_convert(substr($bin...ntation, $i, 8), 2, 10) of type string is incompatible with the type integer expected by parameter $ascii of chr(). ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

40
            $output .= \chr(/** @scrutinizer ignore-type */ base_convert(substr($binaryRepresentation, $i, 8), 2, 10));
Loading history...
41
        }
42
43
        if ($applyBase64 === true) {
44
            return base64_encode($output);
45
        }
46
47
        return $output;
48
    }
49
}
50