|
1
|
|
|
<?php |
|
2
|
|
|
|
|
3
|
|
|
declare(strict_types=1); |
|
4
|
|
|
|
|
5
|
|
|
namespace Yiisoft\Validator\Rule; |
|
6
|
|
|
|
|
7
|
|
|
use Yiisoft\Validator\HasValidationErrorMessage; |
|
8
|
|
|
use Yiisoft\Validator\Result; |
|
9
|
|
|
use Yiisoft\Validator\Rule; |
|
10
|
|
|
use Yiisoft\Validator\ValidationContext; |
|
11
|
|
|
|
|
12
|
|
|
use function is_array; |
|
13
|
|
|
|
|
14
|
|
|
/** |
|
15
|
|
|
* RegularExpressionValidator validates that the attribute value matches the pattern specified in constructor. |
|
16
|
|
|
* |
|
17
|
|
|
* If the {@see MatchRegularExpression::not()} is used, the validator will ensure the attribute value do NOT match |
|
18
|
|
|
* the pattern. |
|
19
|
|
|
*/ |
|
20
|
|
|
class MatchRegularExpression extends Rule |
|
21
|
|
|
{ |
|
22
|
|
|
use HasValidationErrorMessage; |
|
23
|
|
|
|
|
24
|
|
|
/** |
|
25
|
|
|
* @var string the regular expression to be matched with |
|
26
|
|
|
*/ |
|
27
|
|
|
private string $pattern; |
|
28
|
|
|
/** |
|
29
|
|
|
* @var bool whether to invert the validation logic. Defaults to false. If set to true, |
|
30
|
|
|
* the regular expression defined via {@see pattern} should NOT match the attribute value. |
|
31
|
|
|
*/ |
|
32
|
|
|
private bool $not = false; |
|
33
|
|
|
|
|
34
|
|
|
private string $message = 'Value is invalid.'; |
|
35
|
|
|
|
|
36
|
|
|
/** |
|
37
|
|
|
* @param string $pattern The regular expression to be matched with. |
|
38
|
|
|
*/ |
|
39
|
2 |
|
public static function rule(string $pattern): self |
|
40
|
|
|
{ |
|
41
|
2 |
|
$rule = new self(); |
|
42
|
2 |
|
$rule->pattern = $pattern; |
|
43
|
2 |
|
return $rule; |
|
44
|
|
|
} |
|
45
|
|
|
|
|
46
|
1 |
|
protected function validateValue($value, ValidationContext $context = null): Result |
|
47
|
|
|
{ |
|
48
|
1 |
|
$result = new Result(); |
|
49
|
|
|
|
|
50
|
1 |
|
$valid = !is_array($value) && |
|
51
|
1 |
|
((!$this->not && preg_match($this->pattern, $value)) |
|
52
|
1 |
|
|| ($this->not && !preg_match($this->pattern, $value))); |
|
53
|
|
|
|
|
54
|
1 |
|
if (!$valid) { |
|
55
|
1 |
|
$result->addError($this->formatMessage($this->message)); |
|
56
|
|
|
} |
|
57
|
|
|
|
|
58
|
1 |
|
return $result; |
|
59
|
|
|
} |
|
60
|
|
|
|
|
61
|
1 |
|
public function not(): self |
|
62
|
|
|
{ |
|
63
|
1 |
|
$new = clone $this; |
|
64
|
1 |
|
$new->not = true; |
|
65
|
1 |
|
return $new; |
|
66
|
|
|
} |
|
67
|
|
|
|
|
68
|
2 |
|
public function getOptions(): array |
|
69
|
|
|
{ |
|
70
|
2 |
|
return array_merge( |
|
71
|
2 |
|
parent::getOptions(), |
|
72
|
|
|
[ |
|
73
|
2 |
|
'message' => $this->formatMessage($this->message), |
|
74
|
2 |
|
'not' => $this->not, |
|
75
|
2 |
|
'pattern' => $this->pattern, |
|
76
|
|
|
], |
|
77
|
|
|
); |
|
78
|
|
|
} |
|
79
|
|
|
} |
|
80
|
|
|
|