0 follower

Final Class Yiisoft\Validator\Rule\IpHandler

InheritanceYiisoft\Validator\Rule\IpHandler
ImplementsYiisoft\Validator\RuleHandlerInterface

Checks if the value is a valid IPv4/IPv6 address or subnet.

See also Yiisoft\Validator\Rule\Ip.

Public Methods

Hide inherited methods

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

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 Ip) {
        throw new UnexpectedRuleException(Ip::class, $rule);
    }
    if (!is_string($value)) {
        return (new Result())->addError($rule->getIncorrectInputMessage(), [
            'property' => $context->getTranslatedProperty(),
            'Property' => $context->getCapitalizedTranslatedProperty(),
            'type' => get_debug_type($value),
        ]);
    }
    if (preg_match(self::getIpParsePattern(), $value, $matches) === 0) {
        return self::getGenericErrorResult($rule->getMessage(), $context, $value);
    }
    $negation = !empty($matches['not'] ?? null);
    $ip = $matches['ip'];
    $cidr = $matches['cidr'] ?? null;
    $ipCidr = $matches['ipCidr'];
    /**
     * Exception handling and validation in IpHelper are not needed because of the check above (regular expression
     * in "getIpParsePattern()").
     *
     * @infection-ignore-all
     */
    $ipVersion = IpHelper::getIpVersion($ip, validate: false);
    $result = self::validateValueParts($rule, $cidr, $negation, $value, $context);
    if ($result !== null) {
        return $result;
    }
    $result = self::validateVersion($rule, $ipVersion, $value, $context);
    if ($result !== null) {
        return $result;
    }
    $result = self::validateCidr($rule, $cidr, $ipCidr, $value, $context);
    return $result ?? new Result();
}