RegexHandler   A
last analyzed

Complexity

Total Complexity 7

Size/Duplication

Total Lines 27
Duplicated Lines 0 %

Test Coverage

Coverage 100%

Importance

Changes 1
Bugs 0 Features 0
Metric Value
wmc 7
eloc 14
c 1
b 0
f 0
dl 0
loc 27
ccs 13
cts 13
cp 1
rs 10

1 Method

Rating   Name   Duplication   Size   Complexity  
B validate() 0 25 7
1
<?php
2
3
declare(strict_types=1);
4
5
namespace Yiisoft\Validator\Rule;
6
7
use Yiisoft\Validator\Exception\UnexpectedRuleException;
8
use Yiisoft\Validator\Result;
9
use Yiisoft\Validator\RuleHandlerInterface;
10
use Yiisoft\Validator\ValidationContext;
11
12
use function is_string;
13
14
/**
15
 * Validates that the value matches the pattern specified in constructor.
16
 *
17
 * @see Regex
18
 */
19
final class RegexHandler implements RuleHandlerInterface
20
{
21 19
    public function validate(mixed $value, object $rule, ValidationContext $context): Result
22
    {
23 19
        if (!$rule instanceof Regex) {
24 1
            throw new UnexpectedRuleException(Regex::class, $rule);
25
        }
26
27 18
        $result = new Result();
28 18
        if (!is_string($value)) {
29 9
            return $result->addError($rule->getIncorrectInputMessage(), [
30 9
                'attribute' => $context->getTranslatedAttribute(),
31 9
                'type' => get_debug_type($value),
32
            ]);
33
        }
34
35
        if (
36 9
            (!$rule->isNot() && !preg_match($rule->getPattern(), $value)) ||
37 9
            ($rule->isNot() && preg_match($rule->getPattern(), $value))
38
        ) {
39 6
            $result->addError($rule->getMessage(), [
40 6
                'attribute' => $context->getTranslatedAttribute(),
41
                'value' => $value,
42
            ]);
43
        }
44
45 9
        return $result;
46
    }
47
}
48