Passed
Pull Request — master (#619)
by Alexander
06:58 queued 03:19
created

OneOfHandler::validate()   B

Complexity

Conditions 8
Paths 10

Size

Total Lines 30
Code Lines 15

Duplication

Lines 0
Ratio 0 %

Importance

Changes 2
Bugs 0 Features 0
Metric Value
cc 8
dl 0
loc 30
rs 8.4444
c 2
b 0
f 0
eloc 15
nc 10
nop 3
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
        $filledCount = 0;
43
        foreach ($rule->getAttributes() as $attribute) {
44
            if (!(new WhenEmpty())(ArrayHelper::getValue($value, $attribute), $context->isAttributeMissing())) {
45
                $filledCount++;
46
            }
47
48
            if ($filledCount > 1) {
49
                return $this->getGenericErrorResult($rule->getMessage(), $context);
50
            }
51
        }
52
53
        return $filledCount === 1 ? $result : $this->getGenericErrorResult($rule->getMessage(), $context);
54
    }
55
56
    private function getGenericErrorResult(string $message, ValidationContext $context): Result
57
    {
58
        return (new Result())->addError($message, [
59
            'attribute' => $context->getTranslatedAttribute(),
60
        ]);
61
    }
62
}
63