parse static method

  1. @internal
PhoneNumber parse(
  1. String phoneNumber, {
  2. IsoCode? callerCountry,
  3. IsoCode? destinationCountry,
})

Implementation

@internal
static PhoneNumber parse(
  String phoneNumber, {
  IsoCode? callerCountry,
  IsoCode? destinationCountry,
}) {
  phoneNumber = TextParser.normalize(phoneNumber);
  final callerMetadata = callerCountry != null
      ? MetadataFinder.getMetadataForIsoCode(callerCountry)
      : null;
  var destinationMetadata = destinationCountry != null
      ? MetadataFinder.getMetadataForIsoCode(destinationCountry)
      : null;

  final withoutExitCode = InternationalPrefixParser.removeExitCode(
    phoneNumber,
    destinationCountryMetadata: destinationMetadata,
    callerCountryMetadata: callerMetadata,
  );
  final containsExitCode = withoutExitCode.length != phoneNumber.length;
  // if no destination metadata was provided we have to find it,
  destinationMetadata ??= _findDestinationMetadata(
    phoneWithoutExitCode: withoutExitCode,
    callerMetadata: callerMetadata,
  );
  var national = withoutExitCode;
  // if there was no exit code then we assume we are dealing with a national number
  if (containsExitCode) {
    national = CountryCodeParser.removeCountryCode(
      withoutExitCode,
      destinationMetadata.countryCode,
    );
  }
  final containsCountryCode = national.length != withoutExitCode.length;
  // normally a phone number should not contain a national prefix after the country
  // code. However we let it slide to cover a wider range of incorrect input
  var nsn = NationalNumberParser.removeNationalPrefix(
    national,
    destinationMetadata,
  );
  // if the phone number contained a country code, it should in its international form
  // and we should not transform it
  if (!containsCountryCode) {
    nsn = NationalNumberParser.transformLocalNsnToInternationalUsingPatterns(
      nsn,
      destinationMetadata,
    );
  }

  // at this point we have the phone number that has been processed, but
  // if it is invalid, we remove the processing of the nsn part
  // this allows for a better behavior in some widget input usages where the
  // text is changed on validity.
  final parsed = PhoneNumber(isoCode: destinationMetadata.isoCode, nsn: nsn);
  if (parsed.isValid()) return parsed;
  return PhoneNumber(isoCode: destinationMetadata.isoCode, nsn: national);
}