Test Failed
Pull Request — master (#364)
by
unknown
03:02
created

AtLeastHandler   A

Complexity

Total Complexity 7

Size/Duplication

Total Lines 32
Duplicated Lines 0 %

Test Coverage

Coverage 100%

Importance

Changes 3
Bugs 0 Features 0
Metric Value
wmc 7
eloc 16
c 3
b 0
f 0
dl 0
loc 32
ccs 13
cts 13
cp 1
rs 10

1 Method

Rating   Name   Duplication   Size   Complexity  
B validate() 0 30 7
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
use function is_array;
15
use function is_object;
16
17
/**
18
 * Checks if at least {@see AtLeast::$min} of many attributes are filled.
19 12
 */
20
final class AtLeastHandler implements RuleHandlerInterface
21 12
{
22 1
    public function validate(mixed $value, object $rule, ValidationContext $context): Result
23
    {
24
        if (!$rule instanceof AtLeast) {
25 11
            throw new UnexpectedRuleException(AtLeast::class, $rule);
26
        }
27 11
28 11
        $result = new Result();
29 10
30
        if (!is_array($value) && !is_object($value)) {
31
            return $result->addError($rule->getIncorrectInputMessage(), [
32
                'attribute' => $context->getAttribute(),
33 11
                'type' => get_debug_type($value),
34
            ]);
35 11
        }
36 3
37 3
        $filledCount = 0;
38
        foreach ($rule->getAttributes() as $attribute) {
39 3
            if (!(new SkipOnEmpty())(ArrayHelper::getValue($value, $attribute), $context->isAttributeMissing())) {
40 3
                $filledCount++;
41
            }
42
        }
43
44
        if ($filledCount < $rule->getMin()) {
45
            $result->addError($rule->getMessage(), [
46 11
                'attribute' => $context->getAttribute(),
47
                'min' => $rule->getMin(),
48
            ]);
49
        }
50
51
        return $result;
52
    }
53
}
54