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

IpSerializer   A

Complexity

Total Complexity 6

Size/Duplication

Total Lines 50
Duplicated Lines 0 %

Coupling/Cohesion

Components 0
Dependencies 7

Test Coverage

Coverage 100%

Importance

Changes 2
Bugs 0 Features 1
Metric Value
wmc 6
c 2
b 0
f 1
lcom 0
cbo 7
dl 0
loc 50
ccs 21
cts 21
cp 1
rs 10

3 Methods

Rating   Name   Duplication   Size   Complexity  
B fromParser() 0 23 4
A parse() 0 4 1
A serialize() 0 4 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