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

RegexHandler   A

Complexity

Total Complexity 8

Size/Duplication

Total Lines 39
Duplicated Lines 0 %

Test Coverage

Coverage 100%

Importance

Changes 0
Metric Value
wmc 8
eloc 19
dl 0
loc 39
ccs 19
cts 19
cp 1
rs 10
c 0
b 0
f 0

2 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 3 1
B validate() 0 30 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 14
    public function __construct(?FormatterInterface $formatter = null)
25
    {
26 14
        $this->formatter = $formatter ?? new Formatter();
27
    }
28
29 14
    public function validate(mixed $value, object $rule, ?ValidationContext $context = null): Result
30
    {
31 14
        if (!$rule instanceof Regex) {
32 1
            throw new UnexpectedRuleException(Regex::class, $rule);
33
        }
34
35 13
        $result = new Result();
36
37 13
        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 6
            (!$rule->isNot() && !preg_match($rule->getPattern(), $value)) ||
49 6
            ($rule->isNot() && preg_match($rule->getPattern(), $value))
50
        ) {
51 3
            $formattedMessage = $this->formatter->format(
52 3
                $rule->getMessage(),
53 3
                ['attribute' => $context?->getAttribute(), 'value' => $value]
54
            );
55 3
            $result->addError($formattedMessage);
56
        }
57
58 6
        return $result;
59
    }
60
}
61