Passed
Pull Request — master (#222)
by Rustam
02:32
created

RegexHandler::validate()   B

Complexity

Conditions 7
Paths 4

Size

Total Lines 30
Code Lines 17

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 17
CRAP Score 7

Importance

Changes 0
Metric Value
eloc 17
dl 0
loc 30
ccs 17
cts 17
cp 1
rs 8.8333
c 0
b 0
f 0
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\Formatter;
9
use Yiisoft\Validator\FormatterInterface;
10
use Yiisoft\Validator\Result;
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
    private FormatterInterface $formatter;
23
24 15
    public function __construct(?FormatterInterface $formatter = null)
25
    {
26 15
        $this->formatter = $formatter ?? new Formatter();
27
    }
28
29 15
    public function validate(mixed $value, object $rule, ?ValidationContext $context = null): Result
30
    {
31 15
        if (!$rule instanceof Regex) {
32 1
            throw new UnexpectedRuleException(Regex::class, $rule);
33
        }
34
35 14
        $result = new Result();
36
37 14
        if (!is_string($value)) {
38 7
            $formattedMessage = $this->formatter->format(
39 7
                $rule->getIncorrectInputMessage(),
40 7
                ['attribute' => $context?->getAttribute(), 'value' => $value]
41
            );
42 7
            $result->addError($formattedMessage);
43
44 7
            return $result;
45
        }
46
47
        if (
48 7
            (!$rule->isNot() && !preg_match($rule->getPattern(), $value)) ||
49 7
            ($rule->isNot() && preg_match($rule->getPattern(), $value))
50
        ) {
51 4
            $formattedMessage = $this->formatter->format(
52 4
                $rule->getMessage(),
53 4
                ['attribute' => $context?->getAttribute(), 'value' => $value]
54
            );
55 4
            $result->addError($formattedMessage);
56
        }
57
58 7
        return $result;
59
    }
60
}
61