Passed
Pull Request — master (#245)
by Rustam
12:07
created

AtLeastHandler::validate()   A

Complexity

Conditions 5
Paths 7

Size

Total Lines 25
Code Lines 13

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 14
CRAP Score 5

Importance

Changes 1
Bugs 0 Features 0
Metric Value
eloc 13
c 1
b 0
f 0
dl 0
loc 25
ccs 14
cts 14
cp 1
rs 9.5222
cc 5
nc 7
nop 3
crap 5
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