Completed
Push — master ( ed861e...6484b8 )
by Eduardo Gulias
02:04
created

DNSCheckValidation::checkDNS()   A

Complexity

Conditions 4
Paths 6

Size

Total Lines 14
Code Lines 9

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
c 1
b 0
f 0
dl 0
loc 14
rs 9.2
cc 4
eloc 9
nc 6
nop 1
1
<?php
2
3
namespace Egulias\EmailValidator\Validation;
4
5
use Egulias\EmailValidator\EmailLexer;
6
use Egulias\EmailValidator\Warning\NoDNSMXRecord;
7
use Egulias\EmailValidator\Exception\NoDNSRecord;
8
9
class DNSCheckValidation implements EmailValidation
10
{
11
    /**
12
     * @var EmailParser
13
     */
14
    private $parser;
15
16
    /**
17
     * @var array
18
     */
19
    private $warnings = [];
20
21
    /**
22
     * @var InvalidEmail
23
     */
24
    private $error;
25
26
    public function isValid($email, EmailLexer $emailLexer)
27
    {
28
        // use the input to check DNS if we cannot extract something similar to a domain
29
        $host = $email;
30
        // Arguable pattern to extract the domain. Not aiming to validate the domain nor the email
31
        $pattern = "/^[a-z'0-9]+([._-][a-z'0-9]+)*@([a-z0-9]+([._-][a-z0-9]+)+)+$/";
32
        if (preg_match($pattern, $email, $result)) {
33
            $host = $this->extractHost($result);
34
        }
35
36
        return $this->checkDNS($host);
37
    }
38
39
    public function getError()
40
    {
41
        return $this->error;
42
    }
43
44
    public function getWarnings()
45
    {
46
        return $this->warnings;
47
    }
48
49
    private function extractHost(array $result)
50
    {
51
        foreach ($result as $match) {
52
            $onlyDomainPattern = "/^([a-z0-9]+([._-][a-z0-9]+))+$/";
53
            if (preg_match($onlyDomainPattern, $match, $domainResult)) {
54
                return $domainResult[0];
55
            }
56
        }
57
    }
58
59
    protected function checkDNS($host)
60
    {
61
        $Aresult = true;
62
        $MXresult = checkdnsrr($host, 'MX');
63
        
64
        if (!$MXresult) {
65
            $this->warnings[NoDNSMXRecord::CODE] = new NoDNSMXRecord();
66
            $Aresult = checkdnsrr($host, 'A');
67
            if (!$Aresult) {
68
                $this->error = new NoDNSRecord();
0 ignored issues
show
Documentation Bug introduced by
It seems like new \Egulias\EmailValida...Exception\NoDNSRecord() of type object<Egulias\EmailVali...\Exception\NoDNSRecord> is incompatible with the declared type object<Egulias\EmailVali...alidation\InvalidEmail> of property $error.

Our type inference engine has found an assignment to a property that is incompatible with the declared type of that property.

Either this assignment is in error or the assigned type should be added to the documentation/type hint for that property..

Loading history...
69
            }
70
        }
71
        return $MXresult || $Aresult;
72
    }
73
}
74