Passed
Pull Request — master (#335)
by Sergei
02:50
created

RegexHandler::validate()   B

Complexity

Conditions 7
Paths 4

Size

Total Lines 30
Code Lines 17

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 16
CRAP Score 7.0099

Importance

Changes 1
Bugs 0 Features 0
Metric Value
eloc 17
c 1
b 0
f 0
dl 0
loc 30
ccs 16
cts 17
cp 0.9412
rs 8.8333
cc 7
nc 4
nop 3
crap 7.0099
1
<?php
2
3
declare(strict_types=1);
4
5
namespace Yiisoft\Validator\Rule;
6
7
use Yiisoft\Translator\TranslatorInterface;
8
use Yiisoft\Validator\Exception\UnexpectedRuleException;
9
use Yiisoft\Validator\Result;
10
use Yiisoft\Validator\RuleHandlerInterface;
11
use Yiisoft\Validator\ValidationContext;
12
13
use function is_string;
14
15
/**
16
 * Validates that the value matches the pattern specified in constructor.
17
 *
18
 * If the {@see Regex::$not} is used, the rule will ensure the value do NOT match the pattern.
19
 */
20
final class RegexHandler implements RuleHandlerInterface
21
{
22 14
    public function __construct(private TranslatorInterface $translator)
23
    {
24
    }
25
26 14
    public function validate(mixed $value, object $rule, ValidationContext $context): Result
27
    {
28 14
        if (!$rule instanceof Regex) {
29
            throw new UnexpectedRuleException(Regex::class, $rule);
30
        }
31
32 14
        $result = new Result();
33
34 14
        if (!is_string($value)) {
35 7
            $formattedMessage = $this->translator->translate(
36 7
                $rule->getIncorrectInputMessage(),
37 7
                ['attribute' => $context->getAttribute(), 'value' => $value]
38
            );
39 7
            $result->addError($formattedMessage);
40
41 7
            return $result;
42
        }
43
44
        if (
45 7
            (!$rule->isNot() && !preg_match($rule->getPattern(), $value)) ||
46 7
            ($rule->isNot() && preg_match($rule->getPattern(), $value))
47
        ) {
48 4
            $formattedMessage = $this->translator->translate(
49 4
                $rule->getMessage(),
50 4
                ['attribute' => $context->getAttribute(), 'value' => $value]
51
            );
52 4
            $result->addError($formattedMessage);
53
        }
54
55 7
        return $result;
56
    }
57
}
58