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 {@see $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 {@see $allowIpv4} is set. Yiisoft\Validator\Rule\Ip
getIpv6NotAllowedMessage() Get error message used when validation fails due to the disabled IPv6 validation when {@see $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 {@see $ranges}. Yiisoft\Validator\Rule\Ip
getNoSubnetMessage() Get error message used when validation fails due to {@see $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 {@see $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 {@see $allowSubnet} is set. Yiisoft\Validator\Rule\Ip
isAllowed() Whether the IP address with specified CIDR is allowed according to the {@see $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 mixed __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 )
$networks array

Custom network aliases, that can be used in {@see $ranges}:

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

The following aliases are defined by default in {@see $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 {@see $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 {@see $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 {@see $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 {@see $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 {@see $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 {@see $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 {@see $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 {@see \Yiisoft\Validator\SkipOnEmptyInterface}.

$skipOnError boolean

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

$when Closure|null

A callable to define a condition for applying the rule. See {@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 string getHandler ( )

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

            
getHasSubnetMessage() public method

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

public string getHasSubnetMessage ( )
return string

Error message.

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

            
getIncorrectInputMessage() public method

Get a message used when the input it incorrect.

public string getIncorrectInputMessage ( )
return string

Error message

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

            
getIpRanges() public method

public \Yiisoft\NetworkUtilities\IpRanges getIpRanges ( )

                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 {@see $allowIpv4} is set.

public string getIpv4NotAllowedMessage ( )
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 {@see $allowIpv6} is set.

public string getIpv6NotAllowedMessage ( )
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 string getMessage ( )
return string

Error message.

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

            
getName() public method

public string getName ( )

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

            
getNetworks() public method
Deprecated Use {@see \Yiisoft\NetworkUtilities\IpRanges::getNetworks()} instead.

Get custom network aliases, that can be used in {@see $ranges}.

public array getNetworks ( )
return array

Network aliases.

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

            
getNoSubnetMessage() public method

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

public string getNoSubnetMessage ( )
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 {@see $ranges} check.

public string getNotInRangeMessage ( )
return string

Error message.

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

            
getOptions() public method

public array getOptions ( )

                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 {@see \Yiisoft\NetworkUtilities\IpRanges::getRanges()} instead.

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

public string[] getRanges ( )
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 boolean|callable|null getSkipOnEmpty ( )
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 Closure|null getWhen ( )
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 {@see $allowSubnet} is set.

public string getWrongCidrMessage ( )
return string

Error message.

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

            
isAllowed() public method
Deprecated Use {@see \Yiisoft\NetworkUtilities\IpRanges::isAllowed()} instead.

Whether the IP address with specified CIDR is allowed according to the {@see $ranges} list.

public boolean isAllowed ( string $ip )
$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 boolean isIpv4Allowed ( )
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 boolean isIpv6Allowed ( )
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 boolean isNegationAllowed ( )
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 boolean isSubnetAllowed ( )
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 boolean isSubnetRequired ( )
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 boolean shouldSkipOnError ( )
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 $this skipOnEmpty ( boolean|callable|null $value )
$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 $this skipOnError ( boolean $value )
$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 $this when ( Closure|null $value )
$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;
}