Passed
Pull Request — master (#222)
by Dmitriy
16:32 queued 14:10
created

AtLeastHandler   A

Complexity

Total Complexity 5

Size/Duplication

Total Lines 25
Duplicated Lines 0 %

Test Coverage

Coverage 100%

Importance

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

1 Method

Rating   Name   Duplication   Size   Complexity  
A validate() 0 21 5
1
<?php
2
3
declare(strict_types=1);
4
5
namespace Yiisoft\Validator\Rule\AtLeast;
6
7
use Yiisoft\Validator\Exception\UnexpectedRuleException;
8
use Yiisoft\Validator\Result;
9
use Yiisoft\Validator\Rule\EmptyCheckTrait;
10
use Yiisoft\Validator\Rule\RuleHandlerInterface;
11
use Yiisoft\Validator\ValidationContext;
12
use Yiisoft\Validator\ValidatorInterface;
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 6
    public function validate(mixed $value, object $rule, ValidatorInterface $validator, ?ValidationContext $context = null): Result
22
    {
23 6
        if (!$rule instanceof AtLeast) {
24 1
            throw new UnexpectedRuleException(AtLeast::class, $rule);
25
        }
26
27 5
        $filledCount = 0;
28
29 5
        foreach ($rule->attributes as $attribute) {
30 5
            if (!$this->isEmpty($value->{$attribute})) {
31 4
                $filledCount++;
32
            }
33
        }
34
35 5
        $result = new Result();
36
37 5
        if ($filledCount < $rule->min) {
38 3
            $result->addError($rule->message, ['min' => $rule->min]);
39
        }
40
41 5
        return $result;
42
    }
43
}
44