Passed
Pull Request — master (#222)
by Dmitriy
02:26
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
dl 0
loc 22
ccs 11
cts 11
cp 1
rs 8.8333
c 0
b 0
f 0
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\RuleHandlerInterface;
9
use Yiisoft\Validator\ValidationContext;
10
use Yiisoft\Validator\ValidatorInterface;
11
use function is_string;
12
use Yiisoft\Validator\Exception\UnexpectedRuleException;
13
14
/**
15
 * Validates that the value matches the pattern specified in constructor.
16
 *
17
 * If the {@see Regex::$not} is used, the rule will ensure the value do NOT match the pattern.
18
 */
19
final class RegexHandler implements RuleHandlerInterface
20
{
21 14
    public function validate(mixed $value, object $rule, ValidatorInterface $validator, ?ValidationContext $context = null): Result
22
    {
23 14
        if (!$rule instanceof Regex) {
24 1
            throw new UnexpectedRuleException(Regex::class, $rule);
25
        }
26
27 13
        $result = new Result();
28
29 13
        if (!is_string($value)) {
30 7
            $result->addError($rule->incorrectInputMessage);
31
32 7
            return $result;
33
        }
34
35
        if (
36 6
            (!$rule->not && !preg_match($rule->pattern, $value)) ||
37 6
            ($rule->not && preg_match($rule->pattern, $value))
38
        ) {
39 3
            $result->addError($rule->message);
40
        }
41
42 6
        return $result;
43
    }
44
}
45