Completed
Push — master ( badca6...1bd341 )
by Jan-Petter
01:59
created

Host::add()   D

Complexity

Conditions 9
Paths 19

Size

Total Lines 25
Code Lines 16

Duplication

Lines 0
Ratio 0 %

Importance

Changes 2
Bugs 0 Features 0
Metric Value
c 2
b 0
f 0
dl 0
loc 25
rs 4.909
cc 9
eloc 16
nc 19
nop 1
1
<?php
2
namespace vipnytt\RobotsTxtParser\Directives;
3
4
use vipnytt\RobotsTxtParser\UrlToolbox;
5
6
/**
7
 * Class Host
8
 *
9
 * @package vipnytt\RobotsTxtParser\Directives
10
 */
11
class Host implements DirectiveInterface
12
{
13
    use UrlToolbox;
14
15
    /**
16
     * Directive
17
     */
18
    const DIRECTIVE = 'Host';
19
20
    /**
21
     * Host array
22
     * @var array
23
     */
24
    protected $array = [];
25
26
    /**
27
     * Host constructor.
28
     */
29
    public function __construct()
30
    {
31
    }
32
33
    /**
34
     * Add
35
     *
36
     * @param string $line
37
     * @return bool
38
     */
39
    public function add($line)
40
    {
41
        if (($parsed = parse_url(($line = $this->urlEncode(mb_strtolower($line))))) === false) {
42
            return false;
43
        }
44
        $line = isset($parsed['host']) ? $parsed['host'] : $parsed['path'];
45
        if (
46
            !$this->urlValidateHost($line) ||
47
            (
48
                isset($parsed['scheme']) &&
49
                !$this->urlValidateScheme($parsed['scheme'])
50
            )
51
        ) {
52
            return false;
53
        }
54
        $scheme = isset($parsed['scheme']) ? $parsed['scheme'] . '://' : '';
55
        $port = isset($parsed['port']) ? ':' . $parsed['port'] : '';
56
57
        $host = $scheme . $line . $port;
58
        if (in_array($host, $this->array)) {
59
            return false;
60
        }
61
        $this->array[] = $host;
62
        return true;
63
    }
64
65
    /**
66
     * Check
67
     *
68
     * @param string $url
69
     * @return bool
70
     */
71
    public function check($url)
72
    {
73
        if (empty($this->array)) {
74
            return false;
75
        }
76
        $url = mb_strtolower($this->urlEncode($url));
77
        $parts = [
78
            'scheme' => parse_url($url, PHP_URL_SCHEME),
79
            'host' => parse_url($url, PHP_URL_HOST),
80
        ];
81
        $parts['port'] = is_int($port = parse_url($url, PHP_URL_PORT)) ? $port : getservbyname($parts['scheme'], 'tcp');
82
        $cases = [
83
            $parts['host'],
84
            $parts['host'] . ':' . $parts['port'],
85
            $parts['scheme'] . '://' . $parts['host'],
86
            $parts['scheme'] . '://' . $parts['host'] . ':' . $parts['port']
87
        ];
88
        if (in_array($this->array[0], $cases)) {
89
            return true;
90
        }
91
        return false;
92
    }
93
94
    /**
95
     * Export
96
     *
97
     * @return array
98
     */
99
    public function export()
100
    {
101
        return empty($this->array) ? [] : [self::DIRECTIVE => $this->array];
102
    }
103
}
104