fromCountryCode static method

  1. @internal
PhoneNumber fromCountryCode(
  1. String countryCode,
  2. String phoneNumber
)

parses a phoneNumber given a countryCode

Use parseWithIsoCode when possible as multiple countries use the same country calling code.

The phoneNumber can be of the sort: +33 6 86 57 90 14, 06 86 57 90 14, 6 86 57 90 14

throws a PhoneNumberException if the country calling code is invalid

Implementation

@internal
static PhoneNumber fromCountryCode(
  String countryCode,
  String phoneNumber,
) {
  countryCode = CountryCodeParser.normalizeCountryCode(countryCode);
  phoneNumber = TextParser.normalize(phoneNumber);
  final withoutIntlPrefix =
      InternationalPrefixParser.removeInternationalPrefix(
    phoneNumber,
    countryCode: countryCode,
  );
  final withoutCountryCode =
      CountryCodeParser.removeCountryCode(withoutIntlPrefix, countryCode);
  var national = withoutCountryCode;
  // if a country code did not immediately follow the international prefix
  // then it was not an international prefix by definition
  if (withoutIntlPrefix.length == withoutCountryCode.length) {
    national = phoneNumber;
  }
  final metadatas = MetadataFinder.getMetadatasForCountryCode(countryCode);
  final metadata = MetadataMatcher.getMatchUsingPatterns(national, metadatas);
  final result = _parse(metadata.isoCode, national);
  // we only want to modify the national number when it is valid
  if (result.validateLength()) return result;
  return PhoneNumber(isoCode: metadata.isoCode, nsn: phoneNumber);
}