|
1
|
|
|
<?php |
|
2
|
|
|
|
|
3
|
|
|
/** |
|
4
|
|
|
* Linna Filter |
|
5
|
|
|
* |
|
6
|
|
|
* @author Sebastian Rapetti <[email protected]> |
|
7
|
|
|
* @copyright (c) 2018, Sebastian Rapetti |
|
8
|
|
|
* @license http://opensource.org/licenses/MIT MIT License |
|
9
|
|
|
*/ |
|
10
|
|
|
declare(strict_types=1); |
|
11
|
|
|
|
|
12
|
|
|
namespace Linna\Filter\Rules; |
|
13
|
|
|
|
|
14
|
|
|
use InvalidArgumentException; |
|
15
|
|
|
|
|
16
|
|
|
/** |
|
17
|
|
|
* Check if passed string match a regex |
|
18
|
|
|
*/ |
|
19
|
|
|
class Regex implements RuleValidateInterface |
|
20
|
|
|
{ |
|
21
|
|
|
/** |
|
22
|
|
|
* @var array Rule properties |
|
23
|
|
|
*/ |
|
24
|
|
|
public static $config = [ |
|
25
|
|
|
'full_class' => __CLASS__, |
|
26
|
|
|
'alias' => ['regex', 'rex', 'rx'], |
|
27
|
|
|
'args_count' => 1, |
|
28
|
|
|
'args_type' => ['string'] |
|
29
|
|
|
]; |
|
30
|
|
|
|
|
31
|
|
|
/** |
|
32
|
|
|
* @var string Error message |
|
33
|
|
|
*/ |
|
34
|
|
|
private $message = ''; |
|
35
|
|
|
|
|
36
|
|
|
/** |
|
37
|
|
|
* Validate. |
|
38
|
|
|
* |
|
39
|
|
|
* @return bool |
|
40
|
|
|
*/ |
|
41
|
4 |
|
public function validate(): bool |
|
42
|
|
|
{ |
|
43
|
4 |
|
$args = \func_get_args(); |
|
44
|
|
|
|
|
45
|
4 |
|
return $this->concreteValidate($args[0], $args[1]); |
|
46
|
|
|
} |
|
47
|
|
|
|
|
48
|
|
|
/** |
|
49
|
|
|
* Concrete validate. |
|
50
|
|
|
* |
|
51
|
|
|
* @param string $received |
|
52
|
|
|
* @param string $regex |
|
53
|
|
|
* |
|
54
|
|
|
* @return bool |
|
55
|
|
|
* |
|
56
|
|
|
* @throws InvalidArgumentException If a bad regex is provided. |
|
57
|
|
|
*/ |
|
58
|
4 |
|
private function concreteValidate(string $received, string $regex): bool |
|
59
|
|
|
{ |
|
60
|
4 |
|
$matches = []; |
|
61
|
|
|
|
|
62
|
|
|
//error suppressed with @ because if occours preg_match PHP show a warning |
|
63
|
|
|
//error replaced with exception |
|
64
|
4 |
|
$result = @\preg_match($regex, $received, $matches); |
|
65
|
|
|
|
|
66
|
4 |
|
if ($result === false) { |
|
67
|
1 |
|
throw new InvalidArgumentException("Invalid regex provided {$regex}."); |
|
68
|
|
|
} |
|
69
|
|
|
|
|
70
|
3 |
|
if ($result === 0) { |
|
71
|
2 |
|
$this->message = "Received value not match regex {$regex}"; |
|
72
|
2 |
|
return true; |
|
73
|
|
|
} |
|
74
|
|
|
|
|
75
|
1 |
|
return false; |
|
76
|
|
|
} |
|
77
|
|
|
|
|
78
|
|
|
/** |
|
79
|
|
|
* Return error message. |
|
80
|
|
|
* |
|
81
|
|
|
* @return string Error message |
|
82
|
|
|
*/ |
|
83
|
1 |
|
public function getMessage(): string |
|
84
|
|
|
{ |
|
85
|
1 |
|
return $this->message; |
|
86
|
|
|
} |
|
87
|
|
|
} |
|
88
|
|
|
|