IpSerializer::serialize()   A
last analyzed

Complexity

Conditions 1
Paths 1

Size

Total Lines 3
Code Lines 1

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 2

Importance

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