1
|
|
|
<?php |
2
|
|
|
namespace vipnytt\RobotsTxtParser\Modules; |
3
|
|
|
|
4
|
|
|
use vipnytt\RobotsTxtParser\Exceptions\ParserException; |
5
|
|
|
|
6
|
|
|
/** |
7
|
|
|
* Trait DirectiveTools |
8
|
|
|
* |
9
|
|
|
* @package vipnytt\RobotsTxtParser\Modules |
10
|
|
|
*/ |
11
|
|
|
trait Toolbox |
12
|
|
|
{ |
13
|
|
|
/** |
14
|
|
|
* Check basic rule |
15
|
|
|
* |
16
|
|
|
* @param string $path |
17
|
|
|
* @param array $paths |
18
|
|
|
* @return bool |
19
|
|
|
*/ |
20
|
|
|
protected function checkPath($path, $paths) |
21
|
|
|
{ |
22
|
|
|
// bug: https://github.com/t1gor/Robots.txt-Parser-Class/issues/62 |
23
|
|
|
foreach ($paths as $robotPath) { |
24
|
|
|
$escaped = strtr($robotPath, ["@" => '\@']); |
25
|
|
|
if (preg_match('@' . $escaped . '@', $path)) { |
26
|
|
|
if (mb_stripos($escaped, '$') !== false) { |
27
|
|
|
if (mb_strlen($escaped) - 1 == mb_strlen($path)) { |
28
|
|
|
return true; |
29
|
|
|
} |
30
|
|
|
} else { |
31
|
|
|
return true; |
32
|
|
|
} |
33
|
|
|
} |
34
|
|
|
} |
35
|
|
|
return false; |
36
|
|
|
} |
37
|
|
|
|
38
|
|
|
/** |
39
|
|
|
* Generate directive/rule pair |
40
|
|
|
* |
41
|
|
|
* @param string $line |
42
|
|
|
* @param array $whiteList |
43
|
|
|
* @return array|false |
44
|
|
|
*/ |
45
|
|
|
protected function generateRulePair($line, $whiteList) |
46
|
|
|
{ |
47
|
|
|
$whiteList = array_map('mb_strtolower', $whiteList); |
48
|
|
|
// Split by directive and rule |
49
|
|
|
$pair = array_map('trim', mb_split(':', $line, 2)); |
50
|
|
|
// Check if the line contains a rule |
51
|
|
|
if ( |
52
|
|
|
empty($pair[1]) || |
53
|
|
|
empty($pair[0]) || |
54
|
|
|
!in_array(($pair[0] = mb_strtolower($pair[0])), $whiteList) |
55
|
|
|
) { |
56
|
|
|
// Line does not contain any supported directive |
57
|
|
|
return false; |
58
|
|
|
} |
59
|
|
|
return [ |
60
|
|
|
'directive' => $pair[0], |
61
|
|
|
'value' => $pair[1], |
62
|
|
|
]; |
63
|
|
|
} |
64
|
|
|
|
65
|
|
|
/** |
66
|
|
|
* Validate directive |
67
|
|
|
* |
68
|
|
|
* @param $directive |
69
|
|
|
* @param $directives |
70
|
|
|
* @return string |
71
|
|
|
* @throws ParserException |
72
|
|
|
*/ |
73
|
|
|
protected function validateDirective($directive, $directives) |
74
|
|
|
{ |
75
|
|
|
if (!in_array($directive, $directives, true)) { |
76
|
|
|
throw new ParserException('Directive is not allowed here'); |
77
|
|
|
} |
78
|
|
|
return mb_strtolower($directive); |
79
|
|
|
} |
80
|
|
|
} |
81
|
|
|
|