1
|
|
|
<?php |
2
|
|
|
namespace JClaveau\LogicalFilter\Rule; |
3
|
|
|
|
4
|
|
|
/** |
5
|
|
|
* a regexp /^...$/ |
6
|
|
|
* |
7
|
|
|
* RegexpRule follow the PCRE syntax as PHP and MariaDb. |
8
|
|
|
* |
9
|
|
|
* @see https://mariadb.com/kb/en/library/pcre/ |
10
|
|
|
*/ |
11
|
|
|
class RegexpRule extends AbstractAtomicRule |
12
|
|
|
{ |
13
|
|
|
/** @var string operator */ |
14
|
|
|
const operator = 'regexp'; |
15
|
|
|
|
16
|
|
|
/** @var mixed $value */ |
17
|
|
|
protected $pattern; |
18
|
|
|
|
19
|
|
|
/** |
20
|
|
|
* |
21
|
|
|
* @param string $field The field to apply the rule on. |
22
|
|
|
* @param array $pattern The regular expression to match. |
23
|
|
|
* |
24
|
|
|
* @todo Support Posix? |
25
|
|
|
*/ |
26
|
13 |
|
public function __construct( $field, $pattern ) |
27
|
|
|
{ |
28
|
13 |
|
$this->field = $field; |
29
|
13 |
|
$this->pattern = $pattern; |
30
|
13 |
|
} |
31
|
|
|
|
32
|
|
|
/** |
33
|
|
|
*/ |
34
|
13 |
|
public function getPattern() |
35
|
|
|
{ |
36
|
13 |
|
return $this->pattern; |
37
|
|
|
} |
38
|
|
|
|
39
|
|
|
/** |
40
|
|
|
* @return array |
41
|
|
|
*/ |
42
|
13 |
|
public function getValues() |
43
|
|
|
{ |
44
|
13 |
|
return $this->getPattern(); |
45
|
|
|
} |
46
|
|
|
|
47
|
|
|
/** |
48
|
|
|
* By default, every atomic rule can have a solution by itself |
49
|
|
|
* |
50
|
|
|
* @return bool |
51
|
|
|
*/ |
52
|
4 |
|
public function hasSolution(array $simplification_options=[]) |
53
|
|
|
{ |
54
|
4 |
|
return true; |
55
|
|
|
} |
56
|
|
|
|
57
|
|
|
/** |
58
|
|
|
* Removes the delimiter and write the options in a MariaDB way. |
59
|
|
|
* |
60
|
|
|
* @param string The pattern written in a PHP PCRE way |
61
|
|
|
* @return string The pattern in a MariaDB syntax |
62
|
|
|
* |
63
|
|
|
* @todo Find more difference between MariaDB and PHP and handle them. |
64
|
|
|
* @see https://mariadb.com/kb/en/library/pcre/ |
65
|
|
|
*/ |
66
|
2 |
|
public static function php2mariadbPCRE($php_regexp) |
67
|
|
|
{ |
68
|
2 |
|
$delimiter = substr($php_regexp, 0, 1); |
69
|
2 |
|
$quoted_delimiter = preg_quote($delimiter, '#'); |
70
|
|
|
|
71
|
2 |
|
if ( ! preg_match("#^$quoted_delimiter(.*)$quoted_delimiter([^$quoted_delimiter]*)$#", $php_regexp, $matches)) { |
72
|
|
|
throw new \InvalidArgumentException( |
73
|
|
|
"The provided PCRE regular expression (with the delimiter '$delimiter') cannot be parsed: " |
74
|
|
|
.var_export($php_regexp, true) |
75
|
|
|
); |
76
|
|
|
} |
77
|
|
|
|
78
|
2 |
|
$pattern = $matches[1]; |
79
|
2 |
|
$options = $matches[2]; |
80
|
|
|
|
81
|
2 |
|
return ($options ? "(?$options)" : '') . $pattern; |
82
|
|
|
} |
83
|
|
|
|
84
|
|
|
/**/ |
85
|
|
|
} |
86
|
|
|
|