allNumberGroupsAreExactlyPresent static method

bool allNumberGroupsAreExactlyPresent(
  1. PhoneNumberUtil util,
  2. PhoneNumber number,
  3. StringBuffer normalizedCandidate,
  4. List<String> formattedNumberGroups,
)

Implementation

static bool allNumberGroupsAreExactlyPresent(
  PhoneNumberUtil util,
  PhoneNumber number,
  StringBuffer normalizedCandidate,
  List<String> formattedNumberGroups,
) {
  List<String> candidateGroups =
      normalizedCandidate.toString().split(PhoneNumberUtil.nonDigitsPattern);

  // Set this to the last group, skipping it if the number has an extension.
  int candidateNumberGroupIndex = number.hasExtension_3()
      ? candidateGroups.length - 2
      : candidateGroups.length - 1;

  // First we check if the national significant number is formatted as a block.
  // We use contains and not equals, since the national significant number may be present with
  // a prefix such as a national number prefix, or the country code itself.
  if (candidateGroups.length == 1 ||
      candidateGroups[candidateNumberGroupIndex]
          .contains(util.getNationalSignificantNumber(number))) {
    return true;
  }

  // Starting from the end, go through in reverse, excluding the first group, and check the
  // candidate and number groups are the same.
  for (int formattedNumberGroupIndex = (formattedNumberGroups.length - 1);
      formattedNumberGroupIndex > 0 && candidateNumberGroupIndex >= 0;
      formattedNumberGroupIndex--, candidateNumberGroupIndex--) {
    if (candidateGroups[candidateNumberGroupIndex] !=
        formattedNumberGroups[formattedNumberGroupIndex]) {
      return false;
    }
  }

  // Now check the first group. There may be a national prefix at the start, so we only check
  // that the candidate group ends with the formatted number group.
  return (candidateNumberGroupIndex >= 0 &&
      candidateGroups[candidateNumberGroupIndex]
          .endsWith(formattedNumberGroups[0]));
}