1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
declare(strict_types=1); |
4
|
|
|
|
5
|
|
|
namespace Yiisoft\Validator\Rule; |
6
|
|
|
|
7
|
|
|
use Yiisoft\Translator\TranslatorInterface; |
8
|
|
|
use Yiisoft\Validator\Exception\UnexpectedRuleException; |
9
|
|
|
use Yiisoft\Validator\Result; |
10
|
|
|
use Yiisoft\Validator\RuleHandlerInterface; |
11
|
|
|
use Yiisoft\Validator\ValidationContext; |
12
|
|
|
|
13
|
|
|
use function is_string; |
14
|
|
|
|
15
|
|
|
/** |
16
|
|
|
* Validates that the value matches the pattern specified in constructor. |
17
|
|
|
* |
18
|
|
|
* If the {@see Regex::$not} is used, the rule will ensure the value do NOT match the pattern. |
19
|
|
|
*/ |
20
|
|
|
final class RegexHandler implements RuleHandlerInterface |
21
|
|
|
{ |
22
|
14 |
|
public function __construct(private TranslatorInterface $translator) |
23
|
|
|
{ |
24
|
|
|
} |
25
|
|
|
|
26
|
14 |
|
public function validate(mixed $value, object $rule, ValidationContext $context): Result |
27
|
|
|
{ |
28
|
14 |
|
if (!$rule instanceof Regex) { |
29
|
|
|
throw new UnexpectedRuleException(Regex::class, $rule); |
30
|
|
|
} |
31
|
|
|
|
32
|
14 |
|
$result = new Result(); |
33
|
|
|
|
34
|
14 |
|
if (!is_string($value)) { |
35
|
7 |
|
$formattedMessage = $this->translator->translate( |
36
|
7 |
|
$rule->getIncorrectInputMessage(), |
37
|
7 |
|
['attribute' => $context->getAttribute(), 'value' => $value] |
38
|
|
|
); |
39
|
7 |
|
$result->addError($formattedMessage); |
40
|
|
|
|
41
|
7 |
|
return $result; |
42
|
|
|
} |
43
|
|
|
|
44
|
|
|
if ( |
45
|
7 |
|
(!$rule->isNot() && !preg_match($rule->getPattern(), $value)) || |
46
|
7 |
|
($rule->isNot() && preg_match($rule->getPattern(), $value)) |
47
|
|
|
) { |
48
|
4 |
|
$formattedMessage = $this->translator->translate( |
49
|
4 |
|
$rule->getMessage(), |
50
|
4 |
|
['attribute' => $context->getAttribute(), 'value' => $value] |
51
|
|
|
); |
52
|
4 |
|
$result->addError($formattedMessage); |
53
|
|
|
} |
54
|
|
|
|
55
|
7 |
|
return $result; |
56
|
|
|
} |
57
|
|
|
} |
58
|
|
|
|