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

HeaderSerializer   A

Complexity

Total Complexity 4

Size/Duplication

Total Lines 61
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 6

Test Coverage

Coverage 90%

Importance

Changes 0
Metric Value
wmc 4
lcom 1
cbo 6
dl 0
loc 61
ccs 18
cts 20
cp 0.9
rs 10
c 0
b 0
f 0

4 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 6 1
A serialize() 0 10 1
A parse() 0 4 1
A fromParser() 0 8 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