Completed
Push — master ( 00a863...d2dd08 )
by thomas
50:05 queued 12:04
created

IpSerializer::serialize()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 4
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 1
Metric Value
c 1
b 0
f 1
dl 0
loc 4
rs 10
cc 1
eloc 2
nc 1
nop 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
    public function fromParser(Parser $parser)
21
    {
22
        $buffer = $parser->readBytes(16);
23
        $binary = $buffer->getBinary();
24
25
        if (Onion::MAGIC === substr($binary, 0, strlen(Onion::MAGIC))) {
26
            $addr = strtolower(Base32::encode($buffer->slice(strlen(Onion::MAGIC))->getBinary())) . '.onion';
27
            $ip = new Onion($addr);
28
        } elseif (Ipv4::MAGIC === substr($binary, 0, strlen(Ipv4::MAGIC))) {
29
            $end = $buffer->slice(strlen(Ipv4::MAGIC), 4);
30
            $ip = new Ipv4(long2ip($end->getInt()));
31
        } else {
32
            $addr = [];
33
            foreach (str_split($binary, 2) as $segment) {
34
                $addr[] = bin2hex($segment);
35
            }
36
37
            $addr = implode(":", $addr);
38
            $ip = new Ipv6($addr);
39
        }
40
41
        return $ip;
42
    }
43
44
    /**
45
     * @param $data
46
     * @return Ipv4|Ipv6|Onion
47
     */
48
    public function parse($data)
49
    {
50
        return $this->fromParser(new Parser($data));
51
    }
52
53
    /**
54
     * @param IpInterface $address
55
     * @return \BitWasp\Buffertools\Buffer
56
     */
57
    public function serialize(IpInterface $address)
58
    {
59
        return $address->getBuffer();
60
    }
61
}
62