Passed
Pull Request — master (#320)
by Dmitriy
02:52
created

RegexHandler::validate()   B

Complexity

Conditions 7
Paths 4

Size

Total Lines 28
Code Lines 15

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 15
CRAP Score 7

Importance

Changes 1
Bugs 0 Features 0
Metric Value
eloc 15
c 1
b 0
f 0
dl 0
loc 28
ccs 15
cts 15
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\Exception\UnexpectedRuleException;
8
use Yiisoft\Validator\Result;
9
use Yiisoft\Validator\RuleHandlerInterface;
10
use Yiisoft\Validator\ValidationContext;
11
12
use function is_string;
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 15
    public function validate(mixed $value, object $rule, ValidationContext $context): Result
22
    {
23 15
        if (!$rule instanceof Regex) {
24 1
            throw new UnexpectedRuleException(Regex::class, $rule);
25
        }
26
27 14
        $result = new Result();
28
29 14
        if (!is_string($value)) {
30 7
            $result->addError(
31 7
                message: $rule->getIncorrectInputMessage(),
32 7
                parameters: ['value' => $value]
33
            );
34
35 7
            return $result;
36
        }
37
38
        if (
39 7
            (!$rule->isNot() && !preg_match($rule->getPattern(), $value)) ||
40 7
            ($rule->isNot() && preg_match($rule->getPattern(), $value))
41
        ) {
42 4
            $result->addError(
43 4
                message: $rule->getMessage(),
44 4
                parameters: ['value' => $value]
45
            );
46
        }
47
48 7
        return $result;
49
    }
50
}
51