1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
namespace Spatie\Dns; |
4
|
|
|
|
5
|
|
|
use Exception; |
6
|
|
|
use Symfony\Component\Process\Process; |
7
|
|
|
use Spatie\Dns\Exceptions\InvalidArgument; |
8
|
|
|
|
9
|
|
|
class Dns |
10
|
|
|
{ |
11
|
|
|
protected $domain = ''; |
12
|
|
|
|
13
|
|
|
protected $recordTypes = [ |
14
|
|
|
'A', |
15
|
|
|
'AAAA', |
16
|
|
|
'NS', |
17
|
|
|
'SOA', |
18
|
|
|
'MX', |
19
|
|
|
'TXT', |
20
|
|
|
'DNSKEY', |
21
|
|
|
]; |
22
|
|
|
|
23
|
|
|
public function __construct(string $domain) |
24
|
|
|
{ |
25
|
|
|
if ($domain === '') { |
26
|
|
|
throw InvalidArgument::domainIsMissing(); |
27
|
|
|
} |
28
|
|
|
|
29
|
|
|
$this->domain = $this->sanitizeDomainName($domain); |
30
|
|
|
} |
31
|
|
|
|
32
|
|
|
public function getRecords(...$types): string |
33
|
|
|
{ |
34
|
|
|
$types = $this->determineTypes($types); |
35
|
|
|
|
36
|
|
|
$types = count($types) |
37
|
|
|
? $types |
38
|
|
|
: $this->recordTypes; |
39
|
|
|
|
40
|
|
|
$dnsRecords = array_map(function ($type) { |
41
|
|
|
return $this->getRecordsOfType($type); |
42
|
|
|
}, $types); |
43
|
|
|
|
44
|
|
|
return implode('', array_filter($dnsRecords)); |
45
|
|
|
} |
46
|
|
|
|
47
|
|
|
protected function determineTypes(array $types): array |
48
|
|
|
{ |
49
|
|
|
$types = is_array($types[0] ?? null) |
50
|
|
|
? $types[0] |
51
|
|
|
: $types; |
52
|
|
|
|
53
|
|
|
$types = array_map(function (string $type) { |
54
|
|
|
return strtoupper($type); |
55
|
|
|
}, $types); |
56
|
|
|
|
57
|
|
|
foreach ($types as $type) { |
58
|
|
|
if (! in_array($type, $this->recordTypes)) { |
59
|
|
|
throw InvalidArgument::filterIsNotAValidRecordType($type, $this->recordTypes); |
60
|
|
|
} |
61
|
|
|
} |
62
|
|
|
|
63
|
|
|
return $types; |
64
|
|
|
} |
65
|
|
|
|
66
|
|
|
protected function sanitizeDomainName(string $domain): string |
67
|
|
|
{ |
68
|
|
|
$domain = str_replace(['http://', 'https://'], '', $domain); |
69
|
|
|
|
70
|
|
|
$domain = $this->stringBefore($domain, '/'); |
71
|
|
|
|
72
|
|
|
return strtolower($domain); |
73
|
|
|
} |
74
|
|
|
|
75
|
|
|
protected function getRecordsOfType(string $type): string |
76
|
|
|
{ |
77
|
|
|
$command = 'dig +nocmd '.escapeshellarg($this->domain)." {$type} +multiline +noall +answer"; |
78
|
|
|
|
79
|
|
|
$process = new Process($command); |
80
|
|
|
|
81
|
|
|
$process->run(); |
82
|
|
|
|
83
|
|
|
if (! $process->isSuccessful()) { |
84
|
|
|
throw new Exception('Dns records could not be fetched'); |
85
|
|
|
} |
86
|
|
|
|
87
|
|
|
return $process->getOutput(); |
88
|
|
|
} |
89
|
|
|
|
90
|
|
|
protected function stringBefore(string $subject, string $search): string |
91
|
|
|
{ |
92
|
|
|
$position = strpos($subject, $search); |
93
|
|
|
|
94
|
|
|
if ($position === false) { |
95
|
|
|
return $subject; |
96
|
|
|
} |
97
|
|
|
|
98
|
|
|
return substr($subject, 0, $position); |
99
|
|
|
} |
100
|
|
|
} |
101
|
|
|
|