Completed
Push — master ( 2dcc62...2dcc62 )
by thomas
151:35 queued 116:37
created

HeaderSerializer::fromParser()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 8
Code Lines 5

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
dl 0
loc 8
rs 9.4285
c 1
b 0
f 0
cc 1
eloc 5
nc 1
nop 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
    public function __construct()
29
    {
30
        $this->bytestring12 = Types::bytestring(12);
31
        $this->bytestring4 = Types::bytestring(4);
32
        $this->uint32 = Types::uint32le();
33
    }
34
35
    /**
36
     * @param Header $header
37
     * @return Buffer
38
     */
39
    public function serialize(Header $header)
40
    {
41
        $command = new Buffer(str_pad($header->getCommand(), 12, "\x00", STR_PAD_RIGHT));
42
43
        return new Buffer(
44
            $this->bytestring12->write($command).
45
            $this->uint32->write($header->getLength()).
46
            $this->bytestring4->write($header->getChecksum())
47
        );
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
    public function fromParser(Parser $parser)
64
    {
65
        return new Header(
66
            trim($this->bytestring12->read($parser)->getBinary()),
67
            $this->uint32->read($parser),
68
            $this->bytestring4->read($parser)
69
        );
70
    }
71
}
72