Passed
Push — master ( 0363dc...b69f59 )
by Rustam
02:19
created

AtLeastHandler   A

Complexity

Total Complexity 6

Size/Duplication

Total Lines 36
Duplicated Lines 0 %

Test Coverage

Coverage 100%

Importance

Changes 1
Bugs 0 Features 0
Metric Value
wmc 6
eloc 17
c 1
b 0
f 0
dl 0
loc 36
ccs 16
cts 16
cp 1
rs 10

2 Methods

Rating   Name   Duplication   Size   Complexity  
A validate() 0 25 5
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\Rule\Trait\EmptyCheckTrait;
12
use Yiisoft\Validator\ValidationContext;
13
14
/**
15
 * Checks if at least {@see AtLeast::$min} of many attributes are filled.
16
 */
17
final class AtLeastHandler implements RuleHandlerInterface
18
{
19
    use EmptyCheckTrait;
20
21
    private FormatterInterface $formatter;
22
23 6
    public function __construct(?FormatterInterface $formatter = null)
24
    {
25 6
        $this->formatter = $formatter ?? new Formatter();
26
    }
27
28 6
    public function validate(mixed $value, object $rule, ?ValidationContext $context = null): Result
29
    {
30 6
        if (!$rule instanceof AtLeast) {
31 1
            throw new UnexpectedRuleException(AtLeast::class, $rule);
32
        }
33
34 5
        $filledCount = 0;
35
36 5
        foreach ($rule->getAttributes() as $attribute) {
37 5
            if (!$this->isEmpty($value->{$attribute})) {
38 4
                $filledCount++;
39
            }
40
        }
41
42 5
        $result = new Result();
43
44 5
        if ($filledCount < $rule->getMin()) {
45 3
            $formattedMessage = $this->formatter->format(
46 3
                $rule->getMessage(),
47 3
                ['min' => $rule->getMin(), 'attribute' => $context?->getAttribute(), 'value' => $value]
48
            );
49 3
            $result->addError($formattedMessage);
50
        }
51
52 5
        return $result;
53
    }
54
}
55