/
Expression.php
102 lines (90 loc) · 2.01 KB
/
Expression.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
<?php
namespace Bee4\RobotsTxt;
/**
* Class Expression
* Represent a matching expression rule
*
* @copyright Bee4 2016
* @author Stephane HULARD <s.hulard@chstudio.fr>
*/
class Expression
{
/**
* Raw definition
* @var string
*/
private $raw;
/**
* Rule pattern
* @var string
*/
private $pattern;
/**
* Initialize expression
* @param string $rule
*/
public function __construct($rule, $operator = self::ALLOW)
{
$this->raw = $rule;
}
/**
* Retrieve the raw rule definition
* @return string
*/
public function getRaw()
{
return $this->raw;
}
/**
* Transform current pattern to be used for matching
* @param string $raw
* @return string
*/
private function build()
{
$raw = $this->raw;
$ended = substr($raw, -1) === '$';
$raw = rtrim($raw, '*');
$raw = rtrim($raw, '$');
$parts = explode('*', $raw);
array_walk($parts, function (&$part) {
$part = preg_quote($part, '/');
});
return implode('.*', $parts).($ended?'':'.*');
}
/**
* Check if current expression is contained in another
* @param Expression $exp
* @return boolean
*/
public function contained(Expression $exp)
{
return $exp->contains($this);
}
/**
* Check if current expression contains another
* @param Expression $exp
* @return boolean
*/
public function contains(Expression $exp)
{
return preg_match('/^'.(string)$this.'$/', $exp->getRaw()) === 1;
}
/**
* Retrieve the regex pattern corresponding to the Expression
* @return string
*/
public function getPattern()
{
$this->pattern = $this->pattern ?: $this->build();
return $this->pattern;
}
/**
* Transform expression to string
* @return string
*/
public function __toString()
{
return $this->getPattern();
}
}