Completed
Pull Request — master (#56)
by thomas
33:43 queued 31:29
created

IpSerializer::parse()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 4
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 2
CRAP Score 1

Importance

Changes 1
Bugs 0 Features 1
Metric Value
c 1
b 0
f 1
dl 0
loc 4
ccs 2
cts 2
cp 1
rs 10
cc 1
eloc 2
nc 1
nop 1
crap 1
1
<?php
2
3
namespace BitWasp\Bitcoin\Networking\Serializer\Ip;
4
5
use Base32\Base32;
6
use BitWasp\Bitcoin\Networking\Ip\IpInterface;
7
use BitWasp\Bitcoin\Networking\Ip\Ipv4;
8
use BitWasp\Bitcoin\Networking\Ip\Ipv6;
9
use BitWasp\Bitcoin\Networking\Ip\Onion;
10
use BitWasp\Buffertools\Parser;
11
12
class IpSerializer
13
{
14
    /**
15
     * @param Parser $parser
16
     * @return Ipv4|Ipv6|Onion
17
     * @throws \BitWasp\Buffertools\Exceptions\ParserOutOfRange
18
     * @throws \Exception
19
     */
20 9
    public function fromParser(Parser $parser)
21
    {
22 9
        $buffer = $parser->readBytes(16);
23 9
        $binary = $buffer->getBinary();
24
25 9
        if (Onion::MAGIC === substr($binary, 0, strlen(Onion::MAGIC))) {
26 3
            $addr = strtolower(Base32::encode($buffer->slice(strlen(Onion::MAGIC))->getBinary())) . '.onion';
27 3
            $ip = new Onion($addr);
28 9
        } elseif (Ipv4::MAGIC === substr($binary, 0, strlen(Ipv4::MAGIC))) {
29 3
            $end = $buffer->slice(strlen(Ipv4::MAGIC), 4);
30 3
            $ip = new Ipv4(long2ip($end->getInt()));
31 3
        } else {
32 3
            $addr = [];
33 3
            foreach (str_split($binary, 2) as $segment) {
34 3
                $addr[] = bin2hex($segment);
35 3
            }
36
37 3
            $addr = implode(":", $addr);
38 3
            $ip = new Ipv6($addr);
39
        }
40
41 9
        return $ip;
42
    }
43
44
    /**
45
     * @param $data
46
     * @return Ipv4|Ipv6|Onion
47
     */
48 9
    public function parse($data)
49
    {
50 9
        return $this->fromParser(new Parser($data));
51
    }
52
53
    /**
54
     * @param IpInterface $address
55
     * @return \BitWasp\Buffertools\Buffer
56
     */
57 9
    public function serialize(IpInterface $address)
58
    {
59 9
        return $address->getBuffer();
60
    }
61
}
62