-
Notifications
You must be signed in to change notification settings - Fork 468
/
Copy pathPhoneNumberUtil.php
3775 lines (3500 loc) · 181 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 libphonenumber;
use libphonenumber\Leniency\AbstractLeniency;
/**
* 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
* CLDR two-letter region-code format. These should be in upper-case. The list of the codes
* can be found here:
* http://www.unicode.org/cldr/charts/30/supplemental/territory_information.html
*
* @author Shaopeng Jia
* @see https://github.com/google/libphonenumber
*/
class PhoneNumberUtil
{
/** Flags to use when compiling regular expressions for phone numbers */
public const REGEX_FLAGS = 'ui'; //Unicode and case insensitive
// The minimum and maximum length of the national significant number.
public const MIN_LENGTH_FOR_NSN = 2;
// The ITU says the maximum length should be 15, but we have found longer numbers in Germany.
public const MAX_LENGTH_FOR_NSN = 17;
// We don't allow input strings for parsing to be longer than 250 chars. This prevents malicious
// input from overflowing the regular-expression engine.
public const MAX_INPUT_STRING_LENGTH = 250;
// The maximum length of the country calling code.
public const MAX_LENGTH_COUNTRY_CODE = 3;
public const REGION_CODE_FOR_NON_GEO_ENTITY = '001';
// Region-code for the unknown region.
public const UNKNOWN_REGION = 'ZZ';
public const NANPA_COUNTRY_CODE = 1;
// The PLUS_SIGN signifies the international prefix.
public const PLUS_SIGN = '+';
public const PLUS_CHARS = '++';
public const STAR_SIGN = '*';
public const RFC3966_EXTN_PREFIX = ';ext=';
public const RFC3966_PREFIX = 'tel:';
public const RFC3966_PHONE_CONTEXT = ';phone-context=';
public const RFC3966_ISDN_SUBADDRESS = ';isub=';
// 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.
public const VALID_ALPHA_PHONE_PATTERN = '(?:.*?[A-Za-z]){3}.*';
// We accept alpha characters in phone numbers, ASCII only, upper and lower case.
public const VALID_ALPHA = 'A-Za-z';
// 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.
public const DEFAULT_EXTN_PREFIX = ' ext. ';
// Regular expression of acceptable punctuation found in phone numbers, used to find numbers in
// text and to decide what is a viable phone number. This excludes diallable characters.
// 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.
public const VALID_PUNCTUATION = "-x\xE2\x80\x90-\xE2\x80\x95\xE2\x88\x92\xE3\x83\xBC\xEF\xBC\x8D-\xEF\xBC\x8F \xC2\xA0\xC2\xAD\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";
public const DIGITS = '\\p{Nd}';
// Pattern that makes it easy to distinguish whether a region has a single international dialing
// prefix or not. If a region has a single international prefix (e.g. 011 in USA), it will be
// represented as a string that contains a sequence of ASCII digits, and possible a tilde, which
// signals waiting for the tone. If there are multiple available international prefixes in a
// region, they will be represented as a regex string that always contains one or more characters
// that are not ASCII digits or a tilde.
public const SINGLE_INTERNATIONAL_PREFIX = "[\\d]+(?:[~\xE2\x81\x93\xE2\x88\xBC\xEF\xBD\x9E][\\d]+)?";
public 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.
public const FIRST_GROUP_PATTERN = '(\$\\d)';
// Constants used in the formatting rules to represent the national prefix, first group and
// carrier code respectively.
public const NP_STRING = '$NP';
public const FG_STRING = '$FG';
public const CC_STRING = '$CC';
// A pattern that is used to determine if the national prefix formatting rule has the first group
// only, i.e, does not start with the national prefix. Note that the pattern explicitly allows
// for unbalanced parentheses.
public const FIRST_GROUP_ONLY_PREFIX_PATTERN = '\\(?\\$1\\)?';
public static $PLUS_CHARS_PATTERN;
protected static $SEPARATOR_PATTERN;
protected static $CAPTURING_DIGIT_PATTERN;
protected static $VALID_START_CHAR_PATTERN;
public static $SECOND_NUMBER_START_PATTERN = '[\\\\/] *x';
public static $UNWANTED_END_CHAR_PATTERN = '[[\\P{N}&&\\P{L}]&&[^#]]+$';
protected static $DIALLABLE_CHAR_MAPPINGS = [];
protected static $CAPTURING_EXTN_DIGITS;
/**
* @var PhoneNumberUtil
*/
protected static $instance;
/**
* Only upper-case variants of alpha characters are stored.
*
* @var array
*/
protected static $ALPHA_MAPPINGS = [
'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',
];
/**
* Map of country calling codes that use a mobile token before the area code. One example of when
* this is relevant is when determining the length of the national destination code, which should
* be the length of the area code plus the length of the mobile token.
*
* @var array
*/
protected static $MOBILE_TOKEN_MAPPINGS = [];
/**
* Set of country codes that have geographically assigned mobile numbers (see GEO_MOBILE_COUNTRIES
* below) which are not based on *area codes*. For example, in China mobile numbers start with a
* carrier indicator, and beyond that are geographically assigned: this carrier indicator is not
* considered to be an area code.
*
* @var array
*/
protected static $GEO_MOBILE_COUNTRIES_WITHOUT_MOBILE_AREA_CODES;
/**
* Set of country codes that doesn't have national prefix, but it has area codes.
*
* @var array
*/
protected static $COUNTRIES_WITHOUT_NATIONAL_PREFIX_WITH_AREA_CODES;
/**
* Set of country calling codes that have geographically assigned mobile numbers. This may not be
* complete; we add calling codes case by case, as we find geographical mobile numbers or hear
* from user reports. Note that countries like the US, where we can't distinguish between
* fixed-line or mobile numbers, are not listed here, since we consider FIXED_LINE_OR_MOBILE to be
* a possibly geographically-related type anyway (like FIXED_LINE).
*
* @var array
*/
protected static $GEO_MOBILE_COUNTRIES;
/**
* For performance reasons, amalgamate both into one map.
*
* @var array
*/
protected 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 " ".
*
* @var array
*/
protected static $ALL_PLUS_NUMBER_GROUPING_SYMBOLS;
/**
* Simple ASCII digits map used to populate ALPHA_PHONE_MAPPINGS and
* ALL_PLUS_NUMBER_GROUPING_SYMBOLS.
*
* @var array
*/
protected static $asciiDigitMappings = [
'0' => '0',
'1' => '1',
'2' => '2',
'3' => '3',
'4' => '4',
'5' => '5',
'6' => '6',
'7' => '7',
'8' => '8',
'9' => '9',
];
/**
* Regexp of all possible ways to write extensions, for use when parsing. This will be run as a
* case-insensitive regexp match. Wide character versions are also provided after each ASCII
* version.
*
* @var String
*/
protected static $EXTN_PATTERNS_FOR_PARSING;
/**
* @var string
* @internal
*/
public static $EXTN_PATTERNS_FOR_MATCHING;
// Regular expression of valid global-number-digits for the phone-context parameter, following the
// syntax defined in RFC3966.
protected static $RFC3966_VISUAL_SEPARATOR = '[\\-\\.\\(\\)]?';
protected static $RFC3966_PHONE_DIGIT;
protected static $RFC3966_GLOBAL_NUMBER_DIGITS;
// Regular expression of valid domainname for the phone-context parameter, following the syntax
// defined in RFC3966.
protected static $ALPHANUM;
protected static $RFC3966_DOMAINLABEL;
protected static $RFC3966_TOPLABEL;
protected static $RFC3966_DOMAINNAME;
protected static $EXTN_PATTERN;
protected static $VALID_PHONE_NUMBER_PATTERN;
protected static $MIN_LENGTH_PHONE_NUMBER_PATTERN;
/**
* 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:
* [digits]{minLengthNsn}|
* plus_sign*(([punctuation]|[star])*[digits]){3,}([punctuation]|[star]|[digits]|[alpha])*
*
* The first reg-ex is to allow short numbers (two digits long) to be parsed if they are entered
* as "15" etc, but only if there is no punctuation in them. The second expression restricts the
* number of digits to three or more, but then allows them to be in international form, and to
* have alpha-characters and punctuation.
*
* Note VALID_PUNCTUATION starts with a -, so must be the first in the range.
*
* @var string
*/
protected static $VALID_PHONE_NUMBER;
protected static $numericCharacters = [
"\xef\xbc\x90" => 0,
"\xef\xbc\x91" => 1,
"\xef\xbc\x92" => 2,
"\xef\xbc\x93" => 3,
"\xef\xbc\x94" => 4,
"\xef\xbc\x95" => 5,
"\xef\xbc\x96" => 6,
"\xef\xbc\x97" => 7,
"\xef\xbc\x98" => 8,
"\xef\xbc\x99" => 9,
"\xd9\xa0" => 0,
"\xd9\xa1" => 1,
"\xd9\xa2" => 2,
"\xd9\xa3" => 3,
"\xd9\xa4" => 4,
"\xd9\xa5" => 5,
"\xd9\xa6" => 6,
"\xd9\xa7" => 7,
"\xd9\xa8" => 8,
"\xd9\xa9" => 9,
"\xdb\xb0" => 0,
"\xdb\xb1" => 1,
"\xdb\xb2" => 2,
"\xdb\xb3" => 3,
"\xdb\xb4" => 4,
"\xdb\xb5" => 5,
"\xdb\xb6" => 6,
"\xdb\xb7" => 7,
"\xdb\xb8" => 8,
"\xdb\xb9" => 9,
"\xe1\xa0\x90" => 0,
"\xe1\xa0\x91" => 1,
"\xe1\xa0\x92" => 2,
"\xe1\xa0\x93" => 3,
"\xe1\xa0\x94" => 4,
"\xe1\xa0\x95" => 5,
"\xe1\xa0\x96" => 6,
"\xe1\xa0\x97" => 7,
"\xe1\xa0\x98" => 8,
"\xe1\xa0\x99" => 9,
];
/**
* The set of county calling codes that map to the non-geo entity region ("001").
*
* @var array
*/
protected $countryCodesForNonGeographicalRegion = [];
/**
* The set of regions the library supports.
*
* @var array
*/
protected $supportedRegions = [];
/**
* A mapping from a country calling code to the region codes which denote the region represented
* by that country calling code. In the case of multiple regions sharing a calling code, such as
* the NANPA regions, the one indicated with "isMainCountryForCode" in the metadata should be
* first.
*
* @var array
*/
protected $countryCallingCodeToRegionCodeMap = [];
/**
* The set of regions that share country calling code 1.
*
* @var array
*/
protected $nanpaRegions = [];
/**
* @var MetadataSourceInterface
*/
protected $metadataSource;
/**
* @var MatcherAPIInterface
*/
protected $matcherAPI;
/**
* This class implements a singleton, so the only constructor is protected.
*/
protected function __construct(MetadataSourceInterface $metadataSource, $countryCallingCodeToRegionCodeMap)
{
$this->metadataSource = $metadataSource;
$this->countryCallingCodeToRegionCodeMap = $countryCallingCodeToRegionCodeMap;
$this->init();
$this->matcherAPI = RegexBasedMatcher::create();
static::initExtnPatterns();
static::initExtnPattern();
static::initRFC3966Patterns();
static::$PLUS_CHARS_PATTERN = '[' . static::PLUS_CHARS . ']+';
static::$SEPARATOR_PATTERN = '[' . static::VALID_PUNCTUATION . ']+';
static::$CAPTURING_DIGIT_PATTERN = '(' . static::DIGITS . ')';
static::initValidStartCharPattern();
static::initAlphaPhoneMappings();
static::initDiallableCharMappings();
static::$ALL_PLUS_NUMBER_GROUPING_SYMBOLS = [];
// Put (lower letter -> upper letter) and (upper letter -> upper letter) mappings.
foreach (static::$ALPHA_MAPPINGS as $c => $value) {
static::$ALL_PLUS_NUMBER_GROUPING_SYMBOLS[strtolower($c)] = $c;
static::$ALL_PLUS_NUMBER_GROUPING_SYMBOLS[$c] = $c;
}
static::$ALL_PLUS_NUMBER_GROUPING_SYMBOLS += static::$asciiDigitMappings;
static::$ALL_PLUS_NUMBER_GROUPING_SYMBOLS['-'] = '-';
static::$ALL_PLUS_NUMBER_GROUPING_SYMBOLS["\xEF\xBC\x8D"] = '-';
static::$ALL_PLUS_NUMBER_GROUPING_SYMBOLS["\xE2\x80\x90"] = '-';
static::$ALL_PLUS_NUMBER_GROUPING_SYMBOLS["\xE2\x80\x91"] = '-';
static::$ALL_PLUS_NUMBER_GROUPING_SYMBOLS["\xE2\x80\x92"] = '-';
static::$ALL_PLUS_NUMBER_GROUPING_SYMBOLS["\xE2\x80\x93"] = '-';
static::$ALL_PLUS_NUMBER_GROUPING_SYMBOLS["\xE2\x80\x94"] = '-';
static::$ALL_PLUS_NUMBER_GROUPING_SYMBOLS["\xE2\x80\x95"] = '-';
static::$ALL_PLUS_NUMBER_GROUPING_SYMBOLS["\xE2\x88\x92"] = '-';
static::$ALL_PLUS_NUMBER_GROUPING_SYMBOLS['/'] = '/';
static::$ALL_PLUS_NUMBER_GROUPING_SYMBOLS["\xEF\xBC\x8F"] = '/';
static::$ALL_PLUS_NUMBER_GROUPING_SYMBOLS[' '] = ' ';
static::$ALL_PLUS_NUMBER_GROUPING_SYMBOLS["\xE3\x80\x80"] = ' ';
static::$ALL_PLUS_NUMBER_GROUPING_SYMBOLS["\xE2\x81\xA0"] = ' ';
static::$ALL_PLUS_NUMBER_GROUPING_SYMBOLS['.'] = '.';
static::$ALL_PLUS_NUMBER_GROUPING_SYMBOLS["\xEF\xBC\x8E"] = '.';
static::initValidPhoneNumberPatterns();
static::$UNWANTED_END_CHAR_PATTERN = '[^' . static::DIGITS . static::VALID_ALPHA . '#]+$';
static::initMobileTokenMappings();
static::$GEO_MOBILE_COUNTRIES_WITHOUT_MOBILE_AREA_CODES = [];
static::$GEO_MOBILE_COUNTRIES_WITHOUT_MOBILE_AREA_CODES[] = 86; // China
static::$COUNTRIES_WITHOUT_NATIONAL_PREFIX_WITH_AREA_CODES = [];
static::$COUNTRIES_WITHOUT_NATIONAL_PREFIX_WITH_AREA_CODES[] = 52; // Mexico
static::$GEO_MOBILE_COUNTRIES = [];
static::$GEO_MOBILE_COUNTRIES[] = 52; // Mexico
static::$GEO_MOBILE_COUNTRIES[] = 54; // Argentina
static::$GEO_MOBILE_COUNTRIES[] = 55; // Brazil
static::$GEO_MOBILE_COUNTRIES[] = 62; // Indonesia: some prefixes only (fixed CMDA wireless)
static::$GEO_MOBILE_COUNTRIES = array_merge(static::$GEO_MOBILE_COUNTRIES, static::$GEO_MOBILE_COUNTRIES_WITHOUT_MOBILE_AREA_CODES);
}
/**
* 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|null $baseFileLocation
* @return PhoneNumberUtil instance
*/
public static function getInstance(
$baseFileLocation = null,
?array $countryCallingCodeToRegionCodeMap = null,
?MetadataLoaderInterface $metadataLoader = null,
?MetadataSourceInterface $metadataSource = null
) {
if (static::$instance === null) {
if ($countryCallingCodeToRegionCodeMap === null) {
$countryCallingCodeToRegionCodeMap = CountryCodeToRegionCodeMap::$countryCodeToRegionCodeMap;
}
if ($metadataLoader === null) {
$metadataLoader = new DefaultMetadataLoader();
}
if ($metadataSource === null) {
if ($baseFileLocation === null) {
$baseFileLocation = __DIR__ . '/data/PhoneNumberMetadata';
}
$metadataSource = new MultiFileMetadataSourceImpl($metadataLoader, $baseFileLocation);
}
static::$instance = new static($metadataSource, $countryCallingCodeToRegionCodeMap);
}
return static::$instance;
}
protected function init()
{
$supportedRegions = [[]];
foreach ($this->countryCallingCodeToRegionCodeMap as $countryCode => $regionCodes) {
// We can assume that if the country calling code maps to the non-geo entity region code then
// that's the only region code it maps to.
if (count($regionCodes) === 1 && static::REGION_CODE_FOR_NON_GEO_ENTITY === $regionCodes[0]) {
// This is the subset of all country codes that map to the non-geo entity region code.
$this->countryCodesForNonGeographicalRegion[] = $countryCode;
} else {
// The supported regions set does not include the "001" non-geo entity region code.
$supportedRegions[] = $regionCodes;
}
}
$this->supportedRegions = call_user_func_array('array_merge', $supportedRegions);
// If the non-geo entity still got added to the set of supported regions it must be because
// there are entries that list the non-geo entity alongside normal regions (which is wrong).
// If we discover this, remove the non-geo entity from the set of supported regions and log.
$idx_region_code_non_geo_entity = array_search(static::REGION_CODE_FOR_NON_GEO_ENTITY, $this->supportedRegions);
if ($idx_region_code_non_geo_entity !== false) {
unset($this->supportedRegions[$idx_region_code_non_geo_entity]);
}
$this->nanpaRegions = $this->countryCallingCodeToRegionCodeMap[static::NANPA_COUNTRY_CODE];
}
/**
* @internal
*/
public static function initExtnPatterns()
{
static::$EXTN_PATTERNS_FOR_PARSING = static::createExtnPattern(true);
static::$EXTN_PATTERNS_FOR_MATCHING = static::createExtnPattern(false);
}
/**
* Helper method for constructing regular expressions for parsing. Creates an expression that
* captures up to maxLength digits.
* @param int $maxLength
* @return string
*/
protected static function extnDigits($maxLength)
{
return '(' . self::DIGITS . '{1,' . $maxLength . '})';
}
/**
* Helper initialiser method to create the regular-expression pattern to match extensions.
* Note that there are currently six capturing groups for the extension itself. If this number is
* changed, MaybeStripExtension needs to be updated.
*
* @param boolean $forParsing
* @return string
*/
protected static function createExtnPattern($forParsing)
{
// We cap the maximum length of an extension based on the ambiguity of the way the extension is
// prefixed. As per ITU, the officially allowed length for extensions is actually 40, but we
// don't support this since we haven't seen real examples and this introduces many false
// interpretations as the extension labels are not standardized.
$extLimitAfterExplicitLabel = 20;
$extLimitAfterLikelyLabel = 15;
$extLimitAfterAmbiguousChar = 9;
$extLimitWhenNotSure = 6;
$possibleSeparatorsBetweenNumberAndExtLabel = "[ \xC2\xA0\\t,]*";
// Optional full stop (.) or colon, followed by zero or more spaces/tabs/commas.
$possibleCharsAfterExtLabel = "[:\\.\xEf\xBC\x8E]?[ \xC2\xA0\\t,-]*";
$optionalExtnSuffix = '#?';
// Here the extension is called out in more explicit way, i.e mentioning it obvious patterns
// like "ext.". 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.
$explicitExtLabels = "(?:e?xt(?:ensi(?:o\xCC\x81?|\xC3\xB3))?n?|\xEF\xBD\x85?\xEF\xBD\x98\xEF\xBD\x94\xEF\xBD\x8E?|\xD0\xB4\xD0\xBE\xD0\xB1|anexo)";
// One-character symbols that can be used to indicate an extension, and less commonly used
// or more ambiguous extension labels.
$ambiguousExtLabels = "(?:[x\xEF\xBD\x98#\xEF\xBC\x83~\xEF\xBD\x9E]|int|\xEF\xBD\x89\xEF\xBD\x8E\xEF\xBD\x94)";
// When extension is not separated clearly.
$ambiguousSeparator = '[- ]+';
$rfcExtn = static::RFC3966_EXTN_PREFIX . static::extnDigits($extLimitAfterExplicitLabel);
$explicitExtn = $possibleSeparatorsBetweenNumberAndExtLabel . $explicitExtLabels
. $possibleCharsAfterExtLabel . static::extnDigits($extLimitAfterExplicitLabel)
. $optionalExtnSuffix;
$ambiguousExtn = $possibleSeparatorsBetweenNumberAndExtLabel . $ambiguousExtLabels
. $possibleCharsAfterExtLabel . static::extnDigits($extLimitAfterAmbiguousChar) . $optionalExtnSuffix;
$americanStyleExtnWithSuffix = $ambiguousSeparator . static::extnDigits($extLimitWhenNotSure) . '#';
// The first regular expression covers RFC 3966 format, where the extension is added using
// ";ext=". The second more generic where extension is mentioned with explicit labels like
// "ext:". In both the above cases we allow more numbers in extension than any other extension
// labels. The third one captures when single character extension labels or less commonly used
// labels are used. In such cases we capture fewer extension digits in order to reduce the
// chance of falsely interpreting two numbers beside each other as a number + extension. The
// fourth one covers the special case of American numbers where the extension is written with a
// hash at the end, such as "- 503#".
$extensionPattern =
$rfcExtn . '|'
. $explicitExtn . '|'
. $ambiguousExtn . '|'
. $americanStyleExtnWithSuffix;
// Additional pattern that is supported when parsing extensions, not when matching.
if ($forParsing) {
// This is same as possibleSeparatorsBetweenNumberAndExtLabel, but not matching comma as
// extension label may have it.
$possibleSeparatorsNumberExtLabelNoComma = "[ \xC2\xA0\\t]*";
// ",," is commonly used for auto dialling the extension when connected. First comma is matched
// through possibleSeparatorsBetweenNumberAndExtLabel, so we do not repeat it here. Semi-colon
// works in Iphone and Android also to pop up a button with the extension number following.
$autoDiallingAndExtLabelsFound = '(?:,{2}|;)';
$autoDiallingExtn = $possibleSeparatorsNumberExtLabelNoComma
. $autoDiallingAndExtLabelsFound . $possibleCharsAfterExtLabel
. static::extnDigits($extLimitAfterLikelyLabel) . $optionalExtnSuffix;
$onlyCommasExtn = $possibleSeparatorsNumberExtLabelNoComma
. '(?:,)+' . $possibleCharsAfterExtLabel . static::extnDigits($extLimitAfterAmbiguousChar)
. $optionalExtnSuffix;
// Here the first pattern is exclusively for extension autodialling formats which are used
// when dialling and in this case we accept longer extensions. However, the second pattern
// is more liberal on the number of commas that acts as extension labels, so we have a strict
// cap on the number of digits in such extensions.
return $extensionPattern . '|'
. $autoDiallingExtn . '|'
. $onlyCommasExtn;
}
return $extensionPattern;
}
protected static function initExtnPattern()
{
static::$EXTN_PATTERN = '/(?:' . static::$EXTN_PATTERNS_FOR_PARSING . ')$/' . static::REGEX_FLAGS;
}
protected static function initRFC3966Patterns()
{
static::$RFC3966_PHONE_DIGIT = '(' . static::DIGITS . '|' . static::$RFC3966_VISUAL_SEPARATOR . ')';
static::$RFC3966_GLOBAL_NUMBER_DIGITS = '^\\' . static::PLUS_SIGN . static::$RFC3966_PHONE_DIGIT . '*' . static::DIGITS . static::$RFC3966_PHONE_DIGIT . '*$';
static::$ALPHANUM = static::VALID_ALPHA . static::DIGITS;
static::$RFC3966_DOMAINLABEL = '[' . static::$ALPHANUM . ']+((\\-)*[' . static::$ALPHANUM . '])*';
static::$RFC3966_TOPLABEL = '[' . static::VALID_ALPHA . ']+((\\-)*[' . static::$ALPHANUM . '])*';
static::$RFC3966_DOMAINNAME = '^(' . static::$RFC3966_DOMAINLABEL . '\\.)*' . static::$RFC3966_TOPLABEL . '\\.?$';
}
protected static function initValidPhoneNumberPatterns()
{
static::initExtnPatterns();
static::$MIN_LENGTH_PHONE_NUMBER_PATTERN = '[' . static::DIGITS . ']{' . static::MIN_LENGTH_FOR_NSN . '}';
static::$VALID_PHONE_NUMBER = '[' . static::PLUS_CHARS . ']*(?:[' . static::VALID_PUNCTUATION . static::STAR_SIGN . ']*[' . static::DIGITS . ']){3,}[' . static::VALID_PUNCTUATION . static::STAR_SIGN . static::VALID_ALPHA . static::DIGITS . ']*';
static::$VALID_PHONE_NUMBER_PATTERN = '%^' . static::$MIN_LENGTH_PHONE_NUMBER_PATTERN . '$|^' . static::$VALID_PHONE_NUMBER . '(?:' . static::$EXTN_PATTERNS_FOR_PARSING . ')?$%' . static::REGEX_FLAGS;
}
protected static function initAlphaPhoneMappings()
{
static::$ALPHA_PHONE_MAPPINGS = static::$ALPHA_MAPPINGS + static::$asciiDigitMappings;
}
protected static function initValidStartCharPattern()
{
static::$VALID_START_CHAR_PATTERN = '[' . static::PLUS_CHARS . static::DIGITS . ']';
}
protected static function initMobileTokenMappings()
{
static::$MOBILE_TOKEN_MAPPINGS = [];
static::$MOBILE_TOKEN_MAPPINGS['54'] = '9';
}
protected static function initDiallableCharMappings()
{
static::$DIALLABLE_CHAR_MAPPINGS = static::$asciiDigitMappings;
static::$DIALLABLE_CHAR_MAPPINGS[static::PLUS_SIGN] = static::PLUS_SIGN;
static::$DIALLABLE_CHAR_MAPPINGS['*'] = '*';
static::$DIALLABLE_CHAR_MAPPINGS['#'] = '#';
}
/**
* Used for testing purposes only to reset the PhoneNumberUtil singleton to null.
*/
public static function resetInstance()
{
static::$instance = null;
}
/**
* 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)
{
if (static::$ALPHA_PHONE_MAPPINGS === null) {
static::initAlphaPhoneMappings();
}
return static::normalizeHelper($number, static::$ALPHA_PHONE_MAPPINGS, false);
}
/**
* 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.
*/
protected static function normalizeHelper($number, array $normalizationReplacements, $removeNonMatches)
{
$normalizedNumber = '';
$strLength = mb_strlen($number, 'UTF-8');
for ($i = 0; $i < $strLength; $i++) {
$character = mb_substr($number, $i, 1, 'UTF-8');
if (isset($normalizationReplacements[mb_strtoupper($character, 'UTF-8')])) {
$normalizedNumber .= $normalizationReplacements[mb_strtoupper($character, 'UTF-8')];
} elseif (!$removeNonMatches) {
$normalizedNumber .= $character;
}
// If neither of the above are true, we remove this character.
}
return $normalizedNumber;
}
/**
* Helper function to check if the national prefix formatting rule has the first group only, i.e.,
* does not start with the national prefix.
*
* @param string $nationalPrefixFormattingRule
* @return bool
*/
public static function formattingRuleHasFirstGroupOnly($nationalPrefixFormattingRule)
{
$firstGroupOnlyPrefixPatternMatcher = new Matcher(
static::FIRST_GROUP_ONLY_PREFIX_PATTERN,
$nationalPrefixFormattingRule
);
return $nationalPrefixFormattingRule === ''
|| $firstGroupOnlyPrefixPatternMatcher->matches();
}
/**
* Returns all regions the library has metadata for.
*
* @return array An unordered array of the two-letter region codes for every geographical region the
* library supports
*/
public function getSupportedRegions()
{
return $this->supportedRegions;
}
/**
* Returns all global network calling codes the library has metadata for.
*
* @return array An unordered array of the country calling codes for every non-geographical entity
* the library supports
*/
public function getSupportedGlobalNetworkCallingCodes()
{
return $this->countryCodesForNonGeographicalRegion;
}
/**
* Returns all country calling codes the library has metadata for, covering both non-geographical
* entities (global network calling codes) and those used for geographical entities. The could be
* used to populate a drop-down box of country calling codes for a phone-number widget, for
* instance.
*
* @return array An unordered array of the country calling codes for every geographical and
* non-geographical entity the library supports
*/
public function getSupportedCallingCodes()
{
return array_keys($this->countryCallingCodeToRegionCodeMap);
}
/**
* Returns true if there is any possible number data set for a particular PhoneNumberDesc.
*
* @return bool
*/
protected static function descHasPossibleNumberData(PhoneNumberDesc $desc)
{
// If this is empty, it means numbers of this type inherit from the "general desc" -> the value
// '-1' means that no numbers exist for this type.
$possibleLength = $desc->getPossibleLength();
return count($possibleLength) != 1 || $possibleLength[0] != -1;
}
/**
* Returns true if there is any data set for a particular PhoneNumberDesc.
*
* @return bool
*/
protected static function descHasData(PhoneNumberDesc $desc)
{
// Checking most properties since we don't know what's present, since a custom build may have
// stripped just one of them (e.g. liteBuild strips exampleNumber). We don't bother checking the
// possibleLengthsLocalOnly, since if this is the only thing that's present we don't really
// support the type at all: no type-specific methods will work with only this data.
return $desc->hasExampleNumber()
|| static::descHasPossibleNumberData($desc)
|| $desc->hasNationalNumberPattern();
}
/**
* Returns the types we have metadata for based on the PhoneMetadata object passed in.
*
* @return array
*/
private function getSupportedTypesForMetadata(PhoneMetadata $metadata)
{
$types = [];
foreach (array_keys(PhoneNumberType::values()) as $type) {
if ($type === PhoneNumberType::FIXED_LINE_OR_MOBILE || $type === PhoneNumberType::UNKNOWN) {
// Never return FIXED_LINE_OR_MOBILE (it is a convenience type, and represents that a
// particular number type can't be determined) or UNKNOWN (the non-type).
continue;
}
if (self::descHasData($this->getNumberDescByType($metadata, $type))) {
$types[] = $type;
}
}
return $types;
}
/**
* Returns the types for a given region which the library has metadata for. Will not include
* FIXED_LINE_OR_MOBILE (if the numbers in this region could be classified as FIXED_LINE_OR_MOBILE,
* both FIXED_LINE and MOBILE would be present) and UNKNOWN.
*
* No types will be returned for invalid or unknown region codes.
*
* @param string $regionCode
* @return array
*/
public function getSupportedTypesForRegion($regionCode)
{
if (!$this->isValidRegionCode($regionCode)) {
return [];
}
$metadata = $this->getMetadataForRegion($regionCode);
return $this->getSupportedTypesForMetadata($metadata);
}
/**
* Returns the types for a country-code belonging to a non-geographical entity which the library
* has metadata for. Will not include FIXED_LINE_OR_MOBILE (if numbers for this non-geographical
* entity could be classified as FIXED_LINE_OR_MOBILE, both FIXED_LINE and MOBILE would be
* present) and UNKNOWN.
*
* @param int $countryCallingCode
* @return array
*/
public function getSupportedTypesForNonGeoEntity($countryCallingCode)
{
$metadata = $this->getMetadataForNonGeographicalRegion($countryCallingCode);
if ($metadata === null) {
return [];
}
return $this->getSupportedTypesForMetadata($metadata);
}
/**
* Gets the length of the geographical area code from 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:
*
* <code>
* $phoneUtil = PhoneNumberUtil::getInstance();
* $number = $phoneUtil->parse("16502530000", "US");
* $nationalSignificantNumber = $phoneUtil->getNationalSignificantNumber($number);
*
* $areaCodeLength = $phoneUtil->getLengthOfGeographicalAreaCode($number);
* if ($areaCodeLength > 0)
* {
* $areaCode = substr($nationalSignificantNumber, 0,$areaCodeLength);
* $subscriberNumber = substr($nationalSignificantNumber, $areaCodeLength);
* } else {
* $areaCode = "";
* $subscriberNumber = $nationalSignificantNumber;
* }
* </code>
*
* 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 nationalNumber}
* 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 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)
{
$metadata = $this->getMetadataForRegion($this->getRegionCodeForNumber($number));
if ($metadata === null) {
return 0;
}
$countryCallingCode = $number->getCountryCode();
// If a country doesn't use a national prefix, and this number doesn't have an Italian leading
// zero, we assume it is a closed dialling plan with no area codes.
// Note:this is our general assumption, but there are exceptions which are tracked in
// COUNTRIES_WITHOUT_NATIONAL_PREFIX_WITH_AREA_CODES.
if (!$metadata->hasNationalPrefix() && !$number->isItalianLeadingZero() && !in_array($countryCallingCode, self::$COUNTRIES_WITHOUT_NATIONAL_PREFIX_WITH_AREA_CODES)) {
return 0;
}
$type = $this->getNumberType($number);
if ($type === PhoneNumberType::MOBILE
// Note this is a rough heuristic; it doesn't cover Indonesia well, for example, where area
// codes are present for some mobile phones but not for others. We have no better way of
// representing this in the metadata at this point.
&& in_array($countryCallingCode, self::$GEO_MOBILE_COUNTRIES_WITHOUT_MOBILE_AREA_CODES)
) {
return 0;
}
if (!$this->isNumberGeographical($type, $countryCallingCode)) {
return 0;
}
return $this->getLengthOfNationalDestinationCode($number);
}
/**
* Returns the metadata for the given region code or {@code null} if the region code is invalid
* or unknown.
*
* @param string $regionCode
* @return null|PhoneMetadata
*/
public function getMetadataForRegion($regionCode)
{
if (!$this->isValidRegionCode($regionCode)) {
return null;
}
return $this->metadataSource->getMetadataForRegion($regionCode);
}
/**
* Helper function to check region code is not unknown or null.
*
* @param string $regionCode
* @return bool
*/
protected function isValidRegionCode($regionCode)
{
return $regionCode !== null && !is_numeric($regionCode) && in_array(strtoupper($regionCode), $this->supportedRegions);
}
/**
* Returns the region where a phone number is from. This could be used for geocoding at the region
* level. Only guarantees correct results for valid, full numbers (not short-codes, or invalid
* numbers).
*
* @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])) {
return null;
}
$regions = $this->countryCallingCodeToRegionCodeMap[$countryCode];
if (count($regions) == 1) {
return $regions[0];
}
return $this->getRegionCodeForNumberFromRegionList($number, $regions);
}
/**
* Returns the region code for a number from the list of region codes passing in.
*
* @return null|string
*/
protected function getRegionCodeForNumberFromRegionList(PhoneNumber $number, array $regionCodes)
{
$nationalNumber = $this->getNationalSignificantNumber($number);
foreach ($regionCodes as $regionCode) {
// If leadingDigits is present, use this. Otherwise, do full validation.
// Metadata cannot be null because the region codes come from the country calling code map.
$metadata = $this->getMetadataForRegion($regionCode);
if ($metadata->hasLeadingDigits()) {
$nbMatches = preg_match(
'/' . $metadata->getLeadingDigits() . '/',
$nationalNumber,
$matches,
PREG_OFFSET_CAPTURE
);
if ($nbMatches > 0 && $matches[0][1] === 0) {
return $regionCode;
}
} elseif ($this->getNumberTypeHelper($nationalNumber, $metadata) != PhoneNumberType::UNKNOWN) {
return $regionCode;
}
}
return null;
}
/**
* Gets the national significant number of the a phone number. Note a national significant number
* doesn't contain a national prefix or any formatting.
*
* @param PhoneNumber $number the phone number for which the national significant number is needed
* @return string the national significant number of the PhoneNumber object passed in
*/
public function getNationalSignificantNumber(PhoneNumber $number)
{
// If leading zero(s) have been set, we prefix this now. Note this is not a national prefix.
$nationalNumber = '';