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

GroupRuleHandler   A

Complexity

Total Complexity 4

Size/Duplication

Total Lines 25
Duplicated Lines 0 %

Test Coverage

Coverage 100%

Importance

Changes 0
Metric Value
wmc 4
eloc 12
dl 0
loc 25
ccs 12
cts 12
cp 1
rs 10
c 0
b 0
f 0

2 Methods

Rating   Name   Duplication   Size   Complexity  
A validate() 0 16 3
A __construct() 0 3 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\Formatter;
9
use Yiisoft\Validator\FormatterInterface;
10
use Yiisoft\Validator\Result;
11
use Yiisoft\Validator\ValidationContext;
12
13
/**
14
 * Validates a single value for a set of custom rules.
15
 */
16
class GroupRuleHandler implements RuleHandlerInterface
17
{
18
    private FormatterInterface $formatter;
19
20 6
    public function __construct(?FormatterInterface $formatter = null)
21
    {
22 6
        $this->formatter = $formatter ?? new Formatter();
23
    }
24
25 6
    public function validate(mixed $value, object $rule, ?ValidationContext $context = null): Result
26
    {
27 6
        if (!$rule instanceof GroupRule) {
28 1
            throw new UnexpectedRuleException(GroupRule::class, $rule);
29
        }
30
31 5
        $result = new Result();
32 5
        if (!$context?->getValidator()->validate($value, $rule->getRuleSet())->isValid()) {
33 4
            $formattedMessage = $this->formatter->format(
34 4
                $rule->getMessage(),
35 4
                ['attribute' => $context?->getAttribute(), 'value' => $value]
36
            );
37 4
            $result->addError($formattedMessage);
38
        }
39
40 5
        return $result;
41
    }
42
}
43