Completed
Branch Version3 (b9f3d9)
by Sam
02:31
created

Classes::getClassName()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 7
Code Lines 3

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 4
CRAP Score 2

Importance

Changes 0
Metric Value
cc 2
eloc 3
nc 2
nop 1
dl 0
loc 7
ccs 4
cts 4
cp 1
crap 2
rs 10
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;
15
16
class Classes
17
{
18
    const INTERNET = 'IN';
19
    const CSNET = 'CS';
20
    const CHAOS = 'CH';
21
    const HESIOD = 'HS';
22
23
    /**
24
     * @var array
25
     */
26
    public static $classes = [
27
        self::CHAOS => 'CHAOS',
28
        self::CSNET => 'CSNET',
29
        self::HESIOD => 'Hesiod',
30
        self::INTERNET => 'Internet',
31
    ];
32
33
    const CLASS_IDS = [
34
        self::CHAOS => 3,
35
        self::CSNET => 2,
36
        self::HESIOD => 4,
37
        self::INTERNET => 1,
38
    ];
39
40
    /**
41
     * @const string[]
42
     */
43
    const IDS_CLASSES = [
44
        1 => 'IN',
45
        2 => 'CS',
46
        3 => 'CH',
47
        4 => 'HS',
48
    ];
49
50
    /**
51
     * Determine if a class is valid.
52
     *
53
     * @param string $class
54
     *
55
     * @return bool
56
     */
57 38
    public static function isValid(string $class): bool
58
    {
59 38
        if (array_key_exists($class, self::$classes)) {
60 36
            return true;
61
        }
62
63 23
        if (1 === preg_match('/^CLASS\d+$/', $class)) {
64 1
            return true;
65
        }
66
67 23
        return false;
68
    }
69
70
    /**
71
     * @param string $className
72
     *
73
     * @return int
74
     *
75
     * @throws \InvalidArgumentException
76
     */
77 35
    public static function getClassId(string $className): int
78
    {
79 35
        if (!self::isValid($className)) {
80 1
            throw new \InvalidArgumentException(sprintf('Class "%s" is not a valid DNS class.', $className));
81
        }
82
83 34
        if (1 === preg_match('/^CLASS(\d+)$/', $className, $matches)) {
84 1
            return (int) $matches[1];
85
        }
86
87 34
        return self::CLASS_IDS[$className];
88
    }
89
90
    /**
91
     * @param int $classId
92
     *
93
     * @return string
94
     */
95 27
    public static function getClassName(int $classId): string
96
    {
97 27
        if (array_key_exists($classId, self::IDS_CLASSES)) {
98 27
            return self::IDS_CLASSES[$classId];
99
        }
100
101 1
        return 'CLASS'.$classId;
102
    }
103
}
104