Passed
Push — master ( 5c2907...37dc07 )
by Sergei
24:35 queued 21:56
created

RegexHandler::__construct()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 2
Code Lines 0

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 1
CRAP Score 1

Importance

Changes 1
Bugs 0 Features 0
Metric Value
eloc 0
c 1
b 0
f 0
dl 0
loc 2
ccs 1
cts 1
cp 1
rs 10
cc 1
nc 1
nop 1
crap 1
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
                $rule->getIncorrectInputMessage(),
32
                [
33 7
                    'attribute' => $context->getAttribute(),
34
                    'value' => $value,
35
                ],
36
            );
37
38 7
            return $result;
39
        }
40
41
        if (
42 7
            (!$rule->isNot() && !preg_match($rule->getPattern(), $value)) ||
43 7
            ($rule->isNot() && preg_match($rule->getPattern(), $value))
44
        ) {
45 4
            $result->addError(
46 4
                $rule->getMessage(),
47
                [
48 4
                    'attribute' => $context->getAttribute(),
49
                    'value' => $value,
50
                ],
51
            );
52
        }
53
54 7
        return $result;
55
    }
56
}
57