0 follower

Final Class Yiisoft\Validator\Rule\Ip

InheritanceYiisoft\Validator\Rule\Ip
ImplementsYiisoft\Validator\DumpedRuleInterface, Yiisoft\Validator\SkipOnEmptyInterface, Yiisoft\Validator\SkipOnErrorInterface, Yiisoft\Validator\WhenInterface
Uses TraitsYiisoft\Validator\Rule\Trait\SkipOnEmptyTrait, Yiisoft\Validator\Rule\Trait\SkipOnErrorTrait, Yiisoft\Validator\Rule\Trait\WhenTrait

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

See also Yiisoft\Validator\Rule\IpHandler.

Public Methods

Hide inherited methods

Method Description Defined By
__construct() Yiisoft\Validator\Rule\Ip
getHandler() Yiisoft\Validator\Rule\Ip
getHasSubnetMessage() Get error message used when validation fails due to $allowSubnet is false, but CIDR prefix is present. Yiisoft\Validator\Rule\Ip
getIncorrectInputMessage() Get a message used when the input it incorrect. Yiisoft\Validator\Rule\Ip
getIpRanges() Yiisoft\Validator\Rule\Ip
getIpv4NotAllowedMessage() Get an error message used when validation fails due to the disabled IPv4 validation when $allowIpv4 is set. Yiisoft\Validator\Rule\Ip
getIpv6NotAllowedMessage() Get error message used when validation fails due to the disabled IPv6 validation when $allowIpv6 is set. Yiisoft\Validator\Rule\Ip
getMessage() Get an error message used when validation fails due to the wrong IP address format. Yiisoft\Validator\Rule\Ip
getName() Yiisoft\Validator\Rule\Ip
getNetworks() Get custom network aliases, that can be used in $ranges. Yiisoft\Validator\Rule\Ip
getNoSubnetMessage() Get error message used when validation fails due to $allowSubnet is used, but the CIDR prefix is not set. Yiisoft\Validator\Rule\Ip
getNotInRangeMessage() Get error message used when validation fails due to IP address is not allowed by $ranges check. Yiisoft\Validator\Rule\Ip
getOptions() Yiisoft\Validator\Rule\Ip
getRanges() Get the IPv4 or IPv6 ranges that are allowed or forbidden. Yiisoft\Validator\Rule\Ip
getSkipOnEmpty() A getter for $skipOnEmpty property. Yiisoft\Validator\Rule\Trait\SkipOnEmptyTrait
getWhen() A getter for $when property. Yiisoft\Validator\Rule\Trait\WhenTrait
getWrongCidrMessage() Get error message used when validation fails due to the wrong CIDR when $allowSubnet is set. Yiisoft\Validator\Rule\Ip
isAllowed() Whether the IP address with specified CIDR is allowed according to the $ranges list. Yiisoft\Validator\Rule\Ip
isIpv4Allowed() Whether the validating value can be an IPv4 address Yiisoft\Validator\Rule\Ip
isIpv6Allowed() Whether the validating value can be an IPv6 address. Yiisoft\Validator\Rule\Ip
isNegationAllowed() Whether an address may have a ! negation character at the beginning. Yiisoft\Validator\Rule\Ip
isSubnetAllowed() Whether the address can be an IP with CIDR subnet, like 192.168.10.0/24. Yiisoft\Validator\Rule\Ip
isSubnetRequired() Whether subnet is required. Yiisoft\Validator\Rule\Ip
shouldSkipOnError() A getter for $skipOnError property. Yiisoft\Validator\Rule\Trait\SkipOnErrorTrait
skipOnEmpty() An immutable setter to change $skipOnEmpty property. Yiisoft\Validator\Rule\Trait\SkipOnEmptyTrait
skipOnError() An immutable setter to change $skipOnError property. Yiisoft\Validator\Rule\Trait\SkipOnErrorTrait
when() An immutable setter to change $when property. Yiisoft\Validator\Rule\Trait\WhenTrait

Method Details

Hide inherited methods

__construct() public method

