@@ -4,6 +4,7 @@ import 'package:phone_numbers_parser/src/validation/validator.dart';
44import '../../phone_numbers_parser.dart' ;
55import '../metadata/metadata_finder.dart' ;
66import '../metadata/models/phone_metadata.dart' ;
7+ import '../regex/constants.dart' ;
78import '_country_code_parser.dart' ;
89import '_international_prefix_parser.dart' ;
910import '_national_number_parser.dart' ;
@@ -37,6 +38,18 @@ abstract class PhoneParser {
3738 IsoCode ? destinationCountry,
3839 }) {
3940 phoneNumber = TextParser .normalizePhoneNumber (phoneNumber);
41+ // a phone number can never be longer than the maximum country calling code
42+ // length plus the maximum national significant number length.
43+ final maxLength =
44+ Constants .maxLengthCountryCallingCode + Constants .maxLengthNsn;
45+ final digitCount = phoneNumber.replaceAll ('+' , '' ).length;
46+ if (digitCount > maxLength) {
47+ throw PhoneNumberException (
48+ code: Code .inputIsTooLong,
49+ description:
50+ 'phone number has $digitCount digits, maximum is $maxLength ' ,
51+ );
52+ }
4053 final callerMetadata = callerCountry != null
4154 ? MetadataFinder .findMetadataForIsoCode (callerCountry)
4255 : null ;
@@ -124,13 +137,12 @@ abstract class PhoneParser {
124137 // if no caller was provided we need to make a best guess given the country code
125138 final (countryCode, nsn) =
126139 CountryCodeParser .extractCountryCode (phoneWithoutExitCode);
127- // multiple countries use the same country code
140+ // extractCountryCode only returns once it has found metadata matching both
141+ // the country code and the national number, so this lookup is guaranteed to
142+ // find metadata as well.
128143 final metadata =
129144 MetadataFinder .findMetadataForCountryCode (countryCode, nsn);
130-
131- return metadata ??
132- callerMetadata ??
133- // default if nothing was found.
134- MetadataFinder .findMetadataForIsoCode (IsoCode .US );
145+ assert (metadata != null , 'no metadata found for country code $countryCode ' );
146+ return metadata! ;
135147 }
136148}
0 commit comments