0 follower

Final Class Yiisoft\Validator\Rule\UniqueIterableHandler

InheritanceYiisoft\Validator\Rule\UniqueIterableHandler
ImplementsYiisoft\Validator\RuleHandlerInterface

A handler for {@see UniqueIterable} rule. Validates uniqueness of each element of an iterable.

Method Details

Hide inherited methods

validate() public method

public Yiisoft\Validator\Result validate ( mixed $value, Yiisoft\Validator\RuleInterface $rule, Yiisoft\Validator\ValidationContext $context )
$value mixed
$rule Yiisoft\Validator\RuleInterface
$context Yiisoft\Validator\ValidationContext

                public function validate(mixed $value, RuleInterface $rule, ValidationContext $context): Result
{
    if (!$rule instanceof UniqueIterable) {
        throw new UnexpectedRuleException(UniqueIterable::class, $rule);
    }
    if (!is_iterable($value)) {
        return (new Result())->addError($rule->getIncorrectInputMessage(), [
            'property' => $context->getTranslatedProperty(),
            'Property' => $context->getCapitalizedTranslatedProperty(),
            'type' => get_debug_type($value),
        ]);
    }
    $stack = [];
    $previousItem = null;
    foreach ($value as $item) {
        if (!$this->isValueAllowedForItem($item)) {
            return (new Result())->addError($rule->getIncorrectItemValueMessage(), [
                'property' => $context->getTranslatedProperty(),
                'Property' => $context->getCapitalizedTranslatedProperty(),
                'type' => get_debug_type($item),
            ]);
        }
        if ($previousItem !== null && gettype($previousItem) !== gettype($item)) {
            return (new Result())->addError($rule->getDifferentTypesMessage(), [
                'property' => $context->getTranslatedProperty(),
                'Property' => $context->getCapitalizedTranslatedProperty(),
            ]);
        }
        $previousItem = $item;
        if (!empty($stack) && count($stack) !== count(array_unique($stack, flags: SORT_REGULAR))) {
            return (new Result())->addError($rule->getMessage(), [
                'property' => $context->getTranslatedProperty(),
                'Property' => $context->getCapitalizedTranslatedProperty(),
            ]);
        }
        if ($value instanceof Stringable) {
            $stack[] = (string) $value;
        } elseif ($value instanceof DateTimeInterface) {
            $stack[] = $value->getTimestamp();
        } else {
            $stack[] = $value;
        }
    }
    return new Result();
}