1
|
|
|
<?php |
2
|
|
|
namespace vipnytt\RobotsTxtParser; |
3
|
|
|
|
4
|
|
|
trait ObjectTools |
5
|
|
|
{ |
6
|
|
|
/** |
7
|
|
|
* Check basic rule |
8
|
|
|
* |
9
|
|
|
* @param string $path |
10
|
|
|
* @param array $paths |
11
|
|
|
* @return bool |
12
|
|
|
*/ |
13
|
|
|
public function checkPath($path, $paths) |
14
|
|
|
{ |
15
|
|
|
// bug: https://github.com/t1gor/Robots.txt-Parser-Class/issues/62 |
16
|
|
|
foreach ($paths as $robotPath) { |
17
|
|
|
$escaped = strtr($robotPath, ["@" => '\@']); |
18
|
|
|
if (preg_match('@' . $escaped . '@', $path)) { |
19
|
|
|
if (mb_stripos($escaped, '$') !== false) { |
20
|
|
|
if (mb_strlen($escaped) - 1 == mb_strlen($path)) { |
21
|
|
|
return true; |
22
|
|
|
} |
23
|
|
|
} else { |
24
|
|
|
return true; |
25
|
|
|
} |
26
|
|
|
} |
27
|
|
|
} |
28
|
|
|
return false; |
29
|
|
|
} |
30
|
|
|
|
31
|
|
|
/** |
32
|
|
|
* Generate directive/rule pair |
33
|
|
|
* |
34
|
|
|
* @param string $line |
35
|
|
|
* @param array $whiteList |
36
|
|
|
* @return array|false |
37
|
|
|
*/ |
38
|
|
|
protected function generateRulePair($line, $whiteList) |
39
|
|
|
{ |
40
|
|
|
$whiteList = array_map('mb_strtolower', $whiteList); |
41
|
|
|
// Split by directive and rule |
42
|
|
|
$pair = array_map('trim', mb_split(':', $line, 2)); |
43
|
|
|
// Check if the line contains a rule |
44
|
|
|
if ( |
45
|
|
|
empty($pair[1]) || |
46
|
|
|
empty($pair[0]) || |
47
|
|
|
!in_array(($pair[0] = mb_strtolower($pair[0])), $whiteList) |
48
|
|
|
) { |
49
|
|
|
// Line does not contain any supported directive |
50
|
|
|
return false; |
51
|
|
|
} |
52
|
|
|
return [ |
53
|
|
|
'directive' => $pair[0], |
54
|
|
|
'value' => $pair[1], |
55
|
|
|
]; |
56
|
|
|
} |
57
|
|
|
|
58
|
|
|
/** |
59
|
|
|
* Get path |
60
|
|
|
* |
61
|
|
|
* @param string $url |
62
|
|
|
* @return string |
63
|
|
|
* @throws Exceptions\ClientException |
64
|
|
|
*/ |
65
|
|
|
protected function getPath($url) |
66
|
|
|
{ |
67
|
|
|
$url = $this->urlEncode($url); |
|
|
|
|
68
|
|
|
if (mb_stripos($url, '/') === 0) { |
69
|
|
|
// URL already is a path |
70
|
|
|
return $url; |
71
|
|
|
} |
72
|
|
|
if (!$this->urlValidate($url)) { |
|
|
|
|
73
|
|
|
throw new Exceptions\ClientException('Invalid URL'); |
74
|
|
|
} |
75
|
|
|
return parse_url($url, PHP_URL_PATH); |
76
|
|
|
} |
77
|
|
|
} |
78
|
|
|
|
This check looks for methods that are used by a trait but not required by it.
To illustrate, let’s look at the following code example
The trait
Idable
provides a methodequalsId
that in turn relies on the methodgetId()
. If this method does not exist on a class mixing in this trait, the method will fail.Adding the
getId()
as an abstract method to the trait will make sure it is available.