This repository has been archived by the owner on Aug 21, 2018. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 71
/
PhoneNumberUtil.php
2394 lines (2222 loc) · 108 KB
/
PhoneNumberUtil.php
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
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
<?php
namespace com\google\i18n\phonenumbers;
require_once dirname(__FILE__) . '/CountryCodeToRegionCodeMap.php';
require_once dirname(__FILE__) . '/PhoneMetadata.php';
require_once dirname(__FILE__) . '/NumberParseException.php';
require_once dirname(__FILE__) . '/PhoneNumber.php';
/**
* INTERNATIONAL and NATIONAL formats are consistent with the definition in ITU-T Recommendation
* E123. For example, the number of the Google Switzerland office will be written as
* "+41 44 668 1800" in INTERNATIONAL format, and as "044 668 1800" in NATIONAL format.
* E164 format is as per INTERNATIONAL format but with no formatting applied, e.g. +41446681800.
* RFC3966 is as per INTERNATIONAL format, but with all spaces and other separating symbols
* replaced with a hyphen, and with any phone number extension appended with ";ext=".
*
* Note: If you are considering storing the number in a neutral format, you are highly advised to
* use the PhoneNumber class.
*/
class PhoneNumberFormat {
const E164 = 0;
const INTERNATIONAL = 1;
const NATIONAL = 2;
const RFC3966 = 3;
}
/**
* Type of phone numbers.
*/
class PhoneNumberType {
const FIXED_LINE = 0;
const MOBILE = 1;
// In some regions (e.g. the USA), it is impossible to distinguish between fixed-line and
// mobile numbers by looking at the phone number itself.
const FIXED_LINE_OR_MOBILE = 2;
// Freephone lines
const TOLL_FREE = 3;
const PREMIUM_RATE = 4;
// The cost of this call is shared between the caller and the recipient, and is hence typically
// less than PREMIUM_RATE calls. See // http://en.wikipedia.org/wiki/Shared_Cost_Service for
// more information.
const SHARED_COST = 5;
// Voice over IP numbers. This includes TSoIP (Telephony Service over IP).
const VOIP = 6;
// A personal number is associated with a particular person, and may be routed to either a
// MOBILE or FIXED_LINE number. Some more information can be found here:
// http://en.wikipedia.org/wiki/Personal_Numbers
const PERSONAL_NUMBER = 7;
const PAGER = 8;
// Used for "Universal Access Numbers" or "Company Numbers". They may be further routed to
// specific offices, but allow one number to be used for a company.
const UAN = 9;
// A phone number is of type UNKNOWN when it does not fit any of the known patterns for a
// specific region.
const UNKNOWN = 10;
}
/**
* Types of phone number matches. See detailed description beside the isNumberMatch() method.
*/
class MatchType {
const NOT_A_NUMBER = 0;
const NO_MATCH = 1;
const SHORT_NSN_MATCH = 2;
const NSN_MATCH = 3;
const EXACT_MATCH = 4;
}
/**
* Possible outcomes when testing if a PhoneNumber is possible.
*/
class ValidationResult {
const IS_POSSIBLE = 0;
const INVALID_COUNTRY_CODE = 1;
const TOO_SHORT = 2;
const TOO_LONG = 3;
}
/**
* Utility for international phone numbers. Functionality includes formatting, parsing and
* validation.
*
* <p>If you use this library, and want to be notified about important changes, please sign up to
* our <a href="http://groups.google.com/group/libphonenumber-discuss/about">mailing list</a>.
*
* NOTE: A lot of methods in this class require Region Code strings. These must be provided using
* ISO 3166-1 two-letter country-code format. These should be in upper-case. The list of the codes
* can be found here: http://www.iso.org/iso/english_country_names_and_code_elements
*
* @author Shaopeng Jia
* @author Lara Rennie
*/
class PhoneNumberUtil {
const REGEX_FLAGS = 'ui'; //Unicode and case insensitive
// The minimum and maximum length of the national significant number.
const MIN_LENGTH_FOR_NSN = 3;
const MAX_LENGTH_FOR_NSN = 15;
// The maximum length of the country calling code.
const MAX_LENGTH_COUNTRY_CODE = 3;
// A mapping from a region code to the PhoneMetadata for that region.
private $regionToMetadataMap = array();
// A mapping from a country calling code for a non-geographical entity to the PhoneMetadata for
// that country calling code. Examples of the country calling codes include 800 (International
// Toll Free Service) and 808 (International Shared Cost Service).
private $countryCodeToNonGeographicalMetadataMap = array();
const REGION_CODE_FOR_NON_GEO_ENTITY = "001";
const META_DATA_FILE_PREFIX = 'PhoneNumberMetadata';
const TEST_META_DATA_FILE_PREFIX = 'PhoneNumberMetadataForTesting';
/**
* @var PhoneNumberUtil
*/
private static $instance = NULL;
private $supportedRegions = array();
private $currentFilePrefix = self::META_DATA_FILE_PREFIX;
private $countryCallingCodeToRegionCodeMap = NULL;
const UNKNOWN_REGION = "ZZ";
// The set of regions that share country calling code 1.
// There are roughly 26 regions and we set the initial capacity of the HashSet to 35 to offer a
// load factor of roughly 0.75.
private $nanpaRegions = array();
const NANPA_COUNTRY_CODE = 1;
// The prefix that needs to be inserted in front of a Colombian landline number when dialed from
// a mobile phone in Colombia.
const COLOMBIA_MOBILE_TO_FIXED_LINE_PREFIX = "3";
// The PLUS_SIGN signifies the international prefix.
const PLUS_SIGN = '+';
/**
* Gets a {@link PhoneNumberUtil} instance to carry out international phone number formatting,
* parsing, or validation. The instance is loaded with phone number metadata for a number of most
* commonly used regions.
*
* <p>The {@link PhoneNumberUtil} is implemented as a singleton. Therefore, calling getInstance
* multiple times will only result in one instance being created.
*
* @param string $baseFileLocation
* @param array|null $countryCallingCodeToRegionCodeMap
* @return PhoneNumberUtil instance
*/
public static function getInstance($baseFileLocation = self::META_DATA_FILE_PREFIX, array $countryCallingCodeToRegionCodeMap = NULL) {
if ($countryCallingCodeToRegionCodeMap === NULL) {
$countryCallingCodeToRegionCodeMap = CountryCodeToRegionCodeMap::$countryCodeToRegionCodeMap;
}
if (self::$instance == null) {
self::$instance = new PhoneNumberUtil();
self::$instance->countryCallingCodeToRegionCodeMap = $countryCallingCodeToRegionCodeMap;
self::$instance->init($baseFileLocation);
self::initExtnPatterns();
self::initAsciiDigitMappings();
self::initCapturingExtnDigits();
self::initExtnPattern();
self::$PLUS_CHARS_PATTERN = "[" . self::PLUS_CHARS . "]+";
self::$SEPARATOR_PATTERN = "[" . self::VALID_PUNCTUATION . "]+";
self::$CAPTURING_DIGIT_PATTERN = "(" . self::DIGITS . ")";
self::$VALID_START_CHAR_PATTERN = "[" . self::PLUS_CHARS . self::DIGITS . "]";
self::$ALPHA_PHONE_MAPPINGS = self::$ALPHA_MAPPINGS + self::$asciiDigitMappings;
self::$DIALLABLE_CHAR_MAPPINGS = self::$asciiDigitMappings;
self::$DIALLABLE_CHAR_MAPPINGS['+'] = '+';
self::$DIALLABLE_CHAR_MAPPINGS['*'] = '*';
self::$ALL_PLUS_NUMBER_GROUPING_SYMBOLS = array();
// Put (lower letter -> upper letter) and (upper letter -> upper letter) mappings.
foreach (self::$ALPHA_MAPPINGS as $c => $value) {
self::$ALL_PLUS_NUMBER_GROUPING_SYMBOLS[strtolower($c)] = $c;
self::$ALL_PLUS_NUMBER_GROUPING_SYMBOLS[$c] = $c;
}
self::$ALL_PLUS_NUMBER_GROUPING_SYMBOLS += self::$asciiDigitMappings;
self::$ALL_PLUS_NUMBER_GROUPING_SYMBOLS["-"] = '-';
self::$ALL_PLUS_NUMBER_GROUPING_SYMBOLS["\xEF\xBC\x8D"] = '-';
self::$ALL_PLUS_NUMBER_GROUPING_SYMBOLS["\xE2\x80\x90"] = '-';
self::$ALL_PLUS_NUMBER_GROUPING_SYMBOLS["\xE2\x80\x91"] = '-';
self::$ALL_PLUS_NUMBER_GROUPING_SYMBOLS["\xE2\x80\x92"] = '-';
self::$ALL_PLUS_NUMBER_GROUPING_SYMBOLS["\xE2\x80\x93"] = '-';
self::$ALL_PLUS_NUMBER_GROUPING_SYMBOLS["\xE2\x80\x94"] = '-';
self::$ALL_PLUS_NUMBER_GROUPING_SYMBOLS["\xE2\x80\x95"] = '-';
self::$ALL_PLUS_NUMBER_GROUPING_SYMBOLS["\xE2\x88\x92"] = '-';
self::$ALL_PLUS_NUMBER_GROUPING_SYMBOLS["/"] = "/";
self::$ALL_PLUS_NUMBER_GROUPING_SYMBOLS["\xEF\xBC\x8F"] = "/";
self::$ALL_PLUS_NUMBER_GROUPING_SYMBOLS[" "] = " ";
self::$ALL_PLUS_NUMBER_GROUPING_SYMBOLS["\xE3\x80\x80"] = " ";
self::$ALL_PLUS_NUMBER_GROUPING_SYMBOLS["\xE2\x81\xA0"] = " ";
self::$ALL_PLUS_NUMBER_GROUPING_SYMBOLS["."] = ".";
self::$ALL_PLUS_NUMBER_GROUPING_SYMBOLS["\xEF\xBC\x8E"] = ".";
}
return self::$instance;
}
/**
* Used for testing purposes only to reset the PhoneNumberUtil singleton to null.
*/
public static function resetInstance() {
self::$instance = NULL;
}
/**
* Convenience method to get a list of what regions the library has metadata for.
* @return array
*/
public function getSupportedRegions() {
return $this->supportedRegions;
}
/**
* This class implements a singleton, so the only constructor is private.
*/
private function __construct() {
}
private function init($filePrefix) {
$this->currentFilePrefix = dirname(__FILE__) . '/data/' . $filePrefix;
foreach ($this->countryCallingCodeToRegionCodeMap as $regionCodes) {
$this->supportedRegions = array_merge($this->supportedRegions, $regionCodes);
}
unset($this->supportedRegions[array_search(self::REGION_CODE_FOR_NON_GEO_ENTITY, $this->supportedRegions)]);
$this->nanpaRegions = $this->countryCallingCodeToRegionCodeMap[self::NANPA_COUNTRY_CODE];
}
/*
private void loadMetadataForRegionFromFile(String filePrefix, String regionCode) {
InputStream source =
PhoneNumberUtil.class.getResourceAsStream(filePrefix + "_" + regionCode);
ObjectInputStream in = null;
try {
in = new ObjectInputStream(source);
PhoneMetadataCollection metadataCollection = new PhoneMetadataCollection();
metadataCollection.readExternal(in);
for (PhoneMetadata metadata : metadataCollection.getMetadataList()) {
regionToMetadataMap.put(regionCode, metadata);
}
} catch (IOException e) {
LOGGER.log(Level.WARNING, e.toString());
} finally {
close(in);
}
}
private static void close(InputStream in) {
if (in != null) {
try {
in.close();
} catch (IOException e) {
LOGGER.log(Level.WARNING, e.toString());
}
}
}
*/
const PLUS_CHARS = '++';
private static $PLUS_CHARS_PATTERN;
private static $SEPARATOR_PATTERN;
private static $CAPTURING_DIGIT_PATTERN;
// Regular expression of acceptable characters that may start a phone number for the purposes of
// parsing. This allows us to strip away meaningless prefixes to phone numbers that may be
// mistakenly given to us. This consists of digits, the plus symbol and arabic-indic digits. This
// does not contain alpha characters, although they may be used later in the number. It also does
// not include other punctuation, as this will be stripped later during parsing and is of no
// information value when parsing a number.
private static $VALID_START_CHAR_PATTERN = NULL;
// Regular expression of characters typically used to start a second phone number for the purposes
// of parsing. This allows us to strip off parts of the number that are actually the start of
// another number, such as for: (530) 583-6985 x302/x2303 -> the second extension here makes this
// actually two phone numbers, (530) 583-6985 x302 and (530) 583-6985 x2303. We remove the second
// extension so that the first number is parsed correctly.
private static $SECOND_NUMBER_START_PATTERN = "[\\\\/] *x";
// Regular expression of trailing characters that we want to remove. We remove all characters that
// are not alpha or numerical characters. The hash character is retained here, as it may signify
// the previous block was an extension.
private static $UNWANTED_END_CHAR_PATTERN = "[[\\P{N}&&\\P{L}]&&[^#]]+$";
const STAR_SIGN = '*';
const RFC3966_EXTN_PREFIX = ";ext=";
// A map that contains characters that are essential when dialling. That means any of the
// characters in this map must not be removed from a number when dialing, otherwise the call will
// not reach the intended destination.
private static $DIALLABLE_CHAR_MAPPINGS = array();
// We use this pattern to check if the phone number has at least three letters in it - if so, then
// we treat it as a number where some phone-number digits are represented by letters.
const VALID_ALPHA_PHONE_PATTERN = "(?:.*?[A-Za-z]){3}.*";
// Default extension prefix to use when formatting. This will be put in front of any extension
// component of the number, after the main national number is formatted. For example, if you wish
// the default extension formatting to be " extn: 3456", then you should specify " extn: " here
// as the default extension prefix. This can be overridden by region-specific preferences.
const DEFAULT_EXTN_PREFIX = " ext. ";
// Regular expression of acceptable punctuation found in phone numbers. This excludes punctuation
// found as a leading character only.
// This consists of dash characters, white space characters, full stops, slashes,
// square brackets, parentheses and tildes. It also includes the letter 'x' as that is found as a
// placeholder for carrier information in some phone numbers. Full-width variants are also
// present.
/* "-x‐-―−ー--/ <U+200B><U+2060> ()()[].\\[\\]/~⁓∼" */
const VALID_PUNCTUATION = "-x\xE2\x80\x90-\xE2\x80\x95\xE2\x88\x92\xE3\x83\xBC\xEF\xBC\x8D-\xEF\xBC\x8F \xC2\xA0\xE2\x80\x8B\xE2\x81\xA0\xE3\x80\x80()\xEF\xBC\x88\xEF\xBC\x89\xEF\xBC\xBB\xEF\xBC\xBD.\\[\\]/~\xE2\x81\x93\xE2\x88\xBC";
const DIGITS = "\\p{Nd}";
private static $CAPTURING_EXTN_DIGITS;
private static function initCapturingExtnDigits() {
self::$CAPTURING_EXTN_DIGITS = "(" . self::DIGITS . "{1,7})";
}
private static $ALPHA_MAPPINGS = array(
'A' => '2',
'B' => '2',
'C' => '2',
'D' => '3',
'E' => '3',
'F' => '3',
'G' => '4',
'H' => '4',
'I' => '4',
'J' => '5',
'K' => '5',
'L' => '5',
'M' => '6',
'N' => '6',
'O' => '6',
'P' => '7',
'Q' => '7',
'R' => '7',
'S' => '7',
'T' => '8',
'U' => '8',
'V' => '8',
'W' => '9',
'X' => '9',
'Y' => '9',
'Z' => '9',
);
private static $ALPHA_PHONE_MAPPINGS;
// Separate map of all symbols that we wish to retain when formatting alpha numbers. This
// includes digits, ASCII letters and number grouping symbols such as "-" and " ".
private static $ALL_PLUS_NUMBER_GROUPING_SYMBOLS;
private static $asciiDigitMappings;
private static function initAsciiDigitMappings() {
// Simple ASCII digits map used to populate ALPHA_PHONE_MAPPINGS and
// ALL_PLUS_NUMBER_GROUPING_SYMBOLS.
self::$asciiDigitMappings = array(
'0' => '0',
'1' => '1',
'2' => '2',
'3' => '3',
'4' => '4',
'5' => '5',
'6' => '6',
'7' => '7',
'8' => '8',
'9' => '9',
);
}
// Pattern that makes it easy to distinguish whether a region has a unique international dialing
// prefix or not. If a region has a unique international prefix (e.g. 011 in USA), it will be
// represented as a string that contains a sequence of ASCII digits. If there are multiple
// available international prefixes in a region, they will be represented as a regex string that
// always contains character(s) other than ASCII digits.
// Note this regex also includes tilde, which signals waiting for the tone.
const UNIQUE_INTERNATIONAL_PREFIX = "[\\d]+(?:[~\xE2\x81\x93\xE2\x88\xBC\xEF\xBD\x9E][\\d]+)?";
private static function getValidAlphaPattern() {
// We accept alpha characters in phone numbers, ASCII only, upper and lower case.
return preg_replace("[, \\[\\]]", "", implode('', array_keys(self::$ALPHA_MAPPINGS))) . preg_replace("[, \\[\\]]", "", strtolower(implode('', array_keys(self::$ALPHA_MAPPINGS))));
}
private static $EXTN_PATTERNS_FOR_PARSING;
private static $EXTN_PATTERNS_FOR_MATCHING;
private static function initExtnPatterns() {
// One-character symbols that can be used to indicate an extension.
$singleExtnSymbolsForMatching = "x\xEF\xBD\x98#\xEF\xBC\x83~\xEF\xBD\x9E";
// For parsing, we are slightly more lenient in our interpretation than for matching. Here we
// allow a "comma" as a possible extension indicator. When matching, this is hardly ever used to
// indicate this.
$singleExtnSymbolsForParsing = "," . $singleExtnSymbolsForMatching;
self::$EXTN_PATTERNS_FOR_PARSING = self::createExtnPattern($singleExtnSymbolsForParsing);
self::$EXTN_PATTERNS_FOR_MATCHING = self::createExtnPattern($singleExtnSymbolsForMatching);
}
/**
* Helper initialiser method to create the regular-expression pattern to match extensions,
* allowing the one-char extension symbols provided by {@code singleExtnSymbols}.
* @param $singleExtnSymbols
* @return string
*/
private static function createExtnPattern($singleExtnSymbols) {
// There are three regular expressions here. The first covers RFC 3966 format, where the
// extension is added using ";ext=". The second more generic one starts with optional white
// space and ends with an optional full stop (.), followed by zero or more spaces/tabs and then
// the numbers themselves. The other one covers the special case of American numbers where the
// extension is written with a hash at the end, such as "- 503#".
// Note that the only capturing groups should be around the digits that you want to capture as
// part of the extension, or else parsing will fail!
// Canonical-equivalence doesn't seem to be an option with Android java, so we allow two options
// for representing the accented o - the character itself, and one in the unicode decomposed
// form with the combining acute accent.
return (self::RFC3966_EXTN_PREFIX . self::$CAPTURING_EXTN_DIGITS . "|" . "[ \xC2\xA0\\t,]*" .
"(?:e?xt(?:ensi(?:o\xCC\x81?|\xC3\xB3))?n?|(?:\xEF\xBD\x85)?\xEF\xBD\x98\xEF\xBD\x94(?:\xEF\xBD\x8E)?|" .
"[" . $singleExtnSymbols . "]|int|\xEF\xBD\x89\xEF\xBD\x8E\xEF\xBD\x94|anexo)" .
"[:\\.\xEF\xBC\x8E]?[ \xC2\xA0\\t,-]*" . self::$CAPTURING_EXTN_DIGITS . "#?|" .
"[- ]+(" . self::DIGITS . "{1,5})#");
}
const NON_DIGITS_PATTERN = "(\\D+)";
// The FIRST_GROUP_PATTERN was originally set to $1 but there are some countries for which the
// first group is not used in the national pattern (e.g. Argentina) so the $1 group does not match
// correctly. Therefore, we use \d, so that the first group actually used in the pattern will be
// matched.
const FIRST_GROUP_PATTERN = "(\\$\\d)";
const NP_PATTERN = '\\$NP';
const FG_PATTERN = '\\$FG';
const CC_PATTERN = '\\$CC';
// Regular expression of viable phone numbers. This is location independent. Checks we have at
// least three leading digits, and only valid punctuation, alpha characters and
// digits in the phone number. Does not include extension data.
// The symbol 'x' is allowed here as valid punctuation since it is often used as a placeholder for
// carrier codes, for example in Brazilian phone numbers. We also allow multiple "+" characters at
// the start.
// Corresponds to the following:
// plus_sign*([punctuation]*[digits]){3,}([punctuation]|[digits]|[alpha])*
// Note VALID_PUNCTUATION starts with a -, so must be the first in the range.
/**
* We append optionally the extension pattern to the end here, as a valid phone number may
* have an extension prefix appended, followed by 1 or more digits.
* @return string
*/
private static function getValidPhoneNumberPattern() {
return '%[' . self::PLUS_CHARS . ']*(?:[' . self::VALID_PUNCTUATION . ']*' . self::DIGITS . '){3,}[' .
self::VALID_PUNCTUATION . self::getValidAlphaPattern() . self::DIGITS . "]*(?:" . self::$EXTN_PATTERNS_FOR_PARSING . ')?%' . self::REGEX_FLAGS;
}
/**
* Checks to see if the string of characters could possibly be a phone number at all. At the
* moment, checks to see that the string begins with at least 3 digits, ignoring any punctuation
* commonly found in phone numbers.
* This method does not require the number to be normalized in advance - but does assume that
* leading non-number symbols have been removed, such as by the method extractPossibleNumber.
*
* @param string $number to be checked for viability as a phone number
* @return boolean true if the number could be a phone number of some sort, otherwise false
*/
public static function isViablePhoneNumber($number) {
if (strlen($number) < self::MIN_LENGTH_FOR_NSN) {
return FALSE;
}
$m = preg_match(self::getValidPhoneNumberPattern(), $number);
return $m > 0;
}
/**
* Normalizes a string of characters representing a phone number. This performs
* the following conversions:
* Punctuation is stripped.
* For ALPHA/VANITY numbers:
* Letters are converted to their numeric representation on a telephone
* keypad. The keypad used here is the one defined in ITU Recommendation
* E.161. This is only done if there are 3 or more letters in the number,
* to lessen the risk that such letters are typos.
* For other numbers:
* Wide-ascii digits are converted to normal ASCII (European) digits.
* Arabic-Indic numerals are converted to European numerals.
* Spurious alpha characters are stripped.
*
* @param {string} number a string of characters representing a phone number.
* @return string the normalized string version of the phone number.
*/
public static function normalize(&$number) {
$m = preg_match(self::getValidPhoneNumberPattern(), $number);
if ($m > 0) {
return self::normalizeHelper($number, self::$ALPHA_PHONE_MAPPINGS, true);
} else {
return self::normalizeDigitsOnly($number);
}
}
/**
* Normalizes a string of characters representing a phone number by replacing all characters found
* in the accompanying map with the values therein, and stripping all other characters if
* removeNonMatches is true.
*
* @param string $number a string of characters representing a phone number
* @param array $normalizationReplacements a mapping of characters to what they should be replaced by in
* the normalized version of the phone number
* @param bool $removeNonMatches indicates whether characters that are not able to be replaced
* should be stripped from the number. If this is false, they
* will be left unchanged in the number.
* @return string the normalized string version of the phone number
*/
private static function normalizeHelper($number, array $normalizationReplacements, $removeNonMatches) {
$normalizedNumber = "";
$numberAsArray = preg_split('/(?<!^)(?!$)/u', $number);
foreach ($numberAsArray as $character) {
if (isset($normalizationReplacements[mb_strtoupper($character, 'UTF-8')])) {
$normalizedNumber .= $normalizationReplacements[mb_strtoupper($character, 'UTF-8')];
} else if (!$removeNonMatches) {
$normalizedNumber .= $character;
}
// If neither of the above are true, we remove this character.
}
return $normalizedNumber;
}
/**
* Normalizes a string of characters representing a phone number. This converts wide-ascii and
* arabic-indic numerals to European numerals, and strips punctuation and alpha characters.
*
* @param $number string a string of characters representing a phone number
* @return string the normalized string version of the phone number
*/
public static function normalizeDigitsOnly($number) {
return self::normalizeDigits($number, false /* strip non-digits */);
}
/**
* @static
* @param $number
* @param $keepNonDigits
* @return string
*/
private static function normalizeDigits($number, $keepNonDigits) {
$normalizedDigits = "";
$numberAsArray = preg_split('/(?<!^)(?!$)/u', $number);
foreach ($numberAsArray as $character) {
if (is_numeric($character)) {
$normalizedDigits .= $character;
} else if ($keepNonDigits) {
$normalizedDigits .= $character;
}
// If neither of the above are true, we remove this character.
}
return $normalizedDigits;
}
/**
* Converts all alpha characters in a number to their respective digits on a keypad, but retains
* existing formatting.
* @param string $number
* @return string
*/
public static function convertAlphaCharactersInNumber($number) {
return self::normalizeHelper($number, self::$ALPHA_PHONE_MAPPINGS, false);
}
/**
* Gets the length of the geographical area code in the {@code nationalNumber_} field of the
* PhoneNumber object passed in, so that clients could use it to split a national significant
* number into geographical area code and subscriber number. It works in such a way that the
* resultant subscriber number should be diallable, at least on some devices. An example of how
* this could be used:
*
* <pre>
* PhoneNumberUtil phoneUtil = PhoneNumberUtil.getInstance();
* PhoneNumber number = phoneUtil.parse("16502530000", "US");
* String nationalSignificantNumber = phoneUtil.getNationalSignificantNumber(number);
* String areaCode;
* String subscriberNumber;
*
* int areaCodeLength = phoneUtil.getLengthOfGeographicalAreaCode(number);
* if (areaCodeLength > 0) {
* areaCode = nationalSignificantNumber.substring(0, areaCodeLength);
* subscriberNumber = nationalSignificantNumber.substring(areaCodeLength);
* } else {
* areaCode = "";
* subscriberNumber = nationalSignificantNumber;
* }
* </pre>
*
* N.B.: area code is a very ambiguous concept, so the I18N team generally recommends against
* using it for most purposes, but recommends using the more general {@code national_number}
* instead. Read the following carefully before deciding to use this method:
* <ul>
* <li> geographical area codes change over time, and this method honors those changes;
* therefore, it doesn't guarantee the stability of the result it produces.
* <li> subscriber numbers may not be diallable from all devices (notably mobile devices, which
* typically requires the full national_number to be dialled in most regions).
* <li> most non-geographical numbers have no area codes, including numbers from non-geographical
* entities
* <li> some geographical numbers have no area codes.
* </ul>
* @param \com\google\i18n\phonenumbers\PhoneNumber $number PhoneNumber object for which clients want to know the length of the area code.
* @return int the length of area code of the PhoneNumber object passed in.
*/
public function getLengthOfGeographicalAreaCode(PhoneNumber $number) {
$regionCode = $this->getRegionCodeForNumber($number);
if (!$this->isValidRegionCode($regionCode)) {
return 0;
}
$metadata = $this->getMetadataForRegion($regionCode);
if (!$metadata->hasNationalPrefix()) {
return 0;
}
$type = $this->getNumberTypeHelper($this->getNationalSignificantNumber($number), $metadata);
// Most numbers other than the two types below have to be dialled in full.
if ($type != PhoneNumberType::FIXED_LINE && $type != PhoneNumberType::FIXED_LINE_OR_MOBILE) {
return 0;
}
return $this->getLengthOfNationalDestinationCode($number);
}
/**
* Gets the length of the national destination code (NDC) from the PhoneNumber object passed in,
* so that clients could use it to split a national significant number into NDC and subscriber
* number. The NDC of a phone number is normally the first group of digit(s) right after the
* country calling code when the number is formatted in the international format, if there is a
* subscriber number part that follows. An example of how this could be used:
*
* <pre>
* PhoneNumberUtil phoneUtil = PhoneNumberUtil.getInstance();
* PhoneNumber number = phoneUtil.parse("18002530000", "US");
* String nationalSignificantNumber = phoneUtil.getNationalSignificantNumber(number);
* String nationalDestinationCode;
* String subscriberNumber;
*
* int nationalDestinationCodeLength = phoneUtil.getLengthOfNationalDestinationCode(number);
* if (nationalDestinationCodeLength > 0) {
* nationalDestinationCode = nationalSignificantNumber.substring(0,
* nationalDestinationCodeLength);
* subscriberNumber = nationalSignificantNumber.substring(nationalDestinationCodeLength);
* } else {
* nationalDestinationCode = "";
* subscriberNumber = nationalSignificantNumber;
* }
* </pre>
*
* Refer to the unittests to see the difference between this function and
* {@link #getLengthOfGeographicalAreaCode}.
*
* @param \com\google\i18n\phonenumbers\PhoneNumber $number the PhoneNumber object for which clients want to know the length of the NDC.
* @return int the length of NDC of the PhoneNumber object passed in.
*/
public function getLengthOfNationalDestinationCode(PhoneNumber $number) {
if ($number->hasExtension()) {
// We don't want to alter the proto given to us, but we don't want to include the extension
// when we format it, so we copy it and clear the extension here.
$copiedProto = new PhoneNumber();
$copiedProto->mergeFrom($number);
$copiedProto->clearExtension();
} else {
$copiedProto = clone $number;
}
$nationalSignificantNumber = $this->format($copiedProto, PhoneNumberFormat::INTERNATIONAL);
$numberGroups = preg_split('/' . self::NON_DIGITS_PATTERN . '/', $nationalSignificantNumber);
// The pattern will start with "+COUNTRY_CODE " so the first group will always be the empty
// string (before the + symbol) and the second group will be the country calling code. The third
// group will be area code if it is not the last group.
if (count($numberGroups) <= 3) {
return 0;
}
if ($this->getRegionCodeForCountryCode($number->getCountryCode()) === "AR" &&
$this->getNumberType($number) == PhoneNumberType::MOBILE) {
// Argentinian mobile numbers, when formatted in the international format, are in the form of
// +54 9 NDC XXXX.... As a result, we take the length of the third group (NDC) and add 1 for
// the digit 9, which also forms part of the national significant number.
// TODO: Investigate the possibility of better modeling the metadata to make it
// easier to obtain the NDC.
return strlen($numberGroups[3]) + 1;
}
return strlen($numberGroups[2]);
}
/**
* Returns the region where a phone number is from. This could be used for geocoding at the region
* level.
*
* @param PhoneNumber $number the phone number whose origin we want to know
* @return null|string the region where the phone number is from, or null if no region matches this calling
* code
*/
public function getRegionCodeForNumber(PhoneNumber $number) {
$countryCode = $number->getCountryCode();
if (!isset($this->countryCallingCodeToRegionCodeMap[$countryCode])) {
//$numberString = $this->getNationalSignificantNumber($number);
return NULL;
}
$regions = $this->countryCallingCodeToRegionCodeMap[$countryCode];
if (count($regions) == 1) {
return $regions[0];
} else {
return $this->getRegionCodeForNumberFromRegionList($number, $regions);
}
}
/**
* Checks whether the country calling code is from a region whose national significant number
* could contain a leading zero. An example of such a region is Italy. Returns false if no
* metadata for the country is found.
*/
public function isLeadingZeroPossible($countryCallingCode) {
$mainMetadataForCallingCode = $this->getMetadataForRegion(
$this->getRegionCodeForCountryCode($countryCallingCode));
if ($mainMetadataForCallingCode === NULL) {
return FALSE;
}
return (bool) $mainMetadataForCallingCode->isLeadingZeroPossible();
}
/**
* Checks if the number is a valid vanity (alpha) number such as 800 MICROSOFT. A valid vanity
* number will start with at least 3 digits and will have three or more alpha characters. This
* does not do region-specific checks - to work out if this number is actually valid for a region,
* it should be parsed and methods such as {@link #isPossibleNumberWithReason} and
* {@link #isValidNumber} should be used.
*
* @param string $number the number that needs to be checked
* @return bool true if the number is a valid vanity number
*/
public function isAlphaNumber($number) {
if (!$this->isViablePhoneNumber($number)) {
// Number is too short, or doesn't match the basic phone number pattern.
return false;
}
$this->maybeStripExtension($number);
return (bool) preg_match('/' . self::VALID_ALPHA_PHONE_PATTERN . '/' . self::REGEX_FLAGS, $number);
}
/**
* Helper method to check a number against a particular pattern and determine whether it matches,
* or is too short or too long. Currently, if a number pattern suggests that numbers of length 7
* and 10 are possible, and a number in between these possible lengths is entered, such as of
* length 8, this will return TOO_LONG.
*/
private function testNumberLengthAgainstPattern($numberPattern, $number) {
$numberMatcher = preg_match('/^' . $numberPattern . '$/', $number);
if ($numberMatcher > 0) {
return ValidationResult::IS_POSSIBLE;
}
$numberMatcher = preg_match('/^' . $numberPattern . '/', $number);
if ($numberMatcher > 0) {
return ValidationResult::TOO_LONG;
} else {
return ValidationResult::TOO_SHORT;
}
}
/**
* Extracts country calling code from fullNumber, returns it and places the remaining number in nationalNumber.
* It assumes that the leading plus sign or IDD has already been removed.
* Returns 0 if fullNumber doesn't start with a valid country calling code, and leaves nationalNumber unmodified.
* @param string $fullNumber
* @param string $nationalNumber
* @return int
*/
private function extractCountryCode($fullNumber, &$nationalNumber) {
if ((strlen($fullNumber) == 0) || ($fullNumber[0] == '0')) {
// Country codes do not begin with a '0'.
return 0;
}
$numberLength = strlen($fullNumber);
for ($i = 1; $i <= self::MAX_LENGTH_COUNTRY_CODE && $i <= $numberLength; $i++) {
$potentialCountryCode = (int)substr($fullNumber, 0, $i);
if (isset($this->countryCallingCodeToRegionCodeMap[$potentialCountryCode])) {
$nationalNumber .= substr($fullNumber, $i);
return $potentialCountryCode;
}
}
return 0;
}
/**
* Tries to extract a country calling code from a number. This method will return zero if no
* country calling code is considered to be present. Country calling codes are extracted in the
* following ways:
* <ul>
* <li> by stripping the international dialing prefix of the region the person is dialing from,
* if this is present in the number, and looking at the next digits
* <li> by stripping the '+' sign if present and then looking at the next digits
* <li> by comparing the start of the number and the country calling code of the default region.
* If the number is not considered possible for the numbering plan of the default region
* initially, but starts with the country calling code of this region, validation will be
* reattempted after stripping this country calling code. If this number is considered a
* possible number, then the first digits will be considered the country calling code and
* removed as such.
* </ul>
* It will throw a NumberParseException if the number starts with a '+' but the country calling
* code supplied after this does not match that of any known region.
*
* @param string $number non-normalized telephone number that we wish to extract a country calling
* code from - may begin with '+'
* @param PhoneMetadata $defaultRegionMetadata metadata about the region this number may be from
* @param string $nationalNumber a string buffer to store the national significant number in, in the case
* that a country calling code was extracted. The number is appended to any existing contents.
* If no country calling code was extracted, this will be left unchanged.
* @param bool $keepRawInput true if the country_code_source and preferred_carrier_code fields of
* phoneNumber should be populated.
* @param PhoneNumber $phoneNumber the PhoneNumber object where the country_code and country_code_source need
* to be populated. Note the country_code is always populated, whereas country_code_source is
* only populated when keepCountryCodeSource is true.
* @return int the country calling code extracted or 0 if none could be extracted
* @throws NumberParseException
*/
private function maybeExtractCountryCode($number, PhoneMetadata $defaultRegionMetadata = null,
&$nationalNumber, $keepRawInput,
PhoneNumber $phoneNumber) {
if (strlen($number) == 0) {
return 0;
}
$fullNumber = $number;
// Set the default prefix to be something that will never match.
$possibleCountryIddPrefix = "NonMatch";
if ($defaultRegionMetadata != null) {
$possibleCountryIddPrefix = $defaultRegionMetadata->getInternationalPrefix();
}
$countryCodeSource = $this->maybeStripInternationalPrefixAndNormalize($fullNumber, $possibleCountryIddPrefix);
if ($keepRawInput) {
$phoneNumber->setCountryCodeSource($countryCodeSource);
}
if ($countryCodeSource != CountryCodeSource::FROM_DEFAULT_COUNTRY) {
if (strlen($fullNumber) < self::MIN_LENGTH_FOR_NSN) {
throw new NumberParseException(NumberParseException::TOO_SHORT_AFTER_IDD,
"Phone number had an IDD, but after this was not "
. "long enough to be a viable phone number.");
}
$potentialCountryCode = $this->extractCountryCode($fullNumber, $nationalNumber);
if ($potentialCountryCode != 0) {
$phoneNumber->setCountryCode($potentialCountryCode);
return $potentialCountryCode;
}
// If this fails, they must be using a strange country calling code that we don't recognize,
// or that doesn't exist.
throw new NumberParseException(NumberParseException::INVALID_COUNTRY_CODE,
"Country calling code supplied was not recognised.");
} else if ($defaultRegionMetadata != null) {
// Check to see if the number starts with the country calling code for the default region. If
// so, we remove the country calling code, and do some checks on the validity of the number
// before and after.
$defaultCountryCode = $defaultRegionMetadata->getCountryCode();
$defaultCountryCodeString = (string)$defaultCountryCode;
$normalizedNumber = (string)$fullNumber;
if (strpos($normalizedNumber, $defaultCountryCodeString) === 0) {
$potentialNationalNumber = substr($normalizedNumber, strlen($defaultCountryCodeString));
$generalDesc = $defaultRegionMetadata->getGeneralDesc();
$validNumberPattern = $generalDesc->getNationalNumberPattern();
$this->maybeStripNationalPrefixAndCarrierCode(
$potentialNationalNumber, $defaultRegionMetadata, null /* Don't need the carrier code */);
$possibleNumberPattern = $generalDesc->getPossibleNumberPattern();
// If the number was not valid before but is valid now, or if it was too long before, we
// consider the number with the country calling code stripped to be a better result and
// keep that instead.
if ((preg_match('/' . $validNumberPattern . '/', $fullNumber) == 0 &&
preg_match('/' . $validNumberPattern . '/', $potentialNationalNumber) > 0) ||
$this->testNumberLengthAgainstPattern($possibleNumberPattern, (string)$fullNumber)
== ValidationResult::TOO_LONG) {
$nationalNumber .= $potentialNationalNumber;
if ($keepRawInput) {
$phoneNumber->setCountryCodeSource(CountryCodeSource::FROM_NUMBER_WITHOUT_PLUS_SIGN);
}
$phoneNumber->setCountryCode($defaultCountryCode);
return $defaultCountryCode;
}
}
}
// No country calling code present.
$phoneNumber->setCountryCode(0);
return 0;
}
/**
* Strips the IDD from the start of the number if present. Helper function used by
* maybeStripInternationalPrefixAndNormalize.
* @param string $iddPattern
* @param string $number
* @return bool
*/
private function parsePrefixAsIdd($iddPattern, &$number) {
$m = new Matcher($iddPattern, $number);
if ($m->lookingAt()) {
$matchEnd = $m->end();
// Only strip this if the first digit after the match is not a 0, since country calling codes
// cannot begin with 0.
$digitMatcher = new Matcher(self::$CAPTURING_DIGIT_PATTERN, substr($number, $matchEnd));
if ($digitMatcher->find()) {
$normalizedGroup = $this->normalizeDigitsOnly($digitMatcher->group(1));
if ($normalizedGroup == "0") {
return false;
}
}
$number = substr($number, $matchEnd);
return true;
}
return false;
}
/**
* Strips any national prefix (such as 0, 1) present in the number provided.
*
* @param string $number the normalized telephone number that we wish to strip any national
* dialing prefix from
* @param PhoneMetadata $metadata the metadata for the region that we think this number is from
* @param string $carrierCode a place to insert the carrier code if one is extracted
* @return bool true if a national prefix or carrier code (or both) could be extracted.
*/
private function maybeStripNationalPrefixAndCarrierCode(&$number, PhoneMetadata $metadata, $carrierCode) {
$numberLength = strlen($number);
$possibleNationalPrefix = $metadata->getNationalPrefixForParsing();
if ($numberLength == 0 || strlen($possibleNationalPrefix) == 0) {
// Early return for numbers of zero length.
return false;
}
// Attempt to parse the first digits as a national prefix.
$prefixMatcher = new Matcher($possibleNationalPrefix, $number);
if ($prefixMatcher->lookingAt()) {
$nationalNumberRule = $metadata->getGeneralDesc()->getNationalNumberPattern();
// Check if the original number is viable.
$nationalNumberRuleMatcher = new Matcher($nationalNumberRule, $number);
$isViableOriginalNumber = $nationalNumberRuleMatcher->matches();
// prefixMatcher.group(numOfGroups) == null implies nothing was captured by the capturing
// groups in possibleNationalPrefix; therefore, no transformation is necessary, and we just
// remove the national prefix.
$numOfGroups = $prefixMatcher->groupCount();
$transformRule = $metadata->getNationalPrefixTransformRule();
if ($transformRule == null || strlen($transformRule) == 0 ||
$prefixMatcher->group($numOfGroups) == null) {
// If the original number was viable, and the resultant number is not, we return.
$matcher = new Matcher($nationalNumberRule, substr($number, $prefixMatcher->end()));
if ($isViableOriginalNumber && !$matcher->matches()) {
return false;
}
if ($carrierCode != null && $numOfGroups > 0 && $prefixMatcher->group($numOfGroups) != null) {
$carrierCode->append($prefixMatcher->group(1));
}
$number = substr($number, $prefixMatcher->end());
return true;
} else {
// Check that the resultant number is still viable. If not, return. Check this by copying
// the string buffer and making the transformation on the copy first.
$transformedNumber = $number;
$transformedNumber = substr_replace($transformedNumber, $prefixMatcher->replaceFirst($transformRule), 0, $numberLength);
if ($isViableOriginalNumber &&
!$nationalNumberRule->matcher($transformedNumber->toString())->matches()) {
return false;
}
if ($carrierCode != null && $numOfGroups > 1) {
$carrierCode->append($prefixMatcher->group(1));
}
$number = substr_replace($number, $transformedNumber, 0, strlen($number));
return true;
}
}
return false;
}
/**
* Strips any international prefix (such as +, 00, 011) present in the number provided, normalizes
* the resulting number, and indicates if an international prefix was present.
*
* @param string $number the non-normalized telephone number that we wish to strip any international
* dialing prefix from.
* @param $possibleIddPrefix string the international direct dialing prefix from the region we
* think this number may be dialed in
* @return int the corresponding CountryCodeSource if an international dialing prefix could be
* removed from the number, otherwise CountryCodeSource.FROM_DEFAULT_COUNTRY if the number did
* not seem to be in international format.
*/
private function maybeStripInternationalPrefixAndNormalize(