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

RegexHandler::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 0
Metric Value
eloc 11
c 0
b 0
f 0
dl 0
loc 22
ccs 11
cts 11
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\Result;
8
use Yiisoft\Validator\ValidationContext;
9
use Yiisoft\Validator\ValidatorInterface;
10
use function is_string;
11
use Yiisoft\Validator\Exception\UnexpectedRuleException;
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 RegexHandler implements RuleHandlerInterface
19
{
20 14
    public function validate(mixed $value, object $rule, ?ValidationContext $context = null): Result
21
    {
22 14
        if (!$rule instanceof Regex) {
23 1
            throw new UnexpectedRuleException(Regex::class, $rule);
24
        }
25
26 13
        $result = new Result();
27
28 13
        if (!is_string($value)) {
29 7
            $result->addError($rule->incorrectInputMessage);
30
31 7
            return $result;
32
        }
33
34
        if (
35 6
            (!$rule->not && !preg_match($rule->pattern, $value)) ||
36 6
            ($rule->not && preg_match($rule->pattern, $value))
37
        ) {
38 3
            $result->addError($rule->message);
39
        }
40
41 6
        return $result;
42
    }
43
}
44