Passed
Push — master ( 3dc4f8...535c32 )
by thomas
15:05
created

NetworkAddressSerializer::fromParser()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 8
Code Lines 5

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 2
CRAP Score 1

Importance

Changes 0
Metric Value
cc 1
eloc 5
nc 1
nop 1
dl 0
loc 8
ccs 2
cts 2
cp 1
crap 1
rs 9.4285
c 0
b 0
f 0
1
<?php
2
3
declare(strict_types=1);
4
5
namespace BitWasp\Bitcoin\Networking\Serializer\Structure;
6
7
use BitWasp\Bitcoin\Networking\Serializer\Ip\IpSerializer;
8
use BitWasp\Bitcoin\Networking\Structure\NetworkAddress;
9
use BitWasp\Bitcoin\Serializer\Types;
10
use BitWasp\Buffertools\Buffer;
11
use BitWasp\Buffertools\BufferInterface;
12
use BitWasp\Buffertools\Parser;
13
14
class NetworkAddressSerializer
15
{
16 27
    /**
17
     * @var \BitWasp\Buffertools\Types\Uint16
18 27
     */
19 27
    private $uint16;
20 27
21 27
    /**
22 27
     * @var \BitWasp\Buffertools\Types\Uint64
23
     */
24
    private $uint64le;
25
26
    /**
27
     * @var \BitWasp\Buffertools\Types\ByteString
28
     */
29 27
    private $bytestring16;
30
31 27
    public function __construct()
32 27
    {
33 27
        $this->uint16 = Types::uint16();
34 27
        $this->uint64le = Types::uint64le();
35 18
        $this->bytestring16 = Types::bytestring(16);
36
    }
37
38
    /**
39
     * @param NetworkAddress $addr
40
     * @return BufferInterface
41
     */
42 15
    public function serialize(NetworkAddress $addr): BufferInterface
43
    {
44 15
        $services = $this->uint64le->write($addr->getServices());
45 15
        $ip = $addr->getIp()->getBuffer()->getBinary();
46 15
        $port = $this->uint16->write($addr->getPort());
47 10
        return new Buffer("{$services}{$ip}{$port}");
48 15
    }
49
50 10
    /**
51
     * @param Parser $parser
52
     * @return NetworkAddress
53
     */
54
    public function fromParser(Parser $parser): NetworkAddress
55
    {
56
        // @todo: move this into constructor param?
57 15
        $ipSerializer = new IpSerializer();
58
        return new NetworkAddress(
59 15
            (int) $this->uint64le->read($parser),
60
            $ipSerializer->fromParser($parser),
61
            (int) $this->uint16->read($parser)
62
        );
63
    }
64
65
    /**
66
     * @param BufferInterface $data
67
     * @return NetworkAddress
68
     */
69
    public function parse(BufferInterface $data): NetworkAddress
70
    {
71
        return $this->fromParser(new Parser($data));
72
    }
73
}
74