Automattic\WooCommerce\Internal\Fulfillments

FulfillmentUtils::validate_mod7_check_digitpublic staticWC 1.0

Validate Mod 7 check digit for numeric tracking numbers.

Method of the class: FulfillmentUtils{}

No Hooks.

Returns

true|false. True if valid, false otherwise.

Usage

$result = FulfillmentUtils::validate_mod7_check_digit( $tracking_number ): bool;
$tracking_number(string) (required)
The numeric tracking number.

FulfillmentUtils::validate_mod7_check_digit() code WC 10.3.3

public static function validate_mod7_check_digit( string $tracking_number ): bool {
	if ( ! preg_match( '/^\d+$/', $tracking_number ) || strlen( $tracking_number ) < 2 ) {
		return false;
	}

	$check_digit  = (int) substr( $tracking_number, -1 );
	$number       = substr( $tracking_number, 0, -1 );
	$sum          = 0;
	$weights      = array( 3, 1, 3, 1, 3, 1, 3 ); // Mod 7 weights.
	$weight_index = 0;
	// Process each digit from right to left.
	for ( $i = strlen( $number ) - 1; $i >= 0; $i-- ) {
		$digit = (int) $number[ $i ];
		$sum  += $digit * $weights[ $weight_index % count( $weights ) ];
		++$weight_index;
	}
	$calculated_check = $sum % 7;
	if ( 0 === $calculated_check ) {
		$calculated_check = 7; // If the sum is a multiple of 7, the check digit is 7.
	}
	return $calculated_check === $check_digit;
}