Completed
Pull Request — master (#81)
by thomas
02:07
created

HeaderSerializer::__construct()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 6
Code Lines 4

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 5
CRAP Score 1

Importance

Changes 0
Metric Value
dl 0
loc 6
ccs 5
cts 5
cp 1
rs 9.4285
c 0
b 0
f 0
cc 1
eloc 4
nc 1
nop 0
crap 1
1
<?php
2
3
namespace BitWasp\Bitcoin\Networking\Serializer\Structure;
4
5
use BitWasp\Bitcoin\Networking\Structure\Header;
6
use BitWasp\Bitcoin\Serializer\Types;
7
use BitWasp\Buffertools\Buffer;
8
use BitWasp\Buffertools\BufferInterface;
9
use BitWasp\Buffertools\Parser;
10
11
class HeaderSerializer
12
{
13
    /**
14
     * @var \BitWasp\Buffertools\Types\ByteString
15
     */
16
    private $bytestring12;
17
18
    /**
19
     * @var \BitWasp\Buffertools\Types\ByteString
20
     */
21
    private $bytestring4;
22
23
    /**
24
     * @var \BitWasp\Buffertools\Types\Uint32
25
     */
26
    private $uint32;
27
28 96
    public function __construct()
29
    {
30 96
        $this->bytestring12 = Types::bytestring(12);
31 96
        $this->bytestring4 = Types::bytestring(4);
32 96
        $this->uint32 = Types::uint32le();
33 96
    }
34
35
    /**
36
     * @param Header $header
37
     * @return Buffer
38
     */
39 93
    public function serialize(Header $header)
40
    {
41 93
        $command = new Buffer(str_pad($header->getCommand(), 12, "\x00", STR_PAD_RIGHT));
42
43 93
        return new Buffer(
44 93
            $this->bytestring12->write($command).
45 93
            $this->uint32->write($header->getLength()).
46 93
            $this->bytestring4->write($header->getChecksum())
47 31
        );
48
    }
49
50
    /**
51
     * @param string|BufferInterface $data
52
     * @return Header
53
     */
54
    public function parse($data)
55
    {
56
        return $this->fromParser(new Parser($data));
57
    }
58
59
    /**
60
     * @param Parser $parser
61
     * @return Header
62
     */
63 87
    public function fromParser(Parser $parser)
64
    {
65 87
        return new Header(
66 87
            trim($this->bytestring12->read($parser)->getBinary()),
67 87
            $this->uint32->read($parser),
68 87
            $this->bytestring4->read($parser)
69 29
        );
70
    }
71
}
72