Passed
Pull Request — master (#222)
by Alexander
04:47 queued 02:23
created

RegexValidator   A

Complexity

Total Complexity 6

Size/Duplication

Total Lines 20
Duplicated Lines 0 %

Test Coverage

Coverage 100%

Importance

Changes 1
Bugs 0 Features 0
Metric Value
eloc 9
c 1
b 0
f 0
dl 0
loc 20
ccs 9
cts 9
cp 1
rs 10
wmc 6

1 Method

Rating   Name   Duplication   Size   Complexity  
A validate() 0 18 6
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\RuleValidatorInterface;
9
use Yiisoft\Validator\ValidationContext;
10
use Yiisoft\Validator\ValidatorInterface;
11
use function is_string;
12
13
/**
14
 * Validates that the value matches the pattern specified in constructor.
15
 *
16
 * If the {@see Regex::$not} is used, the rule will ensure the value do NOT match the pattern.
17
 */
18
final class RegexValidator implements RuleValidatorInterface
19
{
20 13
    public function validate(mixed $value, object $rule, ValidatorInterface $validator, ?ValidationContext $context = null): Result
21
    {
22 13
        $result = new Result();
23
24 13
        if (!is_string($value)) {
25 7
            $result->addError($rule->incorrectInputMessage);
26
27 7
            return $result;
28
        }
29
30
        if (
31 6
            (!$rule->not && !preg_match($rule->pattern, $value)) ||
32 6
            ($rule->not && preg_match($rule->pattern, $value))
33
        ) {
34 3
            $result->addError($rule->message);
35
        }
36
37 6
        return $result;
38
    }
39
}
40