Completed
Push — master ( 0df7a1...55f7a9 )
by Christian
07:49
created

DataAbstract::createFromTypeAndString()   B

Complexity

Conditions 6
Paths 6

Size

Total Lines 35
Code Lines 20

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 6
eloc 20
nc 6
nop 2
dl 0
loc 35
rs 8.9777
c 0
b 0
f 0
1
<?php
2
namespace RemotelyLiving\PHPDNS\Entities;
3
4
use RemotelyLiving\PHPDNS\Entities\Interfaces\Arrayable;
5
use RemotelyLiving\PHPDNS\Entities\Interfaces\Serializable;
6
use RemotelyLiving\PHPDNS\Exceptions\InvalidArgumentException;
7
8
abstract class DataAbstract implements Arrayable, Serializable
9
{
10
    abstract public function __toString();
11
12
    public function equals(DataAbstract $dataAbstract): bool
13
    {
14
        return (string)$this === (string)$dataAbstract;
15
    }
16
17
    public static function createFromTypeAndString(DNSRecordType $recordType, string $data): self
18
    {
19
        if ($recordType->isA(DNSRecordType::TYPE_TXT)) {
20
            return new TXTData($data);
21
        }
22
23
        if ($recordType->isA(DNSRecordType::TYPE_MX)) {
24
            $exploded = explode(' ', $data);
25
26
            return new MXData(new Hostname($exploded[1]), (int)$exploded[0]);
27
        }
28
29
        if ($recordType->isA(DNSRecordType::TYPE_SOA)) {
30
            $exploded = explode(' ', $data);
31
32
            return new SOAData(
33
                new Hostname($exploded[0]),
34
                new Hostname($exploded[1]),
35
                (int)$exploded[2] ?? 0,
36
                (int)$exploded[3] ?? 0,
37
                (int)$exploded[4] ?? 0,
38
                (int)$exploded[5] ?? 0,
39
                (int)$exploded[6] ?? 0
40
            );
41
        }
42
43
        if ($recordType->isA(DNSRecordType::TYPE_NS)) {
44
            return new NSData(new Hostname($data));
45
        }
46
47
        if ($recordType->isA(DNSRecordType::TYPE_CNAME)) {
48
            return new CNAMEData(new Hostname($data));
49
        }
50
51
        throw new InvalidArgumentException("{$data} could not be created with type {$recordType}");
52
    }
53
}
54