Completed
Push — master ( 135444...54859f )
by Eduardo Gulias
06:36
created

DNSCheckValidation::checkDNS()   B

Complexity

Conditions 6
Paths 20

Size

Total Lines 20

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 16
CRAP Score 6

Importance

Changes 0
Metric Value
dl 0
loc 20
ccs 16
cts 16
cp 1
rs 8.9777
c 0
b 0
f 0
cc 6
nc 20
nop 1
crap 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 __construct()
23
    {
24 12
        if (!extension_loaded('intl')) {
25
            throw new \LogicException(sprintf('The %s class requires the Intl extension.', __CLASS__));
26
        }
27 12
    }
28
29 12
    public function isValid($email, EmailLexer $emailLexer)
30
    {
31
        // use the input to check DNS if we cannot extract something similar to a domain
32 12
        $host = $email;
33
34
        // Arguable pattern to extract the domain. Not aiming to validate the domain nor the email
35 12
        if (false !== $lastAtPos = strrpos($email, '@')) {
36 11
            $host = substr($email, $lastAtPos + 1);
37 11
        }
38
39 12
        return $this->checkDNS($host);
40
    }
41
42 1
    public function getError()
43
    {
44 1
        return $this->error;
45
    }
46
47 1
    public function getWarnings()
48
    {
49 1
        return $this->warnings;
50
    }
51
52 12
    protected function checkDNS($host)
53
    {
54 12
        $variant = INTL_IDNA_VARIANT_2003;
55 12
        if ( defined('INTL_IDNA_VARIANT_UTS46') ) {
56 12
            $variant = INTL_IDNA_VARIANT_UTS46;
57 12
        }
58 12
        $host = rtrim(idn_to_ascii($host, IDNA_DEFAULT, $variant), '.') . '.';
59
60 12
        $Aresult = true;
61 12
        $MXresult = checkdnsrr($host, 'MX');
62
63 12
        if (!$MXresult) {
64 11
            $this->warnings[NoDNSMXRecord::CODE] = new NoDNSMXRecord();
65 11
            $Aresult = checkdnsrr($host, 'A') || checkdnsrr($host, 'AAAA');
66 11
            if (!$Aresult) {
67 3
                $this->error = new NoDNSRecord();
68 3
            }
69 11
        }
70 12
        return $MXresult || $Aresult;
71
    }
72
}
73