-
Notifications
You must be signed in to change notification settings - Fork 27
/
_international_prefix_parser.dart
56 lines (51 loc) · 2 KB
/
_international_prefix_parser.dart
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
import 'package:phone_number_metadata/phone_number_metadata.dart';
abstract class InternationalPrefixParser {
/// Removes the exit code from a phone number if present.
///
/// It expects a normalized [phoneNumber].
/// if phone starts with + it is removed
/// if starts with 00 or 011
/// we consider those as internationalPrefix as
/// they cover 4/5 of the international prefix
static String removeExitCode(
String phoneNumber, {
PhoneMetadata? callerCountryMetadata,
PhoneMetadata? destinationCountryMetadata,
}) {
if (phoneNumber.startsWith('+')) {
return phoneNumber.substring(1);
}
// if the caller country was provided it's easy, just remove the exit code
// from the phone number
if (callerCountryMetadata != null) {
return _removeExitCodeWithMetadata(phoneNumber, callerCountryMetadata);
}
// if the caller country was not specified, a best guess is approximated.
// 4/5 of the world wide numbers exit codes are 00 or 011
// if a country code does not follow the international prefix
// then we can assume it is not an international prefix
// if no metadata was provided for the destination country
// then no such check is made that a country code does not follow
final countryCode = destinationCountryMetadata?.countryCode ?? '';
if (phoneNumber.startsWith('00$countryCode')) {
return phoneNumber.substring(2);
}
if (phoneNumber.startsWith('011$countryCode')) {
return phoneNumber.substring(3);
}
return phoneNumber;
}
static String _removeExitCodeWithMetadata(
String phoneNumber,
PhoneMetadata metadata,
) {
final match =
RegExp(metadata.internationalPrefix).matchAsPrefix(phoneNumber);
if (match != null) {
return phoneNumber.substring(match.end);
}
// if it does not start with the international prefix from the
// country we assume the prefix is not present
return phoneNumber;
}
}