Test Failed
Push — master ( 766a39...696a12 )
by Dispositif
09:33
created

InternetDomainParser::extractSubdomainString()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 7
Code Lines 3

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 2
eloc 3
c 1
b 0
f 0
nc 2
nop 1
dl 0
loc 7
rs 10
1
<?php
2
/*
3
 * This file is part of dispositif/wikibot application (@github)
4
 * 2019-2023 © Philippe M./Irønie  <[email protected]>
5
 * For the full copyright and MIT license information, view the license file.
6
 */
7
8
declare(strict_types=1);
9
10
namespace App\Infrastructure;
11
12
use App\Application\Http\ExternHttpClient;
13
use Exception;
14
use Pdp\Domain;
15
use Pdp\ResolvedDomainName;
16
use Pdp\Rules;
17
18
/**
19
 * Doc https://packagist.org/packages/jeremykendall/php-domain-parser
20
 */
21
class InternetDomainParser
22
{
23
    private const PATH_CACHE_PUBLIC_SUFFIX_LIST = __DIR__ . '/resources/public_suffix_list.dat';
24
25
    /**
26
     * https://www.google.fr => google.fr
27
     * http://fu.co.uk => fu.co.uk
28
     * @throws Exception
29
     */
30
    public static function getRegistrableDomainFromURL(string $httpURL): string
31
    {
32
        $result = self::initialize($httpURL);
33
34
        return $result->registrableDomain()->toString();
35
    }
36
37
    /**
38
     * https://www.google.fr => google.fr
39
     * http://fu.co.uk => fu.co.uk
40
     */
41
    public static function extractSubdomainString(string $httpURL): string
42
    {
43
        if (!ExternHttpClient::isHttpURL($httpURL)) {
44
            throw new \Exception('string is not an URL '.$httpURL);
45
        }
46
47
        return parse_url($httpURL, PHP_URL_HOST);
48
    }
49
50
    protected static function initialize(string $httpURL): ResolvedDomainName
51
    {
52
        if (!file_exists(self::PATH_CACHE_PUBLIC_SUFFIX_LIST)) {
53
            throw new Exception('Public suffix list not found');
54
        }
55
56
        $publicSuffixList = Rules::fromPath(self::PATH_CACHE_PUBLIC_SUFFIX_LIST);
57
        $domain = Domain::fromIDNA2008(parse_url($httpURL, PHP_URL_HOST));
58
59
        return $publicSuffixList->resolve($domain);
60
    }
61
}