0 follower

Final Class Yiisoft\Validator\Rule\NumberHandler

InheritanceYiisoft\Validator\Rule\NumberHandler
ImplementsYiisoft\Validator\RuleHandlerInterface

Validates that the value is a number.

See also Yiisoft\Validator\Rule\Number.

Public Methods

Hide inherited methods

Method Description Defined By
validate() Yiisoft\Validator\Rule\NumberHandler

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 AbstractNumber) {
        throw new UnexpectedRuleException(AbstractNumber::class, $rule);
    }
    $result = new Result();
    if (is_bool($value) || !is_scalar($value)) {
        $result->addError($rule->getIncorrectInputMessage(), [
            'property' => $context->getTranslatedProperty(),
            'Property' => $context->getCapitalizedTranslatedProperty(),
            'type' => get_debug_type($value),
        ]);
        return $result;
    }
    if (!preg_match($rule->getPattern(), NumericHelper::normalize($value))) {
        $result->addError($rule->getNotNumberMessage(), [
            'property' => $context->getTranslatedProperty(),
            'Property' => $context->getCapitalizedTranslatedProperty(),
            'value' => $value,
        ]);
    } elseif ($rule->getMin() !== null && $value < $rule->getMin()) {
        $result->addError($rule->getLessThanMinMessage(), [
            'min' => $rule->getMin(),
            'property' => $context->getTranslatedProperty(),
            'Property' => $context->getCapitalizedTranslatedProperty(),
            'value' => $value,
        ]);
    } elseif ($rule->getMax() !== null && $value > $rule->getMax()) {
        $result->addError($rule->getGreaterThanMaxMessage(), [
            'max' => $rule->getMax(),
            'property' => $context->getTranslatedProperty(),
            'Property' => $context->getCapitalizedTranslatedProperty(),
            'value' => $value,
        ]);
    }
    return $result;
}