Passed
Push — master ( c1e68f...f0bd78 )
by Sam
01:33 queued 10s
created

RdataTrait::decodeName()   B

Complexity

Conditions 6
Paths 14

Size

Total Lines 37
Code Lines 23

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 24
CRAP Score 6

Importance

Changes 0
Metric Value
cc 6
eloc 23
nc 14
nop 2
dl 0
loc 37
ccs 24
cts 24
cp 1
crap 6
rs 8.9297
c 0
b 0
f 0
1
<?php
2
3
declare(strict_types=1);
4
5
/*
6
 * This file is part of Badcow DNS Library.
7
 *
8
 * (c) Samuel Williams <[email protected]>
9
 *
10
 * For the full copyright and license information, please view the LICENSE
11
 * file that was distributed with this source code.
12
 */
13
14
namespace Badcow\DNS\Rdata;
15
16
trait RdataTrait
17
{
18
    /**
19
     * {@inheritdoc}
20
     */
21 43
    public function getType(): string
22
    {
23
        /* @const TYPE */
24 43
        return static::TYPE;
25
    }
26
27
    /**
28
     * {@inheritdoc}
29
     */
30 17
    public function getTypeCode(): int
31
    {
32
        /* @const TYPE_CODE */
33 17
        return static::TYPE_CODE;
34
    }
35
36
    /**
37
     * Encode a domain name as a sequence of labels.
38
     *
39
     * @param string $name
40
     *
41
     * @return string
42
     */
43 38
    public static function encodeName(string $name): string
44
    {
45 38
        if ('.' === $name) {
46 3
            return chr(0);
47
        }
48
49 35
        $name = rtrim($name, '.').'.';
50 35
        $res = '';
51
52 35
        foreach (explode('.', $name) as $label) {
53 35
            $res .= chr(strlen($label)).$label;
54
        }
55
56 35
        return $res;
57
    }
58
59
    /**
60
     * @param string $string
61
     * @param int    $offset
62
     *
63
     * @return string
64
     */
65 30
    public static function decodeName(string $string, int &$offset = 0): string
66
    {
67 30
        $len = ord($string[$offset]);
68 30
        ++$offset;
69
70 30
        $isCompressed = (bool) (0b11000000 & $len);
71 30
        $_offset = 0;
72
73 30
        if ($isCompressed) {
74 7
            $_offset = $offset + 1;
75 7
            $offset = (0b00111111 & $len) * 256 + ord($string[$offset]);
76 7
            $len = ord($string[$offset]);
77 7
            ++$offset;
78
        }
79
80 30
        if (0 === $len) {
81 3
            return '.';
82
        }
83
84 27
        $name = '';
85 27
        while (0 !== $len) {
86 27
            $name .= substr($string, $offset, $len).'.';
87 27
            $offset += $len;
88 27
            $len = ord($string[$offset]);
89 27
            if ($len & 0b11000000) {
90 7
                $name .= self::decodeName($string, $offset);
91 7
                break;
92
            }
93
94 27
            ++$offset;
95
        }
96
97 27
        if ($isCompressed) {
98 7
            $offset = $_offset;
99
        }
100
101 27
        return $name;
102
    }
103
}
104