Passed
Pull Request — master (#30)
by Rustam
01:53
created

DnsHelper   A

Complexity

Total Complexity 5

Size/Duplication

Total Lines 63
Duplicated Lines 0 %

Test Coverage

Coverage 100%

Importance

Changes 3
Bugs 0 Features 0
Metric Value
eloc 21
c 3
b 0
f 0
dl 0
loc 63
ccs 23
cts 23
cp 1
rs 10
wmc 5

3 Methods

Rating   Name   Duplication   Size   Complexity  
A existsMx() 0 17 1
A existsA() 0 17 1
A acceptsEmails() 0 6 3
1
<?php
2
3
declare(strict_types=1);
4
5
namespace Yiisoft\NetworkUtilities;
6
7
use RuntimeException;
8
9
final class DnsHelper
10
{
11
    /**
12
     * @param string $hostname hostname without dot at end
13
     *
14
     * @return bool
15
     */
16 3
    public static function existsMx(string $hostname): bool
17
    {
18
        /** @psalm-suppress InvalidArgument, MixedArgumentTypeCoercion */
19 3
        set_error_handler(
20 3
            static function (int $errorNumber, string $errorString) use ($hostname): ?bool {
21 1
                throw new RuntimeException(
22 1
                    sprintf('Failed to get DNS record "%s". ', $hostname) . $errorString,
23
                    $errorNumber
24
                );
25 3
            }
26
        );
27 3
        $hostname = rtrim($hostname, '.') . '.';
28 3
        $result = dns_get_record($hostname, DNS_MX);
29
30 2
        restore_error_handler();
31
32 2
        return count($result) > 0;
33
    }
34
35
    /**
36
     * @param string $hostname
37
     *
38
     * @return bool
39
     */
40 3
    public static function existsA(string $hostname): bool
41
    {
42
        /** @psalm-suppress InvalidArgument, MixedArgumentTypeCoercion */
43 3
        set_error_handler(
44 3
            static function (int $errorNumber, string $errorString) use ($hostname): ?bool {
45 1
                throw new RuntimeException(
46 1
                    sprintf('Failed to get DNS record "%s". ', $hostname) . $errorString,
47
                    $errorNumber
48
                );
49 3
            }
50
        );
51
52 3
        $result = dns_get_record($hostname, DNS_A);
53
54 2
        restore_error_handler();
55
56 2
        return count($result) > 0;
57
    }
58
59
    /**
60
     * @link https://tools.ietf.org/html/rfc5321#section-5
61
     *
62
     * @param string $hostnameOrEmail
63
     *
64
     * @return bool
65
     */
66 1
    public static function acceptsEmails(string $hostnameOrEmail): bool
67
    {
68 1
        if (strpos($hostnameOrEmail, '@') !== false) {
69 1
            [, $hostnameOrEmail] = explode('@', $hostnameOrEmail, 2);
70
        }
71 1
        return self::existsMx($hostnameOrEmail) || self::existsA($hostnameOrEmail);
72
    }
73
}
74