Passed
Pull Request — master (#320)
by Dmitriy
02:52
created

AtLeastHandler::__construct()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 2
Code Lines 0

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 1
CRAP Score 1

Importance

Changes 1
Bugs 0 Features 0
Metric Value
eloc 0
c 1
b 0
f 0
dl 0
loc 2
ccs 1
cts 1
cp 1
rs 10
cc 1
nc 1
nop 1
crap 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\Result;
9
use Yiisoft\Validator\Rule\Trait\EmptyCheckTrait;
10
use Yiisoft\Validator\RuleHandlerInterface;
11
use Yiisoft\Validator\ValidationContext;
12
13
/**
14
 * Checks if at least {@see AtLeast::$min} of many attributes are filled.
15
 */
16
final class AtLeastHandler implements RuleHandlerInterface
17
{
18
    use EmptyCheckTrait;
19
20 6
    public function validate(mixed $value, object $rule, ValidationContext $context): Result
21
    {
22 6
        if (!$rule instanceof AtLeast) {
23 1
            throw new UnexpectedRuleException(AtLeast::class, $rule);
24
        }
25
26 5
        $filledCount = 0;
27
28 5
        foreach ($rule->getAttributes() as $attribute) {
29 5
            if (!$this->isEmpty($value->{$attribute})) {
30 4
                $filledCount++;
31
            }
32
        }
33
34 5
        $result = new Result();
35
36 5
        if ($filledCount < $rule->getMin()) {
37 3
            $result->addError(
38 3
                message: $rule->getMessage(),
39 3
                parameters: ['min' => $rule->getMin(), 'value' => $value]
40
            );
41
        }
42
43 5
        return $result;
44
    }
45
}
46