Int8::getEndian()   A
last analyzed

Complexity

Conditions 1
Paths 1

Size

Total Lines 4
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 2
CRAP Score 1

Importance

Changes 0
Metric Value
dl 0
loc 4
ccs 2
cts 2
cp 1
rs 10
c 0
b 0
f 0
cc 1
eloc 2
nc 1
nop 0
crap 1
1
<?php
2
3
namespace PhpBinaryReader\Type;
4
5
use PhpBinaryReader\BinaryReader;
6
use PhpBinaryReader\BitMask;
7
8
class Int8 implements TypeInterface
9
{
10
    /**
11
     * @var string
12
     */
13
    private $endian = 'C';
14
15
    /**
16
     * Returns an Unsigned 8-bit Integer (aka a single byte)
17
     *
18
     * @param  \PhpBinaryReader\BinaryReader $br
19
     * @param  null                          $length
20
     * @return int
21
     * @throws \OutOfBoundsException
22
     */
23 50
    public function read(BinaryReader &$br, $length = null)
24
    {
25 50
        if (!$br->canReadBytes(1)) {
26 4
            throw new \OutOfBoundsException('Cannot read 8-bit int, it exceeds the boundary of the file');
27
        }
28
29 50
        $segment = $br->readFromHandle(1);
30
31 50
        $data = unpack($this->endian, $segment);
32 50
        $data = $data[1];
33
34 50
        if ($br->getCurrentBit() != 0) {
35 4
            $data = $this->bitReader($br, $data);
36
        }
37
38 50
        return $data;
39
    }
40
41
    /**
42
     * Returns a Signed 8-bit Integer (aka a single byte)
43
     *
44
     * @param  \PhpBinaryReader\BinaryReader $br
45
     * @return int
46
     */
47 40
    public function readSigned(&$br)
48
    {
49 40
        $this->setEndian('c');
50 40
        $value = $this->read($br);
51 40
        $this->setEndian('C');
52
53 40
        return $value;
54
    }
55
56
    /**
57
     * @param  \PhpBinaryReader\BinaryReader $br
58
     * @param  int                           $data
59
     * @return int
60
     */
61 4
    private function bitReader(&$br, $data)
62
    {
63 4
        $bitmask = new BitMask();
64 4
        $loMask = $bitmask->getMask($br->getCurrentBit(), BitMask::MASK_LO);
65 4
        $hiMask = $bitmask->getMask($br->getCurrentBit(), BitMask::MASK_HI);
66 4
        $hiBits = $br->getNextByte() & $hiMask;
67 4
        $loBits = $data & $loMask;
68 4
        $br->setNextByte($data);
69
70 4
        return $hiBits | $loBits;
71
    }
72
73
    /**
74
     * @param string $endian
75
     */
76 41
    public function setEndian($endian)
77
    {
78 41
        $this->endian = $endian;
79 41
    }
80
81
    /**
82
     * @return string
83
     */
84 1
    public function getEndian()
85
    {
86 1
        return $this->endian;
87
    }
88
}
89