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

RegexValidator::validate()   B

Complexity

Conditions 7
Paths 4

Size

Total Lines 22
Code Lines 11

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 11
CRAP Score 7

Importance

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