Passed
Pull Request — master (#222)
by Dmitriy
02:36
created

RegexValidator   A

Complexity

Total Complexity 7

Size/Duplication

Total Lines 24
Duplicated Lines 0 %

Test Coverage

Coverage 100%

Importance

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

1 Method

Rating   Name   Duplication   Size   Complexity  
B validate() 0 22 7
1
<?php
2
3
declare(strict_types=1);
4
5
namespace Yiisoft\Validator\Rule\Regex;
6
7
use Yiisoft\Validator\Result;
8
use Yiisoft\Validator\Rule\AtLeast\AtLeast;
9
use Yiisoft\Validator\Rule\RuleValidatorInterface;
10
use Yiisoft\Validator\ValidationContext;
11
use Yiisoft\Validator\ValidatorInterface;
12
use function is_string;
13
use Yiisoft\Validator\Exception\UnexpectedRuleException;
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 RegexValidator implements RuleValidatorInterface
21
{
22 14
    public function validate(mixed $value, object $rule, ValidatorInterface $validator, ?ValidationContext $context = null): Result
23
    {
24 14
        if (!$rule instanceof Regex) {
25 1
            throw new UnexpectedRuleException(Regex::class, $rule);
26
        }
27
28 13
        $result = new Result();
29
30 13
        if (!is_string($value)) {
31 7
            $result->addError($rule->incorrectInputMessage);
32
33 7
            return $result;
34
        }
35
36
        if (
37 6
            (!$rule->not && !preg_match($rule->pattern, $value)) ||
38 6
            ($rule->not && preg_match($rule->pattern, $value))
39
        ) {
40 3
            $result->addError($rule->message);
41
        }
42
43 6
        return $result;
44
    }
45
}
46