AbstractType::flipBits()   A
last analyzed

Complexity

Conditions 3
Paths 3

Size

Total Lines 15

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 8
CRAP Score 3

Importance

Changes 0
Metric Value
dl 0
loc 15
ccs 8
cts 8
cp 1
rs 9.7666
c 0
b 0
f 0
cc 3
nc 3
nop 1
crap 3
1
<?php
2
3
declare(strict_types=1);
4
5
namespace BitWasp\Buffertools\Types;
6
7
use BitWasp\Buffertools\ByteOrder;
8
9
abstract class AbstractType implements TypeInterface
10
{
11
    /**
12
     * @var int
13
     */
14
    private $byteOrder;
15
16
    /**
17
     * @param int                  $byteOrder
18
     */
19 198
    public function __construct(int $byteOrder = ByteOrder::BE)
20
    {
21 198
        if (false === in_array($byteOrder, [ByteOrder::BE, ByteOrder::LE])) {
22 2
            throw new \InvalidArgumentException('Must pass valid flag for endianness');
23
        }
24
25 196
        $this->byteOrder = $byteOrder;
26 196
    }
27
28
    /**
29
     * @return int
30
     */
31 150
    public function getByteOrder(): int
32
    {
33 150
        return $this->byteOrder;
34
    }
35
36
    /**
37
     * @return bool
38
     */
39 128
    public function isBigEndian(): bool
40
    {
41 128
        return $this->getByteOrder() == ByteOrder::BE;
42
    }
43
44
    /**
45
     * @param string $bitString
46
     * @return string
47
     * @throws \Exception
48
     */
49 64
    public function flipBits(string $bitString): string
50
    {
51 64
        $length = strlen($bitString);
52
53 64
        if ($length % 8 !== 0) {
54 2
            throw new \Exception('Bit string length must be a multiple of 8');
55
        }
56
57 62
        $newString = '';
58 62
        for ($i = $length; $i >= 0; $i -= 8) {
59 62
            $newString .= substr($bitString, $i, 8);
60
        }
61
62 62
        return $newString;
63
    }
64
}
65