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

RegexValidator::validate()   A

Complexity

Conditions 6
Paths 3

Size

Total Lines 18
Code Lines 9

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 9
CRAP Score 6

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 6
eloc 9
c 1
b 0
f 0
nc 3
nop 4
dl 0
loc 18
ccs 9
cts 9
cp 1
crap 6
rs 9.2222
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