Passed
Branch master (07c3bf)
by Paweł
01:33
created

Url::checkDomain()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 5
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 1
eloc 2
c 1
b 0
f 0
nc 1
nop 1
dl 0
loc 5
rs 10
1
<?php
2
declare(strict_types=1);
3
4
namespace Wszetko\Sitemap\Helpers;
5
6
/**
7
 * Class Url
8
 *
9
 * @package Wszetko\Sitemap\Helpers
10
 */
11
class Url
12
{
13
    /**
14
     * @param string $url
15
     *
16
     * @return bool|string
17
     *
18
     * @see https://bugs.php.net/bug.php?id=52923
19
     * @see https://www.php.net/manual/en/function.parse-url.php#114817
20
     */
21
    public static function normalizeUrl(string $url)
22
    {
23
        $encodedUrl = preg_replace_callback(
24
            '%[^:/@?&=#]+%usD',
25
            function ($matches) {
26
                return urlencode($matches[0]);
27
            },
28
            $url
29
        );
30
31
        $url = parse_url($encodedUrl);
32
33
        if (empty($url) || !isset($url['host'])) {
34
            return false;
35
        }
36
37
        $url = array_map('urldecode', $url);
38
        $url['host'] = idn_to_ascii($url['host'], IDNA_DEFAULT, INTL_IDNA_VARIANT_UTS46);
39
40
        if (empty($url['scheme']) || !is_string($url['host']) || !self::checkDomain($url['host'])) {
41
            return false;
42
        }
43
44
        return
45
            $url['scheme'] . '://'
46
            . (isset($url['user']) ? $url['user'] . ((isset($url['pass'])) ? ':' . $url['pass'] : '') . '@' : '')
47
            . $url['host']
48
            . ((isset($url['port'])) ? ':' . $url['port'] : '')
49
            . ((isset($url['path'])) ? $url['path'] : '')
50
            . ((isset($url['query'])) ? '?' . $url['query'] : '')
51
            . ((isset($url['fragment'])) ? '#' . $url['fragment'] : '');
52
    }
53
54
    /**
55
     * @param string $domain
56
     *
57
     * @return bool
58
     */
59
    public static function checkDomain(string $domain): bool
60
    {
61
        $domain = idn_to_ascii($domain, IDNA_DEFAULT, INTL_IDNA_VARIANT_UTS46);
62
63
        return (bool)filter_var($domain, FILTER_VALIDATE_DOMAIN, FILTER_FLAG_HOSTNAME);
64
    }
65
}
66