fromIsoCode static method

  1. @internal
PhoneNumber fromIsoCode(
  1. IsoCode isoCode,
  2. String phoneNumber
)

parses a phoneNumber given an isoCode

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 isoCode is invalid

Implementation

@internal
static PhoneNumber fromIsoCode(IsoCode isoCode, String phoneNumber) {
  phoneNumber = TextParser.normalize(phoneNumber);
  final metadata = MetadataFinder.getMetadataForIsoCode(isoCode);
  // we now have national which is the phone number that will be transformed
  // to nsn. If the result is not valid, we will keep the original input as
  // the nsn. That is because for the national we assume that if the number
  // starts with the country code, it is in fact the country code.
  // however that's not always the case, some countries like KZ can have an nsn
  // starting with the same digits as the country code.
  // For example we could do fromIsoCode('KZ', '7710009998')
  // the below code will first assume that the leading 7 is the country code
  // then will realize the phone number is invalid when the 7 is removed
  // and will return a result with the original input, which is valid
  final withoutIntlPrefix =
      InternationalPrefixParser.removeInternationalPrefix(
    phoneNumber,
    countryCode: metadata.countryCode,
    metadata: metadata,
  );

  final withoutCountryCode = CountryCodeParser.removeCountryCode(
      withoutIntlPrefix, metadata.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 = withoutCountryCode;
  }

  final result = _parse(isoCode, national);
  // we only want to modify the national number when it is valid
  if (result.validate()) return result;
  return PhoneNumber(isoCode: isoCode, nsn: phoneNumber);
}