Completed
Branch Message (d15af3)
by Sam
05:12
created

RdataTrait   A

Complexity

Total Complexity 11

Size/Duplication

Total Lines 86
Duplicated Lines 0 %

Test Coverage

Coverage 100%

Importance

Changes 1
Bugs 0 Features 0
Metric Value
eloc 33
dl 0
loc 86
ccs 36
cts 36
cp 1
rs 10
c 1
b 0
f 0
wmc 11

4 Methods

Rating   Name   Duplication   Size   Complexity  
A getTypeCode() 0 4 1
A getType() 0 4 1
A encodeName() 0 14 3
B decodeName() 0 37 6
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 15
    public function getTypeCode(): int
31
    {
32
        /* @const TYPE_CODE */
33 15
        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 32
    public static function encodeName(string $name): string
44
    {
45 32
        if ('.' === $name) {
46 2
            return chr(0);
47
        }
48
49 30
        $name = rtrim($name, '.').'.';
50 30
        $res = '';
51
52 30
        foreach (explode('.', $name) as $label) {
53 30
            $res .= chr(strlen($label)).$label;
54
        }
55
56 30
        return $res;
57
    }
58
59
    /**
60
     * @param string $string
61
     * @param int    $offset
62
     *
63
     * @return string
64
     */
65 24
    public static function decodeName(string $string, int &$offset = 0): string
66
    {
67 24
        $len = ord($string[$offset]);
68 24
        ++$offset;
69
70 24
        $isCompressed = (bool) (0b11000000 & $len);
71 24
        $_offset = 0;
72
73 24
        if ($isCompressed) {
74 4
            $_offset = $offset + 1;
75 4
            $offset = (0b00111111 & $len) * 256 + ord($string[$offset]);
76 4
            $len = ord($string[$offset]);
77 4
            ++$offset;
78
        }
79
80 24
        if (0 === $len) {
81 2
            return '.';
82
        }
83
84 22
        $name = '';
85 22
        while (0 !== $len) {
86 22
            $name .= substr($string, $offset, $len).'.';
87 22
            $offset += $len;
88 22
            $len = ord($string[$offset]);
89 22
            if ($len & 0b11000000) {
90 4
                $name .= self::decodeName($string, $offset);
91 4
                break;
92
            }
93
94 22
            ++$offset;
95
        }
96
97 22
        if ($isCompressed) {
98 4
            $offset = $_offset;
99
        }
100
101 22
        return $name;
102
    }
103
}
104