ReadableBinaryData::__toString()   A
last analyzed

Complexity

Conditions 4
Paths 6

Size

Total Lines 13
Code Lines 7

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 8
CRAP Score 4

Importance

Changes 0
Metric Value
dl 0
loc 13
ccs 8
cts 8
cp 1
rs 9.2
c 0
b 0
f 0
cc 4
eloc 7
nc 6
nop 0
crap 4
1
<?php
2
3
namespace ButterAMQP\Debug;
4
5
class ReadableBinaryData
6
{
7
    /**
8
     * @var string
9
     */
10
    private $label;
11
12
    /**
13
     * @var string
14
     */
15
    private $data;
16
17
    /**
18
     * @param string $label
19
     * @param string $data
20
     */
21 3
    public function __construct($label, $data)
22
    {
23 3
        $this->label = $label;
24 3
        $this->data = $data;
25 3
    }
26
27
    /**
28
     * Renders binary data into a string.
29
     *
30
     * @return string
31
     */
32 1
    public function __toString()
33
    {
34 1
        $length = mb_strlen($this->data, 'ASCII');
35
36 1
        $hex = [];
37
38 1
        for ($p = 0; $p < $length; ++$p) {
39 1
            $char = $this->data[$p];
40 1
            $hex[] = ord($char).(self::isPrintable($char) ? "[$char]" : '');
41 1
        }
42
43 1
        return ($this->label ? $this->label.' ' : '').$length.' bytes: '.implode(' ', $hex);
44
    }
45
46
    /**
47
     * @param string $char
48
     *
49
     * @return bool
50
     */
51 1
    private static function isPrintable($char)
52
    {
53 1
        return strpos(' !"#$%&\'()*+,-./0123456789:;<=>?@[]^_`abcdefghijklmnopqrstuvwxyz{|}~', strtolower($char)) !== false;
54
    }
55
}
56