public __construct( array $networks = [], boolean $allowIpv4 true, boolean $allowIpv6 true, boolean $allowSubnet false, boolean $requireSubnet false, boolean $allowNegation false, string $incorrectInputMessage '{Property} must be a string. {type} given.', string $message '{Property} must be a valid IP address.', string $ipv4NotAllowedMessage '{Property} must not be an IPv4 address.', string $ipv6NotAllowedMessage '{Property} must not be an IPv6 address.', string $wrongCidrMessage '{Property} contains wrong subnet mask.', string $noSubnetMessage '{Property} must be an IP address with specified subnet.', string $hasSubnetMessage '{Property} must not be a subnet.', string $notInRangeMessage '{Property} is not in the allowed range.', string[] $ranges = [], boolean|callable|null $skipOnEmpty null, boolean $skipOnError false, Closure|null $when null ): mixed
$networks array

Custom network aliases, that can be used in $ranges:

  • key - alias name.
  • value - array of strings. String can be an IP range, IP address or another alias. String can be negated with \Yiisoft\Validator\Rule\NEGATION_CHARACTER (independent of $allowNegation option).

The following aliases are defined by default in $defaultNetworks and will be merged with custom ones:

  • *: any.
  • any: 0.0.0.0/0, ::/0.
  • private: 10.0.0.0/8, 172.16.0.0/12, 192.168.0.0/16, fd00::/8.
  • multicast: 224.0.0.0/4, ff00::/8.
  • linklocal: 169.254.0.0/16, fe80::/10.
  • localhost: 127.0.0.0/8', ::1.
  • documentation: 192.0.2.0/24, 198.51.100.0/24, 203.0.113.0/24, 2001:db8::/32.
  • system: multicast, linklocal, localhost, documentation.
$allowIpv4 boolean

Whether the validating value can be an IPv4 address. Defaults to true.

$allowIpv6 boolean

Whether the validating value can be an IPv6 address. Defaults to true.

$allowSubnet boolean

Whether the address can be an IP with CIDR subnet, like 192.168.10.0/24. The following values are possible:

  • false - the address must not have a subnet (default).
  • true - specifying a subnet is optional.
$requireSubnet boolean

Whether subnet is required.

$allowNegation boolean

Whether an address may have a ! negation character at the beginning.

$incorrectInputMessage string

A message used when the input it incorrect.

You may use the following placeholders in the message:

  • {property}: the translated label of the property being validated.
  • {type}: the type of the value being validated.
$message string

Error message used when validation fails due to the wrong IP address format.

You may use the following placeholders in the message:

  • {property}: the translated label of the property being validated.
  • {value}: the value being validated.
$ipv4NotAllowedMessage string

Error message used when validation fails due to the disabled IPv4 validation when $allowIpv4 is set.

You may use the following placeholders in the message:

  • {property}: the translated label of the property being validated.
  • {value}: the value being validated.
$ipv6NotAllowedMessage string

Error message used when validation fails due to the disabled IPv6 validation when $allowIpv6 is set.

You may use the following placeholders in the message:

  • {property}: the translated label of the property being validated.
  • {value}: the value being validated.
$wrongCidrMessage string

String Error message used when validation fails due to the wrong CIDR when $allowSubnet is set.

You may use the following placeholders in the message:

  • {property}: the translated label of the property being validated.
  • {value}: the value being validated.
$noSubnetMessage string

Error message used when validation fails due to $allowSubnet is used, but the CIDR prefix is not set.

You may use the following placeholders in the message:

  • {property}: the translated label of the property being validated.
  • {value}: the value being validated.
$hasSubnetMessage string

Error message used when validation fails due to $allowSubnet is false, but CIDR prefix is present.

You may use the following placeholders in the message:

  • {property}: the translated label of the property being validated.
  • {value}: the value being validated.
$notInRangeMessage string

Error message used when validation fails due to IP address is not allowed by $ranges check.

You may use the following placeholders in the message:

  • {property}: the translated label of the property being validated.
  • {value}: the value being validated.
