Completed
Push — master ( 4e8d1d...8d6f18 )
by Philipp
03:00
created

Url::domain()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 8
Code Lines 3

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 2
eloc 3
nc 2
nop 0
dl 0
loc 8
rs 10
c 0
b 0
f 0
1
<?php
2
3
namespace Pmochine\LaravelTongue\Misc;
4
5
use LayerShifter\TLDExtract\Extract;
6
use Illuminate\Support\Str;
7
8
class Url
9
{
10
    public static function domain(): string
11
    {
12
        //check if the hosted domain is the same, if not use it from get host
13
        if (self::configDomainIsSet()) {
14
            return Config::domain();
15
        }
16
17
        return self::extractDomain();
18
    }
19
20
    /**
21
     * This is actually not that important. Only if you have
22
     * complicated domains like '155ad73e.eu.ngrok.io', whe I just 
23
     * cannot tell what the real domain is.
24
     * 
25
     * It is true when e.g.: '155ad73e.eu.ngrok.io' contains in 'yoursubdomain.155ad73e.eu.ngrok.io'
26
     *
27
     * @return  bool  
28
     */
29
    protected static function configDomainIsSet(): bool
30
    {
31
        if (!$domain = Config::domain()) return false; // config was not set
32
33
        //the host could have a different domain, thats why we check it here
34
        return Str::contains(self::host(), $domain);
35
    }
36
37
    /**
38
     * Gets the registrable Domain of the website.
39
     *
40
     * https://github.com/layershifter/TLDExtract
41
     *
42
     * @return  string
43
     */
44
    protected static function extractDomain(): string
45
    {
46
        $result = (new Extract())->parse(self::host());
47
48
        return $result->getRegistrableDomain();
0 ignored issues
show
Bug Best Practice introduced by
The expression return $result->getRegistrableDomain() could return the type null which is incompatible with the type-hinted return string. Consider adding an additional type-check to rule them out.
Loading history...
49
    }
50
51
    public static function domainName(): string
52
    {
53
        $TLD = substr(self::domain(), strrpos(self::domain(), '.'));
54
        return Str::replaceLast($TLD, '', self::domain());
55
    }
56
57
    /**
58
     * @return  string  [like "de.domain.com"]
59
     */
60
    public static function host(): string
61
    {
62
        return request()->getHost();
63
    }
64
65
    /**
66
     * @return  string  [like "de" or when no subdomain "domain" of "domain.com"]
67
     */
68
    public static function subdomain(): string
69
    {
70
        return explode('.', self::host())[0];
71
    }
72
73
    public static function hasSubdomain(): bool
74
    {
75
        return explode('.', self::domain())[0] !== self::subdomain();
76
    }
77
}
78