Passed
Pull Request — master (#320)
by Dmitriy
02:52
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
                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