$ranges string[]

The IPv4 or IPv6 ranges that are allowed or forbidden.

The following preparation tasks are performed:

  • Recursively substitute aliases (described in $networks) with their values.
  • Remove duplicates.

When the array is empty or the option not set, all IP addresses are allowed.

Otherwise, the rules are checked sequentially until the first match is found. An IP address is forbidden, when it has not matched any of the rules.

Example:

new Ip(ranges: [
    '192.168.10.128'
    '!192.168.10.0/24',
    'any' // allows any other IP addresses
]);

In this example, access is allowed for all the IPv4 and IPv6 addresses excluding the 192.168.10.0/24 subnet. IPv4 address 192.168.10.128 is also allowed, because it is listed before the restriction.

$skipOnEmpty boolean|callable|null

Whether to skip this rule if the validated value is empty / not passed. See Yiisoft\Validator\SkipOnEmptyInterface.

$skipOnError boolean

Whether to skip this rule if any of the previous rules gave an error. See Yiisoft\Validator\SkipOnErrorInterface.

$when Closure|null

A callable to define a condition for applying the rule. See Yiisoft\Validator\WhenInterface.

throws InvalidArgumentException

If configuration is wrong.

                public function __construct(
    array $networks = [],
    private bool $allowIpv4 = true,
    private bool $allowIpv6 = true,
    private bool $allowSubnet = false,
    private bool $requireSubnet = false,
    private bool $allowNegation = false,
    private string $incorrectInputMessage = '{Property} must be a string. {type} given.',
    private string $message = '{Property} must be a valid IP address.',
    private string $ipv4NotAllowedMessage = '{Property} must not be an IPv4 address.',
    private string $ipv6NotAllowedMessage = '{Property} must not be an IPv6 address.',
    private string $wrongCidrMessage = '{Property} contains wrong subnet mask.',
    private string $noSubnetMessage = '{Property} must be an IP address with specified subnet.',
    private string $hasSubnetMessage = '{Property} must not be a subnet.',
    private string $notInRangeMessage = '{Property} is not in the allowed range.',
    array $ranges = [],
    bool|callable|null $skipOnEmpty = null,
    private bool $skipOnError = false,
    private ?Closure $when = null,
) {
    if (!$this->allowIpv4 && !$this->allowIpv6) {
        throw new InvalidArgumentException('Both IPv4 and IPv6 checks can not be disabled at the same time.');
    }
    if ($requireSubnet) {
        // Might be a bug of XDebug, because this line is covered by tests (see "IpTest").
        // @codeCoverageIgnoreStart
        $this->allowSubnet = true;
        // @codeCoverageIgnoreEnd
    }
    $this->ranges = new IpRanges($ranges, $networks);
    $this->skipOnEmpty = $skipOnEmpty;
}

            
getHandler() public method

public getHandler( ): string

                public function getHandler(): string
{
    return IpHandler::class;
}

            
getHasSubnetMessage() public method

Get error message used when validation fails due to $allowSubnet is false, but CIDR prefix is present.

public getHasSubnetMessage( ): string
return string

Error message.

                public function getHasSubnetMessage(): string
{
    return $this->hasSubnetMessage;
}

            
getIncorrectInputMessage() public method

Get a message used when the input it incorrect.

public getIncorrectInputMessage( ): string
return string

Error message

                public function getIncorrectInputMessage(): string
{
    return $this->incorrectInputMessage;
}

            
getIpRanges() public method

public getIpRanges( ): \Yiisoft\NetworkUtilities\IpRanges

                public function getIpRanges(): IpRanges
{
    return $this->ranges;
}

            
getIpv4NotAllowedMessage() public method

Get an error message used when validation fails due to the disabled IPv4 validation when $allowIpv4 is set.

public getIpv4NotAllowedMessage( ): string
return string

Error message.

                public function getIpv4NotAllowedMessage(): string
{
    return $this->ipv4NotAllowedMessage;
}

            
getIpv6NotAllowedMessage() public method

