BitStreamWriter::__construct()   A
last analyzed

Complexity

Conditions 1
Paths 1

Size

Total Lines 3
Code Lines 1

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
eloc 1
dl 0
loc 3
rs 10
c 1
b 0
f 0
cc 1
nc 1
nop 0
1
<?php
2
3
namespace Mfonte\Base62x\Compression\Huffman\Binary;
4
5
/**
6
 *	a mechanism for writing a stream if bits into a string, which can then be easily transmistted or stored.
7
 */
8
class BitStreamWriter
9
{
10
    private $data = '';
11
    private $workingByte = null;
12
    private $cursor = 0;
13
14
    /**
15
     *	initialize be creating our working byte / buffer.
16
     */
17
    public function __construct()
18
    {
19
        $this->workingByte = new BitArray(8);
20
    }
21
22
    /**
23
     * 	convert a string of zeroes and ones into a binary representation.
24
     */
25
    public function writeString($bitStr)
26
    {
27
        for ($i = 0; $i < mb_strlen($bitStr); ++$i) {
28
            $this->writeBit((bool) $bitStr[$i]);
29
        }
30
    }
31
32
    /**
33
     * 	write a bit. 1 if $bit is true.
34
     */
35
    public function writeBit($bit)
36
    {
37
        $this->workingByte[$this->cursor] = $bit;
38
        ++$this->cursor;
39
        if ($this->cursor > 7) {
40
            $this->data .= $this->workingByte->getData();
41
            $this->workingByte = new BitArray(8);
42
            $this->cursor = 0;
43
        }
44
    }
45
46
    /**
47
     * 	when the data is accessed, make sure to include any data
48
     * 	byte in $this->workingByte.
49
     */
50
    public function getData()
51
    {
52
        $data = $this->data;
53
        if ($this->cursor > 0) {
54
            $data .= $this->workingByte->getData();
55
        }
56
57
        return $data;
58
    }
59
}
60