Completed
Push — master ( 902e66...0cbd7a )
by Jan-Petter
02:44
created

HostClient::get()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 4
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Importance

Changes 5
Bugs 0 Features 1
Metric Value
c 5
b 0
f 1
dl 0
loc 4
rs 10
cc 2
eloc 2
nc 2
nop 0
1
<?php
2
namespace vipnytt\RobotsTxtParser\Client\Directives;
3
4
/**
5
 * Class HostClient
6
 *
7
 * @see https://github.com/VIPnytt/RobotsTxtParser/blob/master/docs/methods/HostClient.md for documentation
8
 * @package vipnytt\RobotsTxtParser\Client\Directives
9
 */
10
class HostClient extends HostClientCore
11
{
12
    /**
13
     * HostClient constructor.
14
     * @param string $base
15
     * @param string $effective
16
     * @param string[] $host
17
     */
18
    public function __construct($base, $effective, $host)
19
    {
20
        parent::__construct($base, $effective, $host);
21
    }
22
23
    /**
24
     * Is preferred host?
25
     *
26
     * @return bool
27
     */
28
    public function isPreferred()
29
    {
30
        if (($host = $this->export()) === null) {
31
            return $this->base === $this->effective;
32
        }
33
        $parsed = parse_url($host);
34
        $new = [
35
            'scheme' => isset($parsed['scheme']) ? $parsed['scheme'] : parse_url($this->base, PHP_URL_SCHEME),
36
            'host' => isset($parsed['host']) ? $parsed['host'] : $parsed['path'],
37
        ];
38
        $new['port'] = isset($parsed['port']) ? $parsed['port'] : getservbyname($new['scheme'], 'tcp');
39
        return $this->base == $new['scheme'] . '://' . $new['host'] . ':' . $new['port'];
40
    }
41
42
    /**
43
     * Export
44
     *
45
     * @return string|null
46
     */
47
    public function export()
48
    {
49
        return isset($this->host[0]) ? $this->host[0] : null;
50
    }
51
52
    /**
53
     * Get Host, falls back to Effective Request URI if not found
54
     *
55
     * @return string
56
     */
57
    public function getWithUriFallback()
58
    {
59
        if (($get = $this->export()) !== null) {
60
            // Host defined by the Host directive
61
            return $get;
62
        } elseif (
63
            $this->base !== $this->effective &&
64
            parse_url($this->base, PHP_URL_HOST) === ($host = parse_url($this->effective, PHP_URL_HOST))
65
        ) {
66
            // Host is the same, but Scheme or Port is different
67
            return getservbyname($scheme = parse_url($this->effective, PHP_URL_SCHEME), 'tcp') === parse_url($this->effective, PHP_URL_PORT) ? $scheme . '://' . $host : $this->effective;
68
        }
69
        // Return Host name only
70
        return parse_url($this->effective, PHP_URL_HOST);
71
    }
72
}
73