Final Class Yiisoft\Validator\Rule\FilledOnlyOneOfHandler
| Inheritance | Yiisoft\ |
|---|---|
| Implements | Yiisoft\ |
| Uses Traits | Yiisoft\ |
Validates that only one of specified properties is filled.
See also Yiisoft\
Public Methods
| Method | Description | Defined By |
|---|---|---|
| validate() | Yiisoft\ |
Method Details
| public Yiisoft\ | ||
| $value | mixed | |
| $rule | Yiisoft\ |
|
| $context | Yiisoft\ |
|
public function validate(mixed $value, RuleInterface $rule, ValidationContext $context): Result
{
if (!$rule instanceof FilledOnlyOneOf) {
throw new UnexpectedRuleException(FilledOnlyOneOf::class, $rule);
}
/** @var mixed $value */
$value = $context->getParameter(ValidationContext::PARAMETER_VALUE_AS_ARRAY) ?? $value;
$result = new Result();
if (!is_array($value) && !is_object($value)) {
return $result->addError($rule->getIncorrectInputMessage(), [
'property' => $context->getTranslatedProperty(),
'Property' => $context->getCapitalizedTranslatedProperty(),
'type' => get_debug_type($value),
]);
}
$filledCount = 0;
foreach ($rule->getProperties() as $property) {
if (!(new WhenEmpty())(ArrayHelper::getValue($value, $property), $context->isPropertyMissing())) {
$filledCount++;
}
if ($filledCount > 1) {
return $this->getGenericErrorResult($rule, $context);
}
}
return $filledCount === 1 ? $result : $this->getGenericErrorResult($rule, $context);
}
User Contributed Notes
Leave a comment
Join the conversation to share a note.