DnsValidator   A
last analyzed

Complexity

Total Complexity 7

Size/Duplication

Total Lines 56
Duplicated Lines 0 %

Importance

Changes 0
Metric Value
eloc 31
dl 0
loc 56
rs 10
c 0
b 0
f 0
wmc 7

3 Methods

Rating   Name   Duplication   Size   Complexity  
A validateNameServers() 0 23 3
A validateHost() 0 13 3
A __construct() 0 4 1
1
<?php declare(strict_types=1);
2
3
namespace Cocotte\DigitalOcean;
4
5
use Assert\Assertion;
6
use Cocotte\Shell\Env;
7
use Iodev\Whois\Modules\Tld\DomainInfo;
8
use Iodev\Whois\Whois;
9
10
class DnsValidator
11
{
12
    /**
13
     * @var Whois
14
     */
15
    private $whois;
16
    /**
17
     * @var Env
18
     */
19
    private $env;
20
21
    public function __construct(Whois $whois, Env $env)
22
    {
23
        $this->whois = $whois;
24
        $this->env = $env;
25
    }
26
27
    public function validateHost(Hostname $hostname)
28
    {
29
        if ($this->env->get(SkipDnsValidation::SKIP_DNS_VALIDATION)) {
30
            return;
31
        }
32
33
        try {
34
            $this->validateNameServers($hostname->toRoot());
35
        } catch (\Throwable $domainException) {
36
            $message = [];
37
            $message[] = "Failed to validate name servers for '$hostname':";
38
            $message[] = $domainException->getMessage();
39
            throw new \Exception(implode("\n", $message));
40
        }
41
    }
42
43
    protected function validateNameServers(Hostname $hostname)
44
    {
45
        $info = $this->whois->loadDomainInfo($hostname->domainName());
46
        if (!$info instanceof DomainInfo) {
0 ignored issues
show
introduced by
$info is always a sub-type of Iodev\Whois\Modules\Tld\DomainInfo.
Loading history...
47
            throw new \Exception("Could not load domain info of $hostname");
48
        }
49
        $nameServers = $info->getNameServers();
50
        Assertion::isArray(
51
            $nameServers,
52
            "Expected array. Got: ".var_export($nameServers, true)
53
        );
54
        Assertion::greaterThan(
55
            count($nameServers),
56
            0,
57
            "Expected 1 or more name servers. Got ".count($nameServers)
58
        );
59
        foreach ($nameServers as $nameServer) {
60
            $nameServer = Hostname::parse($nameServer);
61
            Assertion::regex(
62
                $nameServer->toString(),
63
                "/ns[0-9]\.digitalocean\.com/",
64
                "'{$nameServer->toString()}' is not a Digital Ocean's name server in the ".
65
                "form of ns[0-9].digitalocean.com"
66
            );
67
        }
68
    }
69
}
70