1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
namespace Spatie\Robots; |
4
|
|
|
|
5
|
|
|
use InvalidArgumentException; |
6
|
|
|
|
7
|
|
|
class RobotsHeaders |
8
|
|
|
{ |
9
|
|
|
protected $robotHeadersProperties = []; |
10
|
|
|
|
11
|
|
|
public static function readFrom(string $source): self |
12
|
|
|
{ |
13
|
|
|
$content = @file_get_contents($source); |
14
|
|
|
|
15
|
|
|
if ($content === false) { |
16
|
|
|
throw new InvalidArgumentException("Could not read from source `{$source}`"); |
17
|
|
|
} |
18
|
|
|
|
19
|
|
|
return new self($http_response_header ?? []); |
20
|
|
|
} |
21
|
|
|
|
22
|
|
|
public static function create(array $headers): self |
23
|
|
|
{ |
24
|
|
|
return new self($headers); |
25
|
|
|
} |
26
|
|
|
|
27
|
|
|
public function __construct(array $headers) |
28
|
|
|
{ |
29
|
|
|
$this->robotHeadersProperties = $this->parseHeaders($headers); |
30
|
|
|
} |
31
|
|
|
|
32
|
|
|
public function mayIndex(string $userAgent = '*'): bool |
33
|
|
|
{ |
34
|
|
|
return ! $this->noindex($userAgent); |
35
|
|
|
} |
36
|
|
|
|
37
|
|
|
public function mayFollow(string $userAgent = '*'): bool |
38
|
|
|
{ |
39
|
|
|
return ! $this->nofollow($userAgent); |
40
|
|
|
} |
41
|
|
|
|
42
|
|
|
public function noindex(string $userAgent = '*'): bool |
43
|
|
|
{ |
44
|
|
|
return $this->robotHeadersProperties[$userAgent]['noindex'] ?? false; |
45
|
|
|
} |
46
|
|
|
|
47
|
|
|
public function nofollow(string $userAgent = '*'): bool |
48
|
|
|
{ |
49
|
|
|
return $this->robotHeadersProperties[$userAgent]['nofollow'] ?? false; |
50
|
|
|
} |
51
|
|
|
|
52
|
|
|
protected function parseHeaders(array $headers): array |
53
|
|
|
{ |
54
|
|
|
$robotHeadders = $this->filterRobotHeaders($headers); |
55
|
|
|
|
56
|
|
|
return array_reduce($robotHeadders, function (array $parsedHeaders, $header) { |
57
|
|
|
$header = $this->normalizeHeaders($header); |
58
|
|
|
|
59
|
|
|
$headerParts = explode(':', $header); |
60
|
|
|
|
61
|
|
|
$userAgent = count($headerParts) === 3 |
62
|
|
|
? trim($headerParts[1]) |
63
|
|
|
: '*'; |
64
|
|
|
|
65
|
|
|
$options = end($headerParts); |
66
|
|
|
|
67
|
|
|
$parsedHeaders[$userAgent] = [ |
68
|
|
|
'noindex' => strpos(strtolower($options), 'noindex') !== false, |
69
|
|
|
'nofollow' => strpos(strtolower($options), 'nofollow') !== false, |
70
|
|
|
]; |
71
|
|
|
|
72
|
|
|
return $parsedHeaders; |
73
|
|
|
}, []); |
74
|
|
|
} |
75
|
|
|
|
76
|
|
|
protected function filterRobotHeaders(array $headers): array |
77
|
|
|
{ |
78
|
|
|
return array_filter($headers, function ($header) { |
79
|
|
|
$header = $this->normalizeHeaders($header); |
80
|
|
|
|
81
|
|
|
return strpos(strtolower($header), 'x-robots-tag') === 0; |
82
|
|
|
}); |
83
|
|
|
} |
84
|
|
|
|
85
|
|
|
protected function normalizeHeaders($headers): string |
86
|
|
|
{ |
87
|
|
|
return implode(',', (array) $headers); |
88
|
|
|
} |
89
|
|
|
} |
90
|
|
|
|