From 1829a61917958cddabc9e055c3727b5fbbab840c Mon Sep 17 00:00:00 2001 From: Nate Weller Date: Fri, 20 Sep 2024 11:39:02 -0600 Subject: [PATCH] Use validate_netmask to avoid code duplication --- projects/packages/ip/src/class-utils.php | 40 ++++++++++-------------- 1 file changed, 17 insertions(+), 23 deletions(-) diff --git a/projects/packages/ip/src/class-utils.php b/projects/packages/ip/src/class-utils.php index 30eec791b677d..a4b820666d6a7 100644 --- a/projects/packages/ip/src/class-utils.php +++ b/projects/packages/ip/src/class-utils.php @@ -224,7 +224,7 @@ public static function validate_cidr( $cidr ) { return false; // Invalid CIDR notation if it doesn't contain exactly one '/'. } - list( $ip, $prefix ) = $parts; + list( $ip, $netmask ) = $parts; // Validate the IP address. if ( ! filter_var( $ip, FILTER_VALIDATE_IP ) ) { @@ -232,22 +232,15 @@ public static function validate_cidr( $cidr ) { } $ip_version = self::get_ip_version( $ip ); - - // Validate prefix length. - if ( $ip_version === 'ipv4' ) { - // For IPv4, the prefix length must be an integer between 0 and 32. - if ( ! ctype_digit( $prefix ) || $prefix < 0 || $prefix > 32 ) { - return false; - } - } elseif ( $ip_version === 'ipv6' ) { - // For IPv6, the prefix length must be an integer between 0 and 128. - if ( ! ctype_digit( $prefix ) || $prefix < 0 || $prefix > 128 ) { - return false; - } - } else { + if ( ! $ip_version ) { return false; // Invalid IP address. } + // Validate the netmask based on the IP version. + if ( ! self::validate_netmask( $netmask, $ip_version ) ) { + return false; + } + return true; } @@ -301,12 +294,6 @@ public static function parse_cidr( $cidr ) { } list( $range, $netmask ) = $cidr_parts; - // Ensure that $netmask is an integer - if ( ! ctype_digit( $netmask ) ) { - return false; - } - $netmask = (int) $netmask; - // Determine IP version $ip_version = self::get_ip_version( $range ); if ( ! $ip_version ) { @@ -318,17 +305,24 @@ public static function parse_cidr( $cidr ) { return false; // Netmask out of range } - return array( $range, $netmask ); + return array( $range, (int) $netmask ); } /** * Validates the netmask based on IP version. * - * @param int $netmask Netmask value. - * @param string $ip_version 'ipv4' or 'ipv6'. + * @param string|int $netmask Netmask value. + * @param string $ip_version 'ipv4' or 'ipv6'. * @return bool True if valid, false otherwise. */ public static function validate_netmask( $netmask, $ip_version ) { + // Ensure that $netmask is an integer + if ( ! ctype_digit( $netmask ) ) { + return false; + } + $netmask = (int) $netmask; + + // Validate the netmask based on the IP version. if ( $ip_version === 'ipv4' ) { return ( $netmask >= 0 && $netmask <= 32 ); } elseif ( $ip_version === 'ipv6' ) {