Get error message used when validation fails due to the disabled IPv6 validation when $allowIpv6 is set.

public getIpv6NotAllowedMessage( ): string
return string

Error message.

                public function getIpv6NotAllowedMessage(): string
{
    return $this->ipv6NotAllowedMessage;
}

            
getMessage() public method

Get an error message used when validation fails due to the wrong IP address format.

public getMessage( ): string
return string

Error message.

                public function getMessage(): string
{
    return $this->message;
}

            
getName() public method

public getName( ): string

                public function getName(): string
{
    return self::class;
}

            
getNetworks() public method
Deprecated Use \Yiisoft\NetworkUtilities\IpRanges::getNetworks() instead.

Get custom network aliases, that can be used in $ranges.

public getNetworks( ): array
return array

Network aliases.

                public function getNetworks(): array
{
    return $this->ranges->getNetworks();
}

            
getNoSubnetMessage() public method

Get error message used when validation fails due to $allowSubnet is used, but the CIDR prefix is not set.

public getNoSubnetMessage( ): string
return string

Error message.

                public function getNoSubnetMessage(): string
{
    return $this->noSubnetMessage;
}

            
getNotInRangeMessage() public method

Get error message used when validation fails due to IP address is not allowed by $ranges check.

public getNotInRangeMessage( ): string
return string

Error message.

                public function getNotInRangeMessage(): string
{
    return $this->notInRangeMessage;
}

            
getOptions() public method

public getOptions( ): array

                public function getOptions(): array
{
    return [
        'networks' => $this->ranges->getNetworks(),
        'allowIpv4' => $this->allowIpv4,
        'allowIpv6' => $this->allowIpv6,
        'allowSubnet' => $this->allowSubnet,
        'requireSubnet' => $this->requireSubnet,
        'allowNegation' => $this->allowNegation,
        'incorrectInputMessage' => [
            'template' => $this->incorrectInputMessage,
            'parameters' => [],
        ],
        'message' => [
            'template' => $this->message,
            'parameters' => [],
        ],
        'ipv4NotAllowedMessage' => [
            'template' => $this->ipv4NotAllowedMessage,
            'parameters' => [],
        ],
        'ipv6NotAllowedMessage' => [
            'template' => $this->ipv6NotAllowedMessage,
            'parameters' => [],
        ],
        'wrongCidrMessage' => [
            'template' => $this->wrongCidrMessage,
            'parameters' => [],
        ],
        'noSubnetMessage' => [
            'template' => $this->noSubnetMessage,
            'parameters' => [],
        ],
        'hasSubnetMessage' => [
            'template' => $this->hasSubnetMessage,
            'parameters' => [],
        ],
        'notInRangeMessage' => [
            'template' => $this->notInRangeMessage,
            'parameters' => [],
        ],
        'ranges' => $this->ranges->getRanges(),
        'skipOnEmpty' => $this->getSkipOnEmptyOption(),
        'skipOnError' => $this->skipOnError,
    ];
}

            
getRanges() public method
Deprecated Use \Yiisoft\NetworkUtilities\IpRanges::getRanges() instead.

Get the IPv4 or IPv6 ranges that are allowed or forbidden.

public getRanges( ): string[]
return string[]

The IPv4 or IPv6 ranges that are allowed or forbidden.

                public function getRanges(): array
{
    return $this->ranges->getRanges();
}

            
getSkipOnEmpty() public method

Defined in: Yiisoft\Validator\Rule\Trait\SkipOnEmptyTrait::getSkipOnEmpty()

A getter for $skipOnEmpty property.

public getSkipOnEmpty( ): boolean|callable|null
return boolean|callable|null

A current raw (non-normalized) value.

                public function getSkipOnEmpty(): bool|callable|null
{
    return $this->skipOnEmpty;
}

            
getWhen() public method

Defined in: Yiisoft\Validator\Rule\Trait\WhenTrait::getWhen()

A getter for $when property.

public getWhen( ): Closure|null
return Closure|null

Current value:

  • null - always apply the validation.
  • callable - apply the validation depending on a return value: true - apply, false - do not apply.

                public function getWhen(): ?Closure
{
    return $this->when;
}

            
getWrongCidrMessage() public method

Get error message used when validation fails due to the wrong CIDR when $allowSubnet is set.

public getWrongCidrMessage( ): string
return string

Error message.

                public function getWrongCidrMessage(): string
{
    return $this->wrongCidrMessage;
}

            
isAllowed() public method
Deprecated Use \Yiisoft\NetworkUtilities\IpRanges::isAllowed() instead.

Whether the IP address with specified CIDR is allowed according to the $ranges list.

public isAllowed( string $ip ): boolean
$ip string

                public function isAllowed(string $ip): bool
{
    return $this->ranges->isAllowed($ip);
}

            
isIpv4Allowed() public method

Whether the validating value can be an IPv4 address

public isIpv4Allowed( ): boolean
return boolean

Whether the validating value can be an IPv4 address. Defaults to true.

                public function isIpv4Allowed(): bool
{
    return $this->allowIpv4;
}

            
isIpv6Allowed() public method

Whether the validating value can be an IPv6 address.

public isIpv6Allowed( ): boolean
return boolean

Whether the validating value can be an IPv6 address. Defaults to true.

                public function isIpv6Allowed(): bool
{
    return $this->allowIpv6;
}

            
isNegationAllowed() public method

Whether an address may have a ! negation character at the beginning.

public isNegationAllowed( ): boolean
return boolean

Whether an address may have a ! negation character at the beginning.

                public function isNegationAllowed(): bool
{
    return $this->allowNegation;
}

            
isSubnetAllowed() public method

Whether the address can be an IP with CIDR subnet, like 192.168.10.0/24.

public isSubnetAllowed( ): boolean
return boolean

Whether the address can be an IP with CIDR subnet.

                public function isSubnetAllowed(): bool
{
    return $this->allowSubnet;
}

            
isSubnetRequired() public method

Whether subnet is required.

public isSubnetRequired( ): boolean
return boolean

Whether subnet is required.

                public function isSubnetRequired(): bool
{
    return $this->requireSubnet;
}

            
shouldSkipOnError() public method

Defined in: Yiisoft\Validator\Rule\Trait\SkipOnErrorTrait::shouldSkipOnError()

A getter for $skipOnError property.

public shouldSkipOnError( ): boolean
return boolean

Current value. true means to skip the current rule when the previous one errored and false - do not skip.

                public function shouldSkipOnError(): bool
{
    return $this->skipOnError;
}

            
skipOnEmpty() public method

Defined in: Yiisoft\Validator\Rule\Trait\SkipOnEmptyTrait::skipOnEmpty()

An immutable setter to change $skipOnEmpty property.

public skipOnEmpty( boolean|callable|null $value ): $this
$value boolean|callable|null

A new value.

return $this

The new instance with a changed value.

                public function skipOnEmpty(bool|callable|null $value): static
{
    $new = clone $this;
    $new->skipOnEmpty = $value;
    return $new;
}

            
skipOnError() public method

Defined in: Yiisoft\Validator\Rule\Trait\SkipOnErrorTrait::skipOnError()

An immutable setter to change $skipOnError property.

public skipOnError( boolean $value ): $this
$value boolean

A new value. true means to skip the current rule when the previous one errored and false - do not skip.

return $this

The new instance with a changed value.

                public function skipOnError(bool $value): static
{
    $new = clone $this;
    $new->skipOnError = $value;
    return $new;
}

            
when() public method

Defined in: Yiisoft\Validator\Rule\Trait\WhenTrait::when()

An immutable setter to change $when property.

public when( Closure|null $value ): $this
$value Closure|null

A new value:

  • null - always apply the validation.
  • callable - apply the validation depending on a return value: true - apply, false - do not apply.
return $this

The new instance with a changed value.

                public function when(?Closure $value): static
{
    $new = clone $this;
    $new->when = $value;
    return $new;
}