1
|
|
|
<?php |
2
|
|
|
namespace vipnytt\RobotsTxtParser\Parser\Directives; |
3
|
|
|
|
4
|
|
|
use vipnytt\RobotsTxtParser\Parser\UriParser; |
5
|
|
|
use vipnytt\RobotsTxtParser\RobotsTxtInterface; |
6
|
|
|
|
7
|
|
|
/** |
8
|
|
|
* Class HostParser |
9
|
|
|
* |
10
|
|
|
* @link http://tools.ietf.org/html/rfc952 |
11
|
|
|
* |
12
|
|
|
* @package vipnytt\RobotsTxtParser\Parser\Directives |
13
|
|
|
*/ |
14
|
|
|
abstract class HostParserCore implements ParserInterface, RobotsTxtInterface |
15
|
|
|
{ |
16
|
|
|
/** |
17
|
|
|
* Base uri |
18
|
|
|
* @var string |
19
|
|
|
*/ |
20
|
|
|
protected $base; |
21
|
|
|
|
22
|
|
|
/** |
23
|
|
|
* Effective uri |
24
|
|
|
* @var string |
25
|
|
|
*/ |
26
|
|
|
protected $effective; |
27
|
|
|
|
28
|
|
|
/** |
29
|
|
|
* Host values |
30
|
|
|
* @var string[] |
31
|
|
|
*/ |
32
|
|
|
protected $host = []; |
33
|
|
|
|
34
|
|
|
/** |
35
|
|
|
* HostParser constructor. |
36
|
|
|
* |
37
|
|
|
* @param string $base |
38
|
|
|
* @param string $effective |
39
|
|
|
*/ |
40
|
|
|
public function __construct($base, $effective) |
41
|
|
|
{ |
42
|
|
|
$this->base = $base; |
43
|
|
|
$this->effective = $effective; |
44
|
|
|
} |
45
|
|
|
|
46
|
|
|
/** |
47
|
|
|
* Add |
48
|
|
|
* |
49
|
|
|
* @param string $line |
50
|
|
|
* @return bool |
51
|
|
|
*/ |
52
|
|
|
public function add($line) |
53
|
|
|
{ |
54
|
|
|
$host = $this->parse($line); |
55
|
|
|
if ( |
56
|
|
|
$host === false || |
57
|
|
|
$host !== $line || |
58
|
|
|
in_array($host, $this->host) |
59
|
|
|
) { |
60
|
|
|
return false; |
61
|
|
|
} |
62
|
|
|
$this->host[] = $line; |
63
|
|
|
return true; |
64
|
|
|
} |
65
|
|
|
|
66
|
|
|
/** |
67
|
|
|
* Parse |
68
|
|
|
* |
69
|
|
|
* @param string $line |
70
|
|
|
* @return string|false |
71
|
|
|
*/ |
72
|
|
|
private function parse($line) |
73
|
|
|
{ |
74
|
|
|
$uriParser = new UriParser($line); |
75
|
|
|
$line = $uriParser->encode(); |
76
|
|
|
if ( |
77
|
|
|
$uriParser->validateIP() || |
78
|
|
|
!$uriParser->validateHost() || |
79
|
|
|
( |
80
|
|
|
parse_url($line, PHP_URL_SCHEME) !== null && |
81
|
|
|
!$uriParser->validateScheme() |
82
|
|
|
) |
83
|
|
|
) { |
84
|
|
|
return false; |
85
|
|
|
} |
86
|
|
|
$parts = $this->getParts($line); |
87
|
|
|
return $parts['scheme'] . $parts['host'] . $parts['port']; |
88
|
|
|
} |
89
|
|
|
|
90
|
|
|
/** |
91
|
|
|
* Get URI parts |
92
|
|
|
* |
93
|
|
|
* @param string $uri |
94
|
|
|
* @return string[]|false |
95
|
|
|
*/ |
96
|
|
|
private function getParts($uri) |
97
|
|
|
{ |
98
|
|
|
return ($parsed = parse_url($uri)) === false ? false : [ |
99
|
|
|
'scheme' => isset($parsed['scheme']) ? $parsed['scheme'] . '://' : '', |
100
|
|
|
'host' => isset($parsed['host']) ? $parsed['host'] : $parsed['path'], |
101
|
|
|
'port' => isset($parsed['port']) ? ':' . $parsed['port'] : '', |
102
|
|
|
]; |
103
|
|
|
} |
104
|
|
|
} |
105
|
|
|
|