DnsHelper::existsA()   A
last analyzed

Complexity

Conditions 1
Paths 1

Size

Total Lines 14
Code Lines 7

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 10
CRAP Score 1

Importance

Changes 4
Bugs 0 Features 0
Metric Value
cc 1
eloc 7
c 4
b 0
f 0
nc 1
nop 1
dl 0
loc 14
ccs 10
cts 10
cp 1
crap 1
rs 10
1
<?php
2
3
declare(strict_types=1);
4
5
namespace Yiisoft\NetworkUtilities;
6
7
use RuntimeException;
8
9
/**
10
 * DnsHelper contains static methods to work with DNS.
11
 */
12
final class DnsHelper
13
{
14
    /**
15
     * Checks DNS MX record availability.
16
     *
17
     * @param string $hostname Hostname without dot at end.
18
     *
19
     * @return bool Whether MX record exists.
20
     */
21 3
    public static function existsMx(string $hostname): bool
22
    {
23 3
        set_error_handler(static function (int $errorNumber, string $errorString) use ($hostname): bool {
24 1
            throw new RuntimeException(
25 1
                sprintf('Failed to get DNS record "%s". ', $hostname) . $errorString,
26 1
                $errorNumber
27 1
            );
28 3
        });
29
30 3
        $hostname = rtrim($hostname, '.') . '.';
31 3
        $result = dns_get_record($hostname, DNS_MX);
32
33 2
        restore_error_handler();
34
35 2
        return count($result) > 0;
36
    }
37
38
    /**
39
     * Checks DNS A record availability.
40
     *
41
     * @param string $hostname Hostname without dot at end.
42
     *
43
     * @return bool Whether A records exists.
44
     */
45 3
    public static function existsA(string $hostname): bool
46
    {
47 3
        set_error_handler(static function (int $errorNumber, string $errorString) use ($hostname): bool {
48 1
            throw new RuntimeException(
49 1
                sprintf('Failed to get DNS record "%s". ', $hostname) . $errorString,
50 1
                $errorNumber
51 1
            );
52 3
        });
53
54 3
        $result = dns_get_record($hostname, DNS_A);
55
56 2
        restore_error_handler();
57
58 2
        return count($result) > 0;
59
    }
60
61
    /**
62
     * Checks email's domain availability.
63
     *
64
     * @link https://tools.ietf.org/html/rfc5321#section-5
65
     *
66
     * @param string $hostnameOrEmail Hostname without dot at end or an email.
67
     *
68
     * @return bool Whether email domain is available.
69
     */
70 1
    public static function acceptsEmails(string $hostnameOrEmail): bool
71
    {
72 1
        if (strpos($hostnameOrEmail, '@') !== false) {
73 1
            [, $hostnameOrEmail] = explode('@', $hostnameOrEmail, 2);
74
        }
75 1
        return self::existsMx($hostnameOrEmail) || self::existsA($hostnameOrEmail);
76
    }
77
}
78