Passed
Pull Request — master (#619)
by
unknown
06:15 queued 02:56
created

OneOfHandler   A

Complexity

Total Complexity 6

Size/Duplication

Total Lines 31
Duplicated Lines 0 %

Importance

Changes 2
Bugs 0 Features 0
Metric Value
eloc 14
c 2
b 0
f 0
dl 0
loc 31
rs 10
wmc 6

1 Method

Rating   Name   Duplication   Size   Complexity  
A validate() 0 29 6
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\EmptyCondition\WhenEmpty;
12
use Yiisoft\Validator\ValidationContext;
13
14
use function is_array;
15
use function is_object;
16
17
/**
18
 * Validates that one of specified attributes is filled.
19
 *
20
 * @see AtLeast
21
 */
22
final class OneOfHandler implements RuleHandlerInterface
23
{
24
    public function validate(mixed $value, object $rule, ValidationContext $context): Result
25
    {
26
        if (!$rule instanceof OneOf) {
27
            throw new UnexpectedRuleException(OneOf::class, $rule);
28
        }
29
30
        /** @var mixed $value */
31
        $value = $context->getParameter(ValidationContext::PARAMETER_VALUE_AS_ARRAY) ?? $value;
32
33
        $result = new Result();
34
35
        if (!is_array($value) && !is_object($value)) {
36
            return $result->addError($rule->getIncorrectInputMessage(), [
37
                'attribute' => $context->getTranslatedAttribute(),
38
                'type' => get_debug_type($value),
39
            ]);
40
        }
41
42
        foreach ($rule->getAttributes() as $attribute) {
43
            if (!(new WhenEmpty())(ArrayHelper::getValue($value, $attribute), $context->isAttributeMissing())) {
44
                return $result;
45
            }
46
        }
47
48
        $result->addError($rule->getMessage(), [
49
            'attribute' => $context->getTranslatedAttribute(),
50
        ]);
51
52
        return $result;
53
    }
54
}
55