Passed
Push — master ( 5c2907...37dc07 )
by Sergei
24:35 queued 21:56
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\Arrays\ArrayHelper;
8
use Yiisoft\Validator\Exception\UnexpectedRuleException;
9
use Yiisoft\Validator\Result;
10
use Yiisoft\Validator\RuleHandlerInterface;
11
use Yiisoft\Validator\SkipOnEmptyCallback\SkipOnEmpty;
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 12
    public function validate(mixed $value, object $rule, ValidationContext $context): Result
20
    {
21 12
        if (!$rule instanceof AtLeast) {
22 1
            throw new UnexpectedRuleException(AtLeast::class, $rule);
23
        }
24
25 11
        $filledCount = 0;
26
27 11
        foreach ($rule->getAttributes() as $attribute) {
28 11
            if (!(new SkipOnEmpty())(ArrayHelper::getValue($value, $attribute), $context->isAttributeMissing())) {
29 10
                $filledCount++;
30
            }
31
        }
32
33 11
        $result = new Result();
34
35 11
        if ($filledCount < $rule->getMin()) {
36 3
            $result->addError(
37 3
                $rule->getMessage(),
38
                [
39 3
                    'min' => $rule->getMin(),
40 3
                    'attribute' => $context->getAttribute(),
41
                    'value' => $value,
42
                ],
43
            );
44
        }
45
46 11
        return $result;
47
    }
48
}
49