RegexHandler::validate()   B
last analyzed

Complexity

Conditions 7
Paths 4

Size

Total Lines 25
Code Lines 14

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 13
CRAP Score 7

Importance

Changes 1
Bugs 0 Features 0
Metric Value
eloc 14
c 1
b 0
f 0
dl 0
loc 25
ccs 13
cts 13
cp 1
rs 8.8333
cc 7
nc 4
nop 3
crap 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