Binary::returnValue()   A
last analyzed

Complexity

Conditions 2
Paths 2

Size

Total Lines 14
Code Lines 6

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 6
CRAP Score 2

Importance

Changes 0
Metric Value
cc 2
eloc 6
nc 2
nop 1
dl 0
loc 14
ccs 6
cts 6
cp 1
crap 2
rs 10
c 0
b 0
f 0
1
<?php
2
3
/*
4
 * This file is part of ocubom/base-convert
5
 *
6
 * © Oscar Cubo Medina <https://ocubom.github.io>
7
 *
8
 * For the full copyright and license information, please view the LICENSE
9
 * file that was distributed with this source code.
10
 */
11
12
namespace Ocubom\Math\Base;
13
14
use Ocubom\Math\Exception\RuntimeException;
15
16
class Binary extends Numeric
17
{
18 276
    public function __construct()
19
    {
20 276
        parent::__construct(16); // Uses Hex as internal format to use hex2bin and bin2hex functions
21
    }
22
23 136
    public function filterValue($value): string
24
    {
25 136
        return bin2hex((string) $value);
26
    }
27
28 136
    public function returnValue($value): string
29
    {
30
        // Must be left padded to force even length
31 136
        $len = strlen($value);
32 136
        $val = str_pad($value, $len + ($len % 2), '0', \STR_PAD_LEFT);
33
34
        // Perform conversion
35 136
        $val = \hex2bin($val);
36 136
        if (false === $val) {
37
            throw new RuntimeException(sprintf('Unable to convert "%s" to binary', $value)); // @codeCoverageIgnore
38
        }
39
40
        // Wipe unneeded starting 0
41 136
        return ltrim($val, "\0");
42
    }
43
}
44