Passed
Pull Request — master (#335)
by Sergei
02:50
created

RegexHandler   A

Complexity

Total Complexity 8

Size/Duplication

Total Lines 36
Duplicated Lines 0 %

Test Coverage

Coverage 94.44%

Importance

Changes 1
Bugs 0 Features 0
Metric Value
wmc 8
eloc 17
c 1
b 0
f 0
dl 0
loc 36
ccs 17
cts 18
cp 0.9444
rs 10

2 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 2 1
B validate() 0 30 7
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