Passed
Pull Request — master (#173)
by
unknown
02:49
created

DNSCheckValidation   A

Complexity

Total Complexity 10

Size/Duplication

Total Lines 58
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 2

Test Coverage

Coverage 96.15%

Importance

Changes 0
Metric Value
wmc 10
lcom 1
cbo 2
dl 0
loc 58
ccs 25
cts 26
cp 0.9615
rs 10
c 0
b 0
f 0

4 Methods

Rating   Name   Duplication   Size   Complexity  
A isValid() 0 12 2
A getError() 0 4 1
A getWarnings() 0 4 1
B checkDNS() 0 22 6
1
<?php
2
3
namespace Egulias\EmailValidator\Validation;
4
5
use Egulias\EmailValidator\EmailLexer;
6
use Egulias\EmailValidator\Exception\InvalidEmail;
7
use Egulias\EmailValidator\Warning\NoDNSMXRecord;
8
use Egulias\EmailValidator\Exception\NoDNSRecord;
9
10
class DNSCheckValidation implements EmailValidation
11
{
12
    /**
13
     * @var array
14
     */
15
    private $warnings = [];
16
17
    /**
18
     * @var InvalidEmail
19
     */
20
    private $error;
21
22 12
    public function isValid($email, EmailLexer $emailLexer)
23
    {
24
        // use the input to check DNS if we cannot extract something similar to a domain
25 12
        $host = $email;
26
27
        // Arguable pattern to extract the domain. Not aiming to validate the domain nor the email
28 12
        if (false !== $lastAtPos = strrpos($email, '@')) {
29 11
            $host = substr($email, $lastAtPos + 1);
30 11
        }
31
32 12
        return $this->checkDNS($host);
33
    }
34
35 1
    public function getError()
36
    {
37 1
        return $this->error;
38
    }
39
40 1
    public function getWarnings()
41
    {
42 1
        return $this->warnings;
43
    }
44
45 12
    protected function checkDNS($host)
46
    {
47 12
        if ( defined('INTL_IDNA_VARIANT_UTS46') ) {
48 12
            $variant = INTL_IDNA_VARIANT_UTS46;
49 12
        } else {
50
            $variant = INTL_IDNA_VARIANT_2003;
51
        }
52
        
53 12
        $host = rtrim(idn_to_ascii($host, IDNA_DEFAULT, $variant), '.') . '.';
54
55 12
        $Aresult = true;
56 12
        $MXresult = checkdnsrr($host, 'MX');
57
58 12
        if (!$MXresult) {
59 11
            $this->warnings[NoDNSMXRecord::CODE] = new NoDNSMXRecord();
60 11
            $Aresult = checkdnsrr($host, 'A') || checkdnsrr($host, 'AAAA');
61 11
            if (!$Aresult) {
62 3
                $this->error = new NoDNSRecord();
63 3
            }
64 11
        }
65 12
        return $MXresult || $Aresult;
66
    }
67
}
68