1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
/* |
4
|
|
|
* This file is part of the bisarca/robots-txt package. |
5
|
|
|
* |
6
|
|
|
* (c) Emanuele Minotto <[email protected]> |
7
|
|
|
* |
8
|
|
|
* For the full copyright and license information, please view the LICENSE |
9
|
|
|
* file that was distributed with this source code. |
10
|
|
|
*/ |
11
|
|
|
|
12
|
|
|
namespace Bisarca\RobotsTxt\Directive; |
13
|
|
|
|
14
|
|
|
use Bisarca\RobotsTxt\Exception\InvalidDirectiveException; |
15
|
|
|
|
16
|
|
|
/** |
17
|
|
|
* "User-agent" directive element. |
18
|
|
|
*/ |
19
|
|
|
class UserAgent implements StartOfGroupInterface, GroupMemberInterface |
20
|
|
|
{ |
21
|
|
|
/** |
22
|
|
|
* When the asterisk is used, than all the user-agents are included. |
23
|
|
|
* |
24
|
|
|
* @var string |
25
|
|
|
*/ |
26
|
|
|
const ALL_AGENTS = '*'; |
27
|
|
|
|
28
|
|
|
/** |
29
|
|
|
* Directive value. |
30
|
|
|
* |
31
|
|
|
* @var string |
32
|
|
|
*/ |
33
|
|
|
private $value = ''; |
34
|
|
|
|
35
|
|
|
/** |
36
|
|
|
* {@inheritdoc} |
37
|
|
|
*/ |
38
|
|
|
public function __construct(string $raw) |
39
|
|
|
{ |
40
|
|
|
if (!preg_match('/^user-agent:\s*([^# ]+).*/i', $raw, $matches)) { |
41
|
|
|
throw InvalidDirectiveException::create($raw); |
42
|
|
|
} |
43
|
|
|
|
44
|
|
|
$this->value = trim($matches[1]); |
45
|
|
|
} |
46
|
|
|
|
47
|
|
|
/** |
48
|
|
|
* {@inheritdoc} |
49
|
|
|
*/ |
50
|
|
|
public static function getField(): string |
51
|
|
|
{ |
52
|
|
|
return 'user-agent'; |
53
|
|
|
} |
54
|
|
|
|
55
|
|
|
/** |
56
|
|
|
* {@inheritdoc} |
57
|
|
|
*/ |
58
|
|
|
public function getValue(): string |
59
|
|
|
{ |
60
|
|
|
return $this->value; |
61
|
|
|
} |
62
|
|
|
|
63
|
|
|
/** |
64
|
|
|
* {@inheritdoc} |
65
|
|
|
*/ |
66
|
|
|
public function __toString(): string |
67
|
|
|
{ |
68
|
|
|
return sprintf('User-agent: %s', $this->value); |
69
|
|
|
} |
70
|
|
|
|
71
|
|
|
/** |
72
|
|
|
* Checks if a user-agent is matching current user agent. |
73
|
|
|
* |
74
|
|
|
* @param string $userAgent |
75
|
|
|
* |
76
|
|
|
* @return bool |
77
|
|
|
*/ |
78
|
|
|
public function isMatching(string $userAgent): bool |
79
|
|
|
{ |
80
|
|
|
// "*" matches any sequence of characters (zero or more) |
81
|
|
|
$value = str_replace('*', '.*', $this->value); |
82
|
|
|
|
83
|
|
|
return 1 === preg_match('#^'.$value.'#', trim($userAgent)); |
84
|
|
|
} |
85
|
|
|
} |
86
|
|
|
|