Proyectos de Subversion Moodle

Rev

| Ultima modificación | Ver Log |

Rev Autor Línea Nro. Línea
1441 ariadna 1
<?php
2
 
3
declare(strict_types=1);
4
 
5
namespace libphonenumber;
6
 
7
/**
8
 * Utility for international phone numbers. Functionality includes formatting, parsing and
9
 * validation.
10
 *
11
 * <p>If you use this library, and want to be notified about important changes, please sign up to
12
 * our <a href="http://groups.google.com/group/libphonenumber-discuss/about">mailing list</a>.
13
 *
14
 * NOTE: A lot of methods in this class require Region Code strings. These must be provided using
15
 * CLDR two-letter region-code format. These should be in upper-case. The list of the codes
16
 * can be found here:
17
 * http://www.unicode.org/cldr/charts/30/supplemental/territory_information.html
18
 * @phpstan-consistent-constructor
19
 */
20
class PhoneNumberUtil
21
{
22
    /** Flags to use when compiling regular expressions for phone numbers */
23
    protected const REGEX_FLAGS = 'ui'; //Unicode and case insensitive
24
    // The minimum and maximum length of the national significant number.
25
    protected const MIN_LENGTH_FOR_NSN = 2;
26
    // The ITU says the maximum length should be 15, but we have found longer numbers in Germany.
27
    protected const MAX_LENGTH_FOR_NSN = 17;
28
 
29
    // We don't allow input strings for parsing to be longer than 250 chars. This prevents malicious
30
    // input from overflowing the regular-expression engine.
31
    protected const MAX_INPUT_STRING_LENGTH = 250;
32
 
33
    // The maximum length of the country calling code.
34
    protected const MAX_LENGTH_COUNTRY_CODE = 3;
35
 
36
    /**
37
     * @internal
38
     */
39
    public const REGION_CODE_FOR_NON_GEO_ENTITY = '001';
40
    /**
41
     * @internal
42
     */
43
    public const META_DATA_FILE_PREFIX = __DIR__ . '/data/PhoneNumberMetadata';
44
 
45
    // Region-code for the unknown region.
46
    protected const UNKNOWN_REGION = 'ZZ';
47
 
48
    protected const NANPA_COUNTRY_CODE = 1;
49
    // The PLUS_SIGN signifies the international prefix.
50
    protected const PLUS_SIGN = '+';
51
    protected const PLUS_CHARS = '++';
52
    protected const STAR_SIGN = '*';
53
 
54
    protected const RFC3966_EXTN_PREFIX = ';ext=';
55
    protected const RFC3966_PREFIX = 'tel:';
56
    protected const RFC3966_PHONE_CONTEXT = ';phone-context=';
57
    protected const RFC3966_ISDN_SUBADDRESS = ';isub=';
58
 
59
    // We use this pattern to check if the phone number has at least three letters in it - if so, then
60
    // we treat it as a number where some phone-number digits are represented by letters.
61
    protected const VALID_ALPHA_PHONE_PATTERN = '(?:.*?[A-Za-z]){3}.*';
62
    // We accept alpha characters in phone numbers, ASCII only, upper and lower case.
63
    protected const VALID_ALPHA = 'A-Za-z';
64
 
65
    // Default extension prefix to use when formatting. This will be put in front of any extension
66
    // component of the number, after the main national number is formatted. For example, if you wish
67
    // the default extension formatting to be " extn: 3456", then you should specify " extn: " here
68
    // as the default extension prefix. This can be overridden by region-specific preferences.
69
    protected const DEFAULT_EXTN_PREFIX = ' ext. ';
70
 
71
    // Regular expression of acceptable punctuation found in phone numbers, used to find numbers in
72
    // text and to decide what is a viable phone number. This excludes diallable characters.
73
    // This consists of dash characters, white space characters, full stops, slashes,
74
    // square brackets, parentheses and tildes. It also includes the letter 'x' as that is found as a
75
    // placeholder for carrier information in some phone numbers. Full-width variants are also
76
    // present.
77
    protected 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";
78
    protected const DIGITS = '\\p{Nd}';
79
 
80
    // Pattern that makes it easy to distinguish whether a region has a single international dialing
81
    // prefix or not. If a region has a single international prefix (e.g. 011 in USA), it will be
82
    // represented as a string that contains a sequence of ASCII digits, and possible a tilde, which
83
    // signals waiting for the tone. If there are multiple available international prefixes in a
84
    // region, they will be represented as a regex string that always contains one or more characters
85
    // that are not ASCII digits or a tilde.
86
    protected const SINGLE_INTERNATIONAL_PREFIX = "[\\d]+(?:[~\xE2\x81\x93\xE2\x88\xBC\xEF\xBD\x9E][\\d]+)?";
87
    protected const NON_DIGITS_PATTERN = '(\\D+)';
88
 
89
    // The FIRST_GROUP_PATTERN was originally set to $1 but there are some countries for which the
90
    // first group is not used in the national pattern (e.g. Argentina) so the $1 group does not match
91
    // correctly. Therefore, we use \d, so that the first group actually used in the pattern will be
92
    // matched.
93
    protected const FIRST_GROUP_PATTERN = '(\$\\d)';
94
    // Constants used in the formatting rules to represent the national prefix, first group and
95
    // carrier code respectively.
96
    protected const NP_STRING = '$NP';
97
    protected const FG_STRING = '$FG';
98
    protected const CC_STRING = '$CC';
99
 
100
    // A pattern that is used to determine if the national prefix formatting rule has the first group
101
    // only, i.e, does not start with the national prefix. Note that the pattern explicitly allows
102
    // for unbalanced parentheses.
103
    protected const FIRST_GROUP_ONLY_PREFIX_PATTERN = '\\(?\\$1\\)?';
104
    /**
105
     * @internal
106
     */
107
    public const PLUS_CHARS_PATTERN = '[' . self::PLUS_CHARS . ']+';
108
    protected const SEPARATOR_PATTERN = '[' . self::VALID_PUNCTUATION . ']+';
109
    protected const CAPTURING_DIGIT_PATTERN = '(' . self::DIGITS . ')';
110
    protected const VALID_START_CHAR_PATTERN = '[' . self::PLUS_CHARS . self::DIGITS . ']';
111
    protected const SECOND_NUMBER_START_PATTERN = '[\\\\/] *x';
112
    //protected const UNWANTED_END_CHAR_PATTERN = '[[\\P{N}&&\\P{L}]&&[^#]]+$';
113
    protected const UNWANTED_END_CHAR_PATTERN = '[^' . self::DIGITS . self::VALID_ALPHA . '#]+$';
114
    protected const DIALLABLE_CHAR_MAPPINGS = self::ASCII_DIGIT_MAPPINGS
115
        + [self::PLUS_SIGN => self::PLUS_SIGN]
116
    + ['*' => '*', '#' => '#'];
117
 
118
 
119
    protected static ?PhoneNumberUtil $instance = null;
120
 
121
    /**
122
     * Only upper-case variants of alpha characters are stored.
123
     */
124
    protected const ALPHA_MAPPINGS = [
125
        'A' => '2',
126
        'B' => '2',
127
        'C' => '2',
128
        'D' => '3',
129
        'E' => '3',
130
        'F' => '3',
131
        'G' => '4',
132
        'H' => '4',
133
        'I' => '4',
134
        'J' => '5',
135
        'K' => '5',
136
        'L' => '5',
137
        'M' => '6',
138
        'N' => '6',
139
        'O' => '6',
140
        'P' => '7',
141
        'Q' => '7',
142
        'R' => '7',
143
        'S' => '7',
144
        'T' => '8',
145
        'U' => '8',
146
        'V' => '8',
147
        'W' => '9',
148
        'X' => '9',
149
        'Y' => '9',
150
        'Z' => '9',
151
    ];
152
 
153
    /**
154
     * Map of country calling codes that use a mobile token before the area code. One example of when
155
     * this is relevant is when determining the length of the national destination code, which should
156
     * be the length of the area code plus the length of the mobile token.
157
     */
158
    protected const MOBILE_TOKEN_MAPPINGS = [
159
        '54' => '9',
160
    ];
161
 
162
    /**
163
     * Set of country codes that have geographically assigned mobile numbers (see GEO_MOBILE_COUNTRIES
164
     * below) which are not based on *area codes*. For example, in China mobile numbers start with a
165
     * carrier indicator, and beyond that are geographically assigned: this carrier indicator is not
166
     * considered to be an area code.
167
     */
168
    protected const GEO_MOBILE_COUNTRIES_WITHOUT_MOBILE_AREA_CODES = [
169
        86, // China
170
    ];
171
 
172
    /**
173
     * Set of country codes that doesn't have national prefix, but it has area codes.
174
     */
175
    protected const COUNTRIES_WITHOUT_NATIONAL_PREFIX_WITH_AREA_CODES = [
176
        52, // Mexico
177
    ];
178
 
179
    /**
180
     * Set of country calling codes that have geographically assigned mobile numbers. This may not be
181
     * complete; we add calling codes case by case, as we find geographical mobile numbers or hear
182
     * from user reports. Note that countries like the US, where we can't distinguish between
183
     * fixed-line or mobile numbers, are not listed here, since we consider FIXED_LINE_OR_MOBILE to be
184
     * a possibly geographically-related type anyway (like FIXED_LINE).
185
     */
186
    protected const GEO_MOBILE_COUNTRIES = [
187
        52, // Mexico
188
        54, // Argentina
189
        55, // Brazil
190
        62, // Indonesia: some prefixes only (fixed CMDA wireless)
191
    ] + self::GEO_MOBILE_COUNTRIES_WITHOUT_MOBILE_AREA_CODES;
192
 
193
    /**
194
     * For performance reasons, amalgamate both into one map.
195
     */
196
    protected const ALPHA_PHONE_MAPPINGS = self::ALPHA_MAPPINGS + self::ASCII_DIGIT_MAPPINGS;
197
 
198
    /**
199
     * Separate map of all symbols that we wish to retain when formatting alpha numbers. This
200
     * includes digits, ASCII letters and number grouping symbols such as "-" and " ".
201
     *
202
     * @var array<string,string>
203
     */
204
    protected static array $ALL_PLUS_NUMBER_GROUPING_SYMBOLS;
205
 
206
    /**
207
     * Simple ASCII digits map used to populate ALPHA_PHONE_MAPPINGS and
208
     * ALL_PLUS_NUMBER_GROUPING_SYMBOLS.
209
     */
210
    protected const ASCII_DIGIT_MAPPINGS = [
211
        '0' => '0',
212
        '1' => '1',
213
        '2' => '2',
214
        '3' => '3',
215
        '4' => '4',
216
        '5' => '5',
217
        '6' => '6',
218
        '7' => '7',
219
        '8' => '8',
220
        '9' => '9',
221
    ];
222
 
223
    /**
224
     * Regexp of all possible ways to write extensions, for use when parsing. This will be run as a
225
     * case-insensitive regexp match. Wide character versions are also provided after each ASCII
226
     * version.
227
     */
228
    protected static string $EXTN_PATTERNS_FOR_PARSING;
229
    protected static string $EXTN_PATTERNS_FOR_MATCHING;
230
    // Regular expression of valid global-number-digits for the phone-context parameter, following the
231
    // syntax defined in RFC3966.
232
    protected static string $RFC3966_VISUAL_SEPARATOR = '[\\-\\.\\(\\)]?';
233
    protected static string $RFC3966_PHONE_DIGIT;
234
    protected static string $RFC3966_GLOBAL_NUMBER_DIGITS;
235
 
236
    // Regular expression of valid domainname for the phone-context parameter, following the syntax
237
    // defined in RFC3966.
238
    protected static string $ALPHANUM;
239
    protected static string $RFC3966_DOMAINLABEL;
240
    protected static string $RFC3966_TOPLABEL;
241
    protected static string $RFC3966_DOMAINNAME;
242
    protected static string $EXTN_PATTERN;
243
    protected static string $VALID_PHONE_NUMBER_PATTERN;
244
    protected static string $MIN_LENGTH_PHONE_NUMBER_PATTERN;
245
    /**
246
     *  Regular expression of viable phone numbers. This is location independent. Checks we have at
247
     * least three leading digits, and only valid punctuation, alpha characters and
248
     * digits in the phone number. Does not include extension data.
249
     * The symbol 'x' is allowed here as valid punctuation since it is often used as a placeholder for
250
     * carrier codes, for example in Brazilian phone numbers. We also allow multiple "+" characters at
251
     * the start.
252
     * Corresponds to the following:
253
     * [digits]{minLengthNsn}|
254
     * plus_sign*(([punctuation]|[star])*[digits]){3,}([punctuation]|[star]|[digits]|[alpha])*
255
     *
256
     * The first reg-ex is to allow short numbers (two digits long) to be parsed if they are entered
257
     * as "15" etc, but only if there is no punctuation in them. The second expression restricts the
258
     * number of digits to three or more, but then allows them to be in international form, and to
259
     * have alpha-characters and punctuation.
260
     *
261
     * Note VALID_PUNCTUATION starts with a -, so must be the first in the range.
262
     */
263
    protected static string $VALID_PHONE_NUMBER;
264
    /**
265
     * @var array<string,int>
266
     */
267
    protected const NUMERIC_CHARACTERS = [
268
        "\xef\xbc\x90" => 0,
269
        "\xef\xbc\x91" => 1,
270
        "\xef\xbc\x92" => 2,
271
        "\xef\xbc\x93" => 3,
272
        "\xef\xbc\x94" => 4,
273
        "\xef\xbc\x95" => 5,
274
        "\xef\xbc\x96" => 6,
275
        "\xef\xbc\x97" => 7,
276
        "\xef\xbc\x98" => 8,
277
        "\xef\xbc\x99" => 9,
278
 
279
        "\xd9\xa0" => 0,
280
        "\xd9\xa1" => 1,
281
        "\xd9\xa2" => 2,
282
        "\xd9\xa3" => 3,
283
        "\xd9\xa4" => 4,
284
        "\xd9\xa5" => 5,
285
        "\xd9\xa6" => 6,
286
        "\xd9\xa7" => 7,
287
        "\xd9\xa8" => 8,
288
        "\xd9\xa9" => 9,
289
 
290
        "\xdb\xb0" => 0,
291
        "\xdb\xb1" => 1,
292
        "\xdb\xb2" => 2,
293
        "\xdb\xb3" => 3,
294
        "\xdb\xb4" => 4,
295
        "\xdb\xb5" => 5,
296
        "\xdb\xb6" => 6,
297
        "\xdb\xb7" => 7,
298
        "\xdb\xb8" => 8,
299
        "\xdb\xb9" => 9,
300
 
301
        "\xe1\xa0\x90" => 0,
302
        "\xe1\xa0\x91" => 1,
303
        "\xe1\xa0\x92" => 2,
304
        "\xe1\xa0\x93" => 3,
305
        "\xe1\xa0\x94" => 4,
306
        "\xe1\xa0\x95" => 5,
307
        "\xe1\xa0\x96" => 6,
308
        "\xe1\xa0\x97" => 7,
309
        "\xe1\xa0\x98" => 8,
310
        "\xe1\xa0\x99" => 9,
311
    ];
312
 
313
    /**
314
     * The set of county calling codes that map to the non-geo entity region ("001").
315
     *
316
     * @var int[]
317
     */
318
    protected array $countryCodesForNonGeographicalRegion = [];
319
    /**
320
     * The set of regions the library supports.
321
     *
322
     * @var string[]
323
     */
324
    protected array $supportedRegions = [];
325
 
326
    /**
327
     * A mapping from a country calling code to the region codes which denote the region represented
328
     * by that country calling code. In the case of multiple regions sharing a calling code, such as
329
     * the NANPA regions, the one indicated with "isMainCountryForCode" in the metadata should be
330
     * first.
331
     *
332
     * @var array<int,string[]>
333
     */
334
    protected array $countryCallingCodeToRegionCodeMap = [];
335
    /**
336
     * The set of regions that share country calling code 1.
337
     *
338
     * @var string[]
339
     */
340
    protected array $nanpaRegions = [];
341
 
342
    protected MetadataSourceInterface $metadataSource;
343
 
344
    protected MatcherAPIInterface $matcherAPI;
345
 
346
    /**
347
     * This class implements a singleton, so the only constructor is protected.
348
     * @param array<int,string[]> $countryCallingCodeToRegionCodeMap
349
     */
350
    protected function __construct(MetadataSourceInterface $metadataSource, array $countryCallingCodeToRegionCodeMap)
351
    {
352
        $this->metadataSource = $metadataSource;
353
        $this->countryCallingCodeToRegionCodeMap = $countryCallingCodeToRegionCodeMap;
354
        $this->init();
355
        $this->matcherAPI = RegexBasedMatcher::create();
356
        static::initExtnPatterns();
357
        static::initExtnPattern();
358
        static::initRFC3966Patterns();
359
 
360
        static::$ALL_PLUS_NUMBER_GROUPING_SYMBOLS = [];
361
        // Put (lower letter -> upper letter) and (upper letter -> upper letter) mappings.
362
        foreach (static::ALPHA_MAPPINGS as $c => $value) {
363
            static::$ALL_PLUS_NUMBER_GROUPING_SYMBOLS[strtolower($c)] = $c;
364
            static::$ALL_PLUS_NUMBER_GROUPING_SYMBOLS[(string) $c] = (string) $c;
365
        }
366
        static::$ALL_PLUS_NUMBER_GROUPING_SYMBOLS += static::ASCII_DIGIT_MAPPINGS;
367
        static::$ALL_PLUS_NUMBER_GROUPING_SYMBOLS['-'] = '-';
368
        static::$ALL_PLUS_NUMBER_GROUPING_SYMBOLS["\xEF\xBC\x8D"] = '-';
369
        static::$ALL_PLUS_NUMBER_GROUPING_SYMBOLS["\xE2\x80\x90"] = '-';
370
        static::$ALL_PLUS_NUMBER_GROUPING_SYMBOLS["\xE2\x80\x91"] = '-';
371
        static::$ALL_PLUS_NUMBER_GROUPING_SYMBOLS["\xE2\x80\x92"] = '-';
372
        static::$ALL_PLUS_NUMBER_GROUPING_SYMBOLS["\xE2\x80\x93"] = '-';
373
        static::$ALL_PLUS_NUMBER_GROUPING_SYMBOLS["\xE2\x80\x94"] = '-';
374
        static::$ALL_PLUS_NUMBER_GROUPING_SYMBOLS["\xE2\x80\x95"] = '-';
375
        static::$ALL_PLUS_NUMBER_GROUPING_SYMBOLS["\xE2\x88\x92"] = '-';
376
        static::$ALL_PLUS_NUMBER_GROUPING_SYMBOLS['/'] = '/';
377
        static::$ALL_PLUS_NUMBER_GROUPING_SYMBOLS["\xEF\xBC\x8F"] = '/';
378
        static::$ALL_PLUS_NUMBER_GROUPING_SYMBOLS[' '] = ' ';
379
        static::$ALL_PLUS_NUMBER_GROUPING_SYMBOLS["\xE3\x80\x80"] = ' ';
380
        static::$ALL_PLUS_NUMBER_GROUPING_SYMBOLS["\xE2\x81\xA0"] = ' ';
381
        static::$ALL_PLUS_NUMBER_GROUPING_SYMBOLS['.'] = '.';
382
        static::$ALL_PLUS_NUMBER_GROUPING_SYMBOLS["\xEF\xBC\x8E"] = '.';
383
 
384
        static::initValidPhoneNumberPatterns();
385
    }
386
 
387
    /**
388
     * Gets a {@link PhoneNumberUtil} instance to carry out international phone number formatting,
389
     * parsing or validation. The instance is loaded with phone number metadata for a number of most
390
     * commonly used regions.
391
     *
392
     * <p>The {@link PhoneNumberUtil} is implemented as a singleton. Therefore, calling getInstance
393
     * multiple times will only result in one instance being created.
394
     *
395
     * @param array<int,array<int|string>>|null $countryCallingCodeToRegionCodeMap
396
     * @return PhoneNumberUtil instance
397
     */
398
    public static function getInstance(
399
        string $baseFileLocation = self::META_DATA_FILE_PREFIX,
400
        ?array $countryCallingCodeToRegionCodeMap = null,
401
        ?MetadataLoaderInterface $metadataLoader = null,
402
        ?MetadataSourceInterface $metadataSource = null
403
    ): PhoneNumberUtil {
404
        if (static::$instance === null) {
405
            if ($countryCallingCodeToRegionCodeMap === null) {
406
                $countryCallingCodeToRegionCodeMap = CountryCodeToRegionCodeMap::COUNTRY_CODE_TO_REGION_CODE_MAP;
407
            }
408
 
409
            if ($metadataLoader === null) {
410
                $metadataLoader = new DefaultMetadataLoader();
411
            }
412
 
413
            if ($metadataSource === null) {
414
                $metadataSource = new MultiFileMetadataSourceImpl($metadataLoader, $baseFileLocation);
415
            }
416
 
417
            static::$instance = new static($metadataSource, $countryCallingCodeToRegionCodeMap);
418
        }
419
        return static::$instance;
420
    }
421
 
422
    protected function init(): void
423
    {
424
        $supportedRegions = [[]];
425
 
426
        foreach ($this->countryCallingCodeToRegionCodeMap as $countryCode => $regionCodes) {
427
            // We can assume that if the country calling code maps to the non-geo entity region code then
428
            // that's the only region code it maps to.
429
            if (count($regionCodes) === 1 && static::REGION_CODE_FOR_NON_GEO_ENTITY === $regionCodes[0]) {
430
                // This is the subset of all country codes that map to the non-geo entity region code.
431
                $this->countryCodesForNonGeographicalRegion[] = $countryCode;
432
            } else {
433
                // The supported regions set does not include the "001" non-geo entity region code.
434
                $supportedRegions[] = $regionCodes;
435
            }
436
        }
437
 
438
        $this->supportedRegions = array_merge(...$supportedRegions);
439
 
440
        // If the non-geo entity still got added to the set of supported regions it must be because
441
        // there are entries that list the non-geo entity alongside normal regions (which is wrong).
442
        // If we discover this, remove the non-geo entity from the set of supported regions and log.
443
        $idx_region_code_non_geo_entity = array_search(static::REGION_CODE_FOR_NON_GEO_ENTITY, $this->supportedRegions);
444
        if ($idx_region_code_non_geo_entity !== false) {
445
            unset($this->supportedRegions[$idx_region_code_non_geo_entity]);
446
        }
447
        $this->nanpaRegions = $this->countryCallingCodeToRegionCodeMap[static::NANPA_COUNTRY_CODE];
448
    }
449
 
450
    protected static function initExtnPatterns(): void
451
    {
452
        static::$EXTN_PATTERNS_FOR_PARSING = static::createExtnPattern(true);
453
        static::$EXTN_PATTERNS_FOR_MATCHING = static::createExtnPattern(false);
454
    }
455
 
456
    protected static function initRFC3966Patterns(): void
457
    {
458
        static::$RFC3966_PHONE_DIGIT = '(' . static::DIGITS . '|' . static::$RFC3966_VISUAL_SEPARATOR . ')';
459
        static::$RFC3966_GLOBAL_NUMBER_DIGITS = '^\\' . static::PLUS_SIGN . static::$RFC3966_PHONE_DIGIT . '*' . static::DIGITS . static::$RFC3966_PHONE_DIGIT . '*$';
460
 
461
        static::$ALPHANUM = static::VALID_ALPHA . static::DIGITS;
462
        static::$RFC3966_DOMAINLABEL = '[' . static::$ALPHANUM . ']+((\\-)*[' . static::$ALPHANUM . '])*';
463
        static::$RFC3966_TOPLABEL = '[' . static::VALID_ALPHA . ']+((\\-)*[' . static::$ALPHANUM . '])*';
464
        static::$RFC3966_DOMAINNAME = '^(' . static::$RFC3966_DOMAINLABEL . '\\.)*' . static::$RFC3966_TOPLABEL . '\\.?$';
465
    }
466
 
467
    /**
468
     * Helper method for constructing regular expressions for parsing. Creates an expression that
469
     * captures up to maxLength digits.
470
     */
471
    protected static function extnDigits(int $maxLength): string
472
    {
473
        return '(' . self::DIGITS . '{1,' . $maxLength . '})';
474
    }
475
 
476
    /**
477
     * Helper initialiser method to create the regular-expression pattern to match extensions.
478
     * Note that there are currently six capturing groups for the extension itself. If this number is
479
     * changed, MaybeStripExtension needs to be updated.
480
     */
481
    protected static function createExtnPattern(bool $forParsing): string
482
    {
483
        // We cap the maximum length of an extension based on the ambiguity of the way the extension is
484
        // prefixed. As per ITU, the officially allowed length for extensions is actually 40, but we
485
        // don't support this since we haven't seen real examples and this introduces many false
486
        // interpretations as the extension labels are not standardized.
487
        $extLimitAfterExplicitLabel = 20;
488
        $extLimitAfterLikelyLabel = 15;
489
        $extLimitAfterAmbiguousChar = 9;
490
        $extLimitWhenNotSure = 6;
491
 
492
 
493
 
494
        $possibleSeparatorsBetweenNumberAndExtLabel = "[ \xC2\xA0\\t,]*";
495
        // Optional full stop (.) or colon, followed by zero or more spaces/tabs/commas.
496
        $possibleCharsAfterExtLabel = "[:\\.\xEf\xBC\x8E]?[ \xC2\xA0\\t,-]*";
497
        $optionalExtnSuffix = '#?';
498
 
499
        // Here the extension is called out in more explicit way, i.e mentioning it obvious patterns
500
        // like "ext.". Canonical-equivalence doesn't seem to be an option with Android java, so we
501
        // allow two options for representing the accented o - the character itself, and one in the
502
        // unicode decomposed form with the combining acute accent.
503
        $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)";
504
        // One-character symbols that can be used to indicate an extension, and less commonly used
505
        // or more ambiguous extension labels.
506
        $ambiguousExtLabels = "(?:[x\xEF\xBD\x98#\xEF\xBC\x83~\xEF\xBD\x9E]|int|\xEF\xBD\x89\xEF\xBD\x8E\xEF\xBD\x94)";
507
        // When extension is not separated clearly.
508
        $ambiguousSeparator = '[- ]+';
509
 
510
        $rfcExtn = static::RFC3966_EXTN_PREFIX . static::extnDigits($extLimitAfterExplicitLabel);
511
        $explicitExtn = $possibleSeparatorsBetweenNumberAndExtLabel . $explicitExtLabels
512
            . $possibleCharsAfterExtLabel . static::extnDigits($extLimitAfterExplicitLabel)
513
            . $optionalExtnSuffix;
514
        $ambiguousExtn = $possibleSeparatorsBetweenNumberAndExtLabel . $ambiguousExtLabels
515
            . $possibleCharsAfterExtLabel . static::extnDigits($extLimitAfterAmbiguousChar) . $optionalExtnSuffix;
516
        $americanStyleExtnWithSuffix = $ambiguousSeparator . static::extnDigits($extLimitWhenNotSure) . '#';
517
 
518
        // The first regular expression covers RFC 3966 format, where the extension is added using
519
        // ";ext=". The second more generic where extension is mentioned with explicit labels like
520
        // "ext:". In both the above cases we allow more numbers in extension than any other extension
521
        // labels. The third one captures when single character extension labels or less commonly used
522
        // labels are used. In such cases we capture fewer extension digits in order to reduce the
523
        // chance of falsely interpreting two numbers beside each other as a number + extension. The
524
        // fourth one covers the special case of American numbers where the extension is written with a
525
        // hash at the end, such as "- 503#".
526
        $extensionPattern =
527
            $rfcExtn . '|'
528
            . $explicitExtn . '|'
529
            . $ambiguousExtn . '|'
530
            . $americanStyleExtnWithSuffix;
531
        // Additional pattern that is supported when parsing extensions, not when matching.
532
        if ($forParsing) {
533
            // This is same as possibleSeparatorsBetweenNumberAndExtLabel, but not matching comma as
534
            // extension label may have it.
535
            $possibleSeparatorsNumberExtLabelNoComma = "[ \xC2\xA0\\t]*";
536
            // ",," is commonly used for auto dialling the extension when connected. First comma is matched
537
            // through possibleSeparatorsBetweenNumberAndExtLabel, so we do not repeat it here. Semi-colon
538
            // works in Iphone and Android also to pop up a button with the extension number following.
539
            $autoDiallingAndExtLabelsFound = '(?:,{2}|;)';
540
 
541
            $autoDiallingExtn = $possibleSeparatorsNumberExtLabelNoComma
542
                . $autoDiallingAndExtLabelsFound . $possibleCharsAfterExtLabel
543
                . static::extnDigits($extLimitAfterLikelyLabel) . $optionalExtnSuffix;
544
            $onlyCommasExtn = $possibleSeparatorsNumberExtLabelNoComma
545
                . '(?:,)+' . $possibleCharsAfterExtLabel . static::extnDigits($extLimitAfterAmbiguousChar)
546
                . $optionalExtnSuffix;
547
            // Here the first pattern is exclusively for extension autodialling formats which are used
548
            // when dialling and in this case we accept longer extensions. However, the second pattern
549
            // is more liberal on the number of commas that acts as extension labels, so we have a strict
550
            // cap on the number of digits in such extensions.
551
            return $extensionPattern . '|'
552
                . $autoDiallingExtn . '|'
553
                . $onlyCommasExtn;
554
        }
555
        return $extensionPattern;
556
    }
557
 
558
    protected static function initExtnPattern(): void
559
    {
560
        static::$EXTN_PATTERN = '/(?:' . static::$EXTN_PATTERNS_FOR_PARSING . ')$/' . static::REGEX_FLAGS;
561
    }
562
 
563
    protected static function initValidPhoneNumberPatterns(): void
564
    {
565
        static::initExtnPatterns();
566
        static::$MIN_LENGTH_PHONE_NUMBER_PATTERN = '[' . static::DIGITS . ']{' . static::MIN_LENGTH_FOR_NSN . '}';
567
        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 . ']*';
568
        static::$VALID_PHONE_NUMBER_PATTERN = '%^' . static::$MIN_LENGTH_PHONE_NUMBER_PATTERN . '$|^' . static::$VALID_PHONE_NUMBER . '(?:' . static::$EXTN_PATTERNS_FOR_PARSING . ')?$%' . static::REGEX_FLAGS;
569
    }
570
 
571
    /**
572
     * Used for testing purposes only to reset the PhoneNumberUtil singleton to null.
573
     */
574
    public static function resetInstance(): void
575
    {
576
        static::$instance = null;
577
    }
578
 
579
    /**
580
     * Converts all alpha characters in a number to their respective digits on a keypad, but retains
581
     * existing formatting.
582
     */
583
    public static function convertAlphaCharactersInNumber(string $number): string
584
    {
585
        return static::normalizeHelper($number, static::ALPHA_PHONE_MAPPINGS, false);
586
    }
587
 
588
    /**
589
     * Normalizes a string of characters representing a phone number by replacing all characters found
590
     * in the accompanying map with the values therein, and stripping all other characters if
591
     * removeNonMatches is true.
592
     *
593
     * @param string $number a string of characters representing a phone number
594
     * @param array<string,string> $normalizationReplacements a mapping of characters to what they should be replaced by in
595
     * the normalized version of the phone number.
596
     * @param bool $removeNonMatches indicates whether characters that are not able to be replaced.
597
     * should be stripped from the number. If this is false, they will be left unchanged in the number.
598
     * @return string the normalized string version of the phone number.
599
     */
600
    protected static function normalizeHelper(string $number, array $normalizationReplacements, bool $removeNonMatches): string
601
    {
602
        $normalizedNumber = '';
603
        $strLength = mb_strlen($number, 'UTF-8');
604
        for ($i = 0; $i < $strLength; $i++) {
605
            $character = mb_substr($number, $i, 1, 'UTF-8');
606
            if (isset($normalizationReplacements[mb_strtoupper($character, 'UTF-8')])) {
607
                $normalizedNumber .= $normalizationReplacements[mb_strtoupper($character, 'UTF-8')];
608
            } elseif (!$removeNonMatches) {
609
                $normalizedNumber .= $character;
610
            }
611
            // If neither of the above are true, we remove this character.
612
        }
613
        return $normalizedNumber;
614
    }
615
 
616
    /**
617
     * Helper function to check if the national prefix formatting rule has the first group only, i.e.,
618
     * does not start with the national prefix.
619
     */
620
    public static function formattingRuleHasFirstGroupOnly(string $nationalPrefixFormattingRule): bool
621
    {
622
        $firstGroupOnlyPrefixPatternMatcher = new Matcher(
623
            static::FIRST_GROUP_ONLY_PREFIX_PATTERN,
624
            $nationalPrefixFormattingRule
625
        );
626
 
627
        return $nationalPrefixFormattingRule === ''
628
            || $firstGroupOnlyPrefixPatternMatcher->matches();
629
    }
630
 
631
    /**
632
     * Returns all regions the library has metadata for.
633
     *
634
     * @return string[] An unordered array of the two-letter region codes for every geographical region the
635
     *  library supports
636
     */
637
    public function getSupportedRegions(): array
638
    {
639
        return $this->supportedRegions;
640
    }
641
 
642
    /**
643
     * Returns all global network calling codes the library has metadata for.
644
     *
645
     * @return int[] An unordered array of the country calling codes for every non-geographical entity
646
     *  the library supports
647
     */
648
    public function getSupportedGlobalNetworkCallingCodes(): array
649
    {
650
        return $this->countryCodesForNonGeographicalRegion;
651
    }
652
 
653
    /**
654
     * Returns all country calling codes the library has metadata for, covering both non-geographical
655
     * entities (global network calling codes) and those used for geographical entities. This could be
656
     * used to populate a drop-down box of country calling codes for a phone-number widget, for
657
     * instance.
658
     *
659
     * @return int[] An unordered array of the country calling codes for every geographical and
660
     *      non-geographical entity the library supports
661
     */
662
    public function getSupportedCallingCodes(): array
663
    {
664
        return array_keys($this->countryCallingCodeToRegionCodeMap);
665
    }
666
 
667
    /**
668
     * Returns true if there is any possible number data set for a particular PhoneNumberDesc.
669
     */
670
    protected static function descHasPossibleNumberData(PhoneNumberDesc $desc): bool
671
    {
672
        // If this is empty, it means numbers of this type inherit from the "general desc" -> the value
673
        // '-1' means that no numbers exist for this type.
674
        $possibleLength = $desc->getPossibleLength();
675
        return count($possibleLength) !== 1 || $possibleLength[0] !== -1;
676
    }
677
 
678
    /**
679
     * Returns true if there is any data set for a particular PhoneNumberDesc.
680
     */
681
    protected static function descHasData(PhoneNumberDesc $desc): bool
682
    {
683
        // Checking most properties since we don't know what's present, since a custom build may have
684
        // stripped just one of them (e.g. liteBuild strips exampleNumber). We don't bother checking the
685
        // possibleLengthsLocalOnly, since if this is the only thing that's present we don't really
686
        // support the type at all: no type-specific methods will work with only this data.
687
        return $desc->hasExampleNumber()
688
            || static::descHasPossibleNumberData($desc)
689
            || $desc->hasNationalNumberPattern();
690
    }
691
 
692
    /**
693
     * Returns the types we have metadata for based on the PhoneMetadata object passed in.
694
     *
695
     * @return array<int>
696
     */
697
    private function getSupportedTypesForMetadata(PhoneMetadata $metadata): array
698
    {
699
        $types = [];
700
        foreach (array_keys(PhoneNumberType::values()) as $type) {
701
            if ($type === PhoneNumberType::FIXED_LINE_OR_MOBILE || $type === PhoneNumberType::UNKNOWN) {
702
                // Never return FIXED_LINE_OR_MOBILE (it is a convenience type, and represents that a
703
                // particular number type can't be determined) or UNKNOWN (the non-type).
704
                continue;
705
            }
706
 
707
            if (self::descHasData($this->getNumberDescByType($metadata, $type))) {
708
                $types[] = $type;
709
            }
710
        }
711
 
712
        return $types;
713
    }
714
 
715
    /**
716
     * Returns the types for a given region which the library has metadata for. Will not include
717
     * FIXED_LINE_OR_MOBILE (if the numbers in this region could be classified as FIXED_LINE_OR_MOBILE,
718
     * both FIXED_LINE and MOBILE would be present) and UNKNOWN.
719
     *
720
     * No types will be returned for invalid or unknown region codes.
721
     *
722
     * @return array<int> Array of PhoneNumberType's
723
     */
724
    public function getSupportedTypesForRegion(string $regionCode): array
725
    {
726
        $metadata = $this->getMetadataForRegion($regionCode);
727
 
728
        if ($metadata === null) {
729
            return [];
730
        }
731
 
732
        return $this->getSupportedTypesForMetadata($metadata);
733
    }
734
 
735
    /**
736
     * Returns the types for a country-code belonging to a non-geographical entity which the library
737
     * has metadata for. Will not include FIXED_LINE_OR_MOBILE (if numbers for this non-geographical
738
     * entity could be classified as FIXED_LINE_OR_MOBILE, both FIXED_LINE and MOBILE would be
739
     * present) and UNKNOWN.
740
     * @return array<int> Array of PhoneNumberType's
741
     */
742
    public function getSupportedTypesForNonGeoEntity(int $countryCallingCode): array
743
    {
744
        $metadata = $this->getMetadataForNonGeographicalRegion($countryCallingCode);
745
        if ($metadata === null) {
746
            return [];
747
        }
748
 
749
        return $this->getSupportedTypesForMetadata($metadata);
750
    }
751
 
752
    /**
753
     * Gets the length of the geographical area code from the {@code nationalNumber} field of the
754
     * PhoneNumber object passed in, so that clients could use it to split a national significant
755
     * number into geographical area code and subscriber number. It works in such a way that the
756
     * resultant subscriber number should be diallable, at least on some devices. An example of how
757
     * this could be used:
758
     *
759
     * <code>
760
     * $phoneUtil = PhoneNumberUtil::getInstance();
761
     * $number = $phoneUtil->parse("16502530000", "US");
762
     * $nationalSignificantNumber = $phoneUtil->getNationalSignificantNumber($number);
763
     *
764
     * $areaCodeLength = $phoneUtil->getLengthOfGeographicalAreaCode($number);
765
     * if ($areaCodeLength > 0)
766
     * {
767
     *     $areaCode = substr($nationalSignificantNumber, 0,$areaCodeLength);
768
     *     $subscriberNumber = substr($nationalSignificantNumber, $areaCodeLength);
769
     * } else {
770
     *     $areaCode = "";
771
     *     $subscriberNumber = $nationalSignificantNumber;
772
     * }
773
     * </code>
774
     *
775
     * N.B.: area code is a very ambiguous concept, so the I18N team generally recommends against
776
     * using it for most purposes, but recommends using the more general {@code nationalNumber}
777
     * instead. Read the following carefully before deciding to use this method:
778
     * <ul>
779
     *  <li> geographical area codes change over time, and this method honors those changes;
780
     *    therefore, it doesn't guarantee the stability of the result it produces.
781
     *  <li> subscriber numbers may not be diallable from all devices (notably mobile devices, which
782
     *    typically requires the full national_number to be dialled in most regions).
783
     *  <li> most non-geographical numbers have no area codes, including numbers from non-geographical
784
     *    entities
785
     *  <li> some geographical numbers have no area codes.
786
     * </ul>
787
     *
788
     * @param PhoneNumber $number PhoneNumber object for which clients want to know the length of the area code.
789
     * @return int the length of area code of the PhoneNumber object passed in.
790
     */
791
    public function getLengthOfGeographicalAreaCode(PhoneNumber $number): int
792
    {
793
        $metadata = $this->getMetadataForRegion($this->getRegionCodeForNumber($number));
794
        if ($metadata === null) {
795
            return 0;
796
        }
797
 
798
        $countryCallingCode = $number->getCountryCode();
799
 
800
 
801
        // If a country doesn't use a national prefix, and this number doesn't have an Italian leading
802
        // zero, we assume it is a closed dialling plan with no area codes.
803
        // Note:this is our general assumption, but there are exceptions which are tracked in
804
        // COUNTRIES_WITHOUT_NATIONAL_PREFIX_WITH_AREA_CODES.
805
        if (!$metadata->hasNationalPrefix() && !$number->isItalianLeadingZero() && !in_array($countryCallingCode, static::COUNTRIES_WITHOUT_NATIONAL_PREFIX_WITH_AREA_CODES)) {
806
            return 0;
807
        }
808
 
809
        $type = $this->getNumberType($number);
810
 
811
        if ($type === PhoneNumberType::MOBILE
812
            // Note this is a rough heuristic; it doesn't cover Indonesia well, for example, where area
813
            // codes are present for some mobile phones but not for others. We have no better way of
814
            // representing this in the metadata at this point.
815
            && in_array($countryCallingCode, static::GEO_MOBILE_COUNTRIES_WITHOUT_MOBILE_AREA_CODES)
816
        ) {
817
            return 0;
818
        }
819
 
820
        if (!$this->isNumberGeographical($type, $countryCallingCode)) {
821
            return 0;
822
        }
823
 
824
        return $this->getLengthOfNationalDestinationCode($number);
825
    }
826
 
827
    /**
828
     * Returns the metadata for the given region code or {@code null} if the region code is invalid
829
     * or unknown.
830
     */
831
    public function getMetadataForRegion(?string $regionCode): ?PhoneMetadata
832
    {
833
        if (!$this->isValidRegionCode($regionCode)) {
834
            return null;
835
        }
836
 
837
        return $this->metadataSource->getMetadataForRegion($regionCode);
838
    }
839
 
840
    /**
841
     * Helper function to check region code is not unknown or null.
842
     */
843
    protected function isValidRegionCode(?string $regionCode): bool
844
    {
845
        return $regionCode !== null && in_array(strtoupper($regionCode), $this->supportedRegions);
846
    }
847
 
848
    /**
849
     * Returns the region where a phone number is from. This could be used for geocoding at the region
850
     * level. Only guarantees correct results for valid, full numbers (not short-codes, or invalid
851
     * numbers).
852
     *
853
     * @param PhoneNumber $number the phone number whose origin we want to know
854
     * @return null|string  the region where the phone number is from, or null if no region matches this calling
855
     * code
856
     */
857
    public function getRegionCodeForNumber(PhoneNumber $number): ?string
858
    {
859
        $countryCode = $number->getCountryCode();
860
        if (!isset($this->countryCallingCodeToRegionCodeMap[$countryCode])) {
861
            return null;
862
        }
863
        $regions = $this->countryCallingCodeToRegionCodeMap[$countryCode];
864
        if (count($regions) === 1) {
865
            return $regions[0];
866
        }
867
 
868
        return $this->getRegionCodeForNumberFromRegionList($number, $regions);
869
    }
870
 
871
    /**
872
     * Returns the region code for a number from the list of region codes passing in.
873
     *
874
     * @param string[] $regionCodes
875
     */
876
    protected function getRegionCodeForNumberFromRegionList(PhoneNumber $number, array $regionCodes): ?string
877
    {
878
        $nationalNumber = $this->getNationalSignificantNumber($number);
879
        foreach ($regionCodes as $regionCode) {
880
            // If leadingDigits is present, use this. Otherwise, do full validation.
881
            // Metadata cannot be null because the region codes come from the country calling code map.
882
            /** @var PhoneMetadata $metadata */
883
            $metadata = $this->getMetadataForRegion($regionCode);
884
            if ($metadata->hasLeadingDigits()) {
885
                $nbMatches = preg_match(
886
                    '/' . $metadata->getLeadingDigits() . '/',
887
                    $nationalNumber,
888
                    $matches,
889
                    PREG_OFFSET_CAPTURE
890
                );
891
                if ($nbMatches > 0 && $matches[0][1] === 0) {
892
                    return $regionCode;
893
                }
894
            } elseif ($this->getNumberTypeHelper($nationalNumber, $metadata) !== PhoneNumberType::UNKNOWN) {
895
                return $regionCode;
896
            }
897
        }
898
        return null;
899
    }
900
 
901
    /**
902
     * Gets the national significant number of the phone number. Note a national significant number
903
     * doesn't contain a national prefix or any formatting.
904
     *
905
     * @param PhoneNumber $number the phone number for which the national significant number is needed
906
     * @return string the national significant number of the PhoneNumber object passed in
907
     */
908
    public function getNationalSignificantNumber(PhoneNumber $number): string
909
    {
910
        // If leading zero(s) have been set, we prefix this now. Note this is not a national prefix.
911
        $nationalNumber = '';
912
        if ($number->isItalianLeadingZero() && $number->getNumberOfLeadingZeros() > 0) {
913
            $zeros = str_repeat('0', $number->getNumberOfLeadingZeros());
914
            $nationalNumber .= $zeros;
915
        }
916
        $nationalNumber .= $number->getNationalNumber();
917
        return $nationalNumber;
918
    }
919
 
920
    /**
921
     * Returns the type of number passed in i.e Toll free, premium.
922
     *
923
     * @return int PhoneNumberType constant
924
     */
925
    protected function getNumberTypeHelper(string $nationalNumber, PhoneMetadata $metadata): int
926
    {
927
        if (!$this->isNumberMatchingDesc($nationalNumber, $metadata->getGeneralDesc())) {
928
            return PhoneNumberType::UNKNOWN;
929
        }
930
        if ($this->isNumberMatchingDesc($nationalNumber, $metadata->getPremiumRate())) {
931
            return PhoneNumberType::PREMIUM_RATE;
932
        }
933
        if ($this->isNumberMatchingDesc($nationalNumber, $metadata->getTollFree())) {
934
            return PhoneNumberType::TOLL_FREE;
935
        }
936
        if ($this->isNumberMatchingDesc($nationalNumber, $metadata->getSharedCost())) {
937
            return PhoneNumberType::SHARED_COST;
938
        }
939
        if ($this->isNumberMatchingDesc($nationalNumber, $metadata->getVoip())) {
940
            return PhoneNumberType::VOIP;
941
        }
942
        if ($this->isNumberMatchingDesc($nationalNumber, $metadata->getPersonalNumber())) {
943
            return PhoneNumberType::PERSONAL_NUMBER;
944
        }
945
        if ($this->isNumberMatchingDesc($nationalNumber, $metadata->getPager())) {
946
            return PhoneNumberType::PAGER;
947
        }
948
        if ($this->isNumberMatchingDesc($nationalNumber, $metadata->getUan())) {
949
            return PhoneNumberType::UAN;
950
        }
951
        if ($this->isNumberMatchingDesc($nationalNumber, $metadata->getVoicemail())) {
952
            return PhoneNumberType::VOICEMAIL;
953
        }
954
        $isFixedLine = $this->isNumberMatchingDesc($nationalNumber, $metadata->getFixedLine());
955
        if ($isFixedLine) {
956
            if ($metadata->getSameMobileAndFixedLinePattern()) {
957
                return PhoneNumberType::FIXED_LINE_OR_MOBILE;
958
            }
959
 
960
            if ($this->isNumberMatchingDesc($nationalNumber, $metadata->getMobile())) {
961
                return PhoneNumberType::FIXED_LINE_OR_MOBILE;
962
            }
963
            return PhoneNumberType::FIXED_LINE;
964
        }
965
        // Otherwise, test to see if the number is mobile. Only do this if certain that the patterns for
966
        // mobile and fixed line aren't the same.
967
        if (!$metadata->getSameMobileAndFixedLinePattern() &&
968
            $this->isNumberMatchingDesc($nationalNumber, $metadata->getMobile())
969
        ) {
970
            return PhoneNumberType::MOBILE;
971
        }
972
        return PhoneNumberType::UNKNOWN;
973
    }
974
 
975
    public function isNumberMatchingDesc(string $nationalNumber, PhoneNumberDesc $numberDesc): bool
976
    {
977
        // Check if any possible number lengths are present; if so, we use them to avoid checking the
978
        // validation pattern if they don't match. If they are absent, this means they match the general
979
        // description, which we have already checked before checking a specific number type.
980
        $actualLength = mb_strlen($nationalNumber);
981
        $possibleLengths = $numberDesc->getPossibleLength();
982
        if (count($possibleLengths) > 0 && !in_array($actualLength, $possibleLengths)) {
983
            return false;
984
        }
985
 
986
        return $this->matcherAPI->matchNationalNumber($nationalNumber, $numberDesc, false);
987
    }
988
 
989
    /**
990
     * isNumberGeographical(PhoneNumber)
991
     *
992
     * Tests whether a phone number has a geographical association. It checks if the number is
993
     * associated with a certain region in the country to which it belongs. Note that this doesn't
994
     * verify if the number is actually in use.
995
     *
996
     * isNumberGeographical(PhoneNumberType, $countryCallingCode)
997
     *
998
     * Tests whether a phone number has a geographical association, as represented by its type and the
999
     * country it belongs to.
1000
     *
1001
     * This version exists since calculating the phone number type is expensive; if we have already
1002
     * done this, we don't want to do it again.
1003
     *
1004
     * @param PhoneNumber|int $phoneNumberObjOrType A PhoneNumber object, or a PhoneNumberType integer
1005
     * @param int|null $countryCallingCode Used when passing a PhoneNumberType
1006
     */
1007
    public function isNumberGeographical(PhoneNumber|int $phoneNumberObjOrType, ?int $countryCallingCode = null): bool
1008
    {
1009
        if ($phoneNumberObjOrType instanceof PhoneNumber) {
1010
            return $this->isNumberGeographical($this->getNumberType($phoneNumberObjOrType), $phoneNumberObjOrType->getCountryCode());
1011
        }
1012
 
1013
        return $phoneNumberObjOrType === PhoneNumberType::FIXED_LINE
1014
            || $phoneNumberObjOrType === PhoneNumberType::FIXED_LINE_OR_MOBILE
1015
            || (
1016
                in_array($countryCallingCode, static::GEO_MOBILE_COUNTRIES)
1017
                && $phoneNumberObjOrType === PhoneNumberType::MOBILE
1018
            );
1019
    }
1020
 
1021
    /**
1022
     * Gets the type of a valid phone number.
1023
     *
1024
     * @param PhoneNumber $number the number the phone number that we want to know the type
1025
     * @return int PhoneNumberType the type of the phone number, or UNKNOWN if it is invalid
1026
     */
1027
    public function getNumberType(PhoneNumber $number): int
1028
    {
1029
        $regionCode = $this->getRegionCodeForNumber($number);
1030
        if ($regionCode === null) {
1031
            return PhoneNumberType::UNKNOWN;
1032
        }
1033
        $metadata = $this->getMetadataForRegionOrCallingCode($number->getCountryCode(), $regionCode);
1034
        if ($metadata === null) {
1035
            return PhoneNumberType::UNKNOWN;
1036
        }
1037
        $nationalSignificantNumber = $this->getNationalSignificantNumber($number);
1038
        return $this->getNumberTypeHelper($nationalSignificantNumber, $metadata);
1039
    }
1040
 
1041
    protected function getMetadataForRegionOrCallingCode(int $countryCallingCode, string $regionCode): ?PhoneMetadata
1042
    {
1043
        return static::REGION_CODE_FOR_NON_GEO_ENTITY === $regionCode ?
1044
            $this->getMetadataForNonGeographicalRegion($countryCallingCode) : $this->getMetadataForRegion($regionCode);
1045
    }
1046
 
1047
    public function getMetadataForNonGeographicalRegion(int $countryCallingCode): ?PhoneMetadata
1048
    {
1049
        if (!isset($this->countryCallingCodeToRegionCodeMap[$countryCallingCode])) {
1050
            return null;
1051
        }
1052
        return $this->metadataSource->getMetadataForNonGeographicalRegion($countryCallingCode);
1053
    }
1054
 
1055
    /**
1056
     * Gets the length of the national destination code (NDC) from the PhoneNumber object passed in,
1057
     * so that clients could use it to split a national significant number into NDC and subscriber
1058
     * number. The NDC of a phone number is normally the first group of digit(s) right after the
1059
     * country calling code when the number is formatted in the international format, if there is a
1060
     * subscriber number part that follows.
1061
     *
1062
     * follows.
1063
     *
1064
     * N.B.: similar to an area code, not all numbers have an NDC!
1065
     *
1066
     * An example of how this could be used:
1067
     *
1068
     * <code>
1069
     * $phoneUtil = PhoneNumberUtil::getInstance();
1070
     * $number = $phoneUtil->parse("18002530000", "US");
1071
     * $nationalSignificantNumber = $phoneUtil->getNationalSignificantNumber($number);
1072
     *
1073
     * $nationalDestinationCodeLength = $phoneUtil->getLengthOfNationalDestinationCode($number);
1074
     * if ($nationalDestinationCodeLength > 0) {
1075
     *     $nationalDestinationCode = substr($nationalSignificantNumber, 0, $nationalDestinationCodeLength);
1076
     *     $subscriberNumber = substr($nationalSignificantNumber, $nationalDestinationCodeLength);
1077
     * } else {
1078
     *     $nationalDestinationCode = "";
1079
     *     $subscriberNumber = $nationalSignificantNumber;
1080
     * }
1081
     * </code>
1082
     *
1083
     * Refer to the unit tests to see the difference between this function and
1084
     * {@link #getLengthOfGeographicalAreaCode}.
1085
     *
1086
     * @param PhoneNumber $number the PhoneNumber object for which clients want to know the length of the NDC.
1087
     * @return int the length of NDC of the PhoneNumber object passed in, which could be zero
1088
     */
1089
    public function getLengthOfNationalDestinationCode(PhoneNumber $number): int
1090
    {
1091
        if ($number->hasExtension()) {
1092
            // We don't want to alter the proto given to us, but we don't want to include the extension
1093
            // when we format it, so we copy it and clear the extension here.
1094
            $copiedProto = new PhoneNumber();
1095
            $copiedProto->mergeFrom($number);
1096
            $copiedProto->clearExtension();
1097
        } else {
1098
            $copiedProto = clone $number;
1099
        }
1100
 
1101
        $nationalSignificantNumber = $this->format($copiedProto, PhoneNumberFormat::INTERNATIONAL);
1102
 
1103
        $numberGroups = preg_split('/' . static::NON_DIGITS_PATTERN . '/', $nationalSignificantNumber);
1104
 
1105
        // The pattern will start with "+COUNTRY_CODE " so the first group will always be the empty
1106
        // string (before the + symbol) and the second group will be the country calling code. The third
1107
        // group will be area code if it is not the last group.
1108
        if ($numberGroups === false || count($numberGroups) <= 3) {
1109
            return 0;
1110
        }
1111
 
1112
        if ($this->getNumberType($number) === PhoneNumberType::MOBILE) {
1113
            // For example Argentinian mobile numbers, when formatted in the international format, are in
1114
            // the form of +54 9 NDC XXXX.... As a result, we take the length of the third group (NDC) and
1115
            // add the length of the second group (which is the mobile token), which also forms part of
1116
            // the national significant number. This assumes that the mobile token is always formatted
1117
            // separately from the rest of the phone number.
1118
 
1119
            $mobileToken = static::getCountryMobileToken($number->getCountryCode());
1120
            if ($mobileToken !== '') {
1121
                return mb_strlen($numberGroups[2]) + mb_strlen($numberGroups[3]);
1122
            }
1123
        }
1124
        return mb_strlen($numberGroups[2]);
1125
    }
1126
 
1127
    /**
1128
     * Formats a phone number in the specified format using default rules. Note that this does not
1129
     * promise to produce a phone number that the user can dial from where they are - although we do
1130
     * format in either 'national' or 'international' format depending on what the client asks for, we
1131
     * do not currently support a more abbreviated format, such as for users in the same "area" who
1132
     * could potentially dial the number without area code. Note that if the phone number has a
1133
     * country calling code of 0 or an otherwise invalid country calling code, we cannot work out
1134
     * which formatting rules to apply so we return the national significant number with no formatting
1135
     * applied.
1136
     *
1137
     * @param PhoneNumber $number the phone number to be formatted
1138
     * @param int $numberFormat the PhoneNumberFormat the phone number should be formatted into
1139
     * @return string the formatted phone number
1140
     */
1141
    public function format(PhoneNumber $number, int $numberFormat): string
1142
    {
1143
        if ($number->getNationalNumber() === '0' && $number->hasRawInput()) {
1144
            // Unparseable numbers that kept their raw input just use that.
1145
            // This is the only case where a number can be formatted as E164 without a
1146
            // leading '+' symbol (but the original number wasn't parseable anyway).
1147
            // TODO: Consider removing the 'if' above so that unparseable
1148
            // strings without raw input format to the empty string instead of "+00"
1149
            $rawInput = $number->getRawInput();
1150
            if ($rawInput !== '') {
1151
                return $rawInput;
1152
            }
1153
        }
1154
 
1155
        $formattedNumber = '';
1156
        $countryCallingCode = $number->getCountryCode();
1157
        $nationalSignificantNumber = $this->getNationalSignificantNumber($number);
1158
 
1159
        if ($numberFormat === PhoneNumberFormat::E164) {
1160
            // Early exit for E164 case (even if the country calling code is invalid) since no formatting
1161
            // of the national number needs to be applied. Extensions are not formatted.
1162
            $formattedNumber .= $nationalSignificantNumber;
1163
            $this->prefixNumberWithCountryCallingCode($countryCallingCode, PhoneNumberFormat::E164, $formattedNumber);
1164
            return $formattedNumber;
1165
        }
1166
 
1167
        if (!$this->hasValidCountryCallingCode($countryCallingCode)) {
1168
            $formattedNumber .= $nationalSignificantNumber;
1169
            return $formattedNumber;
1170
        }
1171
 
1172
        // Note getRegionCodeForCountryCode() is used because formatting information for regions which
1173
        // share a country calling code is contained by only one region for performance reasons. For
1174
        // example, for NANPA regions it will be contained in the metadata for US.
1175
        $regionCode = $this->getRegionCodeForCountryCode($countryCallingCode);
1176
        // Metadata cannot be null because the country calling code is valid (which means that the
1177
        // region code cannot be ZZ and must be one of our supported region codes).
1178
        /** @var PhoneMetadata $metadata */
1179
        $metadata = $this->getMetadataForRegionOrCallingCode($countryCallingCode, $regionCode);
1180
        $formattedNumber .= $this->formatNsn($nationalSignificantNumber, $metadata, $numberFormat);
1181
        $this->maybeAppendFormattedExtension($number, $metadata, $numberFormat, $formattedNumber);
1182
        $this->prefixNumberWithCountryCallingCode($countryCallingCode, $numberFormat, $formattedNumber);
1183
        return $formattedNumber;
1184
    }
1185
 
1186
    /**
1187
     * A helper function that is used by format and formatByPattern.
1188
     * @param int $numberFormat PhoneNumberFormat
1189
     */
1190
    protected function prefixNumberWithCountryCallingCode(int $countryCallingCode, int $numberFormat, string &$formattedNumber): void
1191
    {
1192
        switch ($numberFormat) {
1193
            case PhoneNumberFormat::E164:
1194
                $formattedNumber = static::PLUS_SIGN . $countryCallingCode . $formattedNumber;
1195
                return;
1196
            case PhoneNumberFormat::INTERNATIONAL:
1197
                $formattedNumber = static::PLUS_SIGN . $countryCallingCode . ' ' . $formattedNumber;
1198
                return;
1199
            case PhoneNumberFormat::RFC3966:
1200
                $formattedNumber = static::RFC3966_PREFIX . static::PLUS_SIGN . $countryCallingCode . '-' . $formattedNumber;
1201
                return;
1202
        }
1203
    }
1204
 
1205
    /**
1206
     * Helper function to check the country calling code is valid.
1207
     */
1208
    protected function hasValidCountryCallingCode(int $countryCallingCode): bool
1209
    {
1210
        return isset($this->countryCallingCodeToRegionCodeMap[$countryCallingCode]);
1211
    }
1212
 
1213
    /**
1214
     * Returns the region code that matches the specific country calling code. In the case of no
1215
     * region code being found, ZZ will be returned. In the case of multiple regions, the one
1216
     * designated in the metadata as the "main" region for this calling code will be returned. If the
1217
     * countryCallingCode entered is valid but doesn't match a specific region (such as in the case of
1218
     * non-geographical calling codes like 800) the value "001" will be returned (corresponding to
1219
     * the value for World in the UN M.49 schema).
1220
     */
1221
    public function getRegionCodeForCountryCode(int $countryCallingCode): string
1222
    {
1223
        $regionCodes = $this->countryCallingCodeToRegionCodeMap[$countryCallingCode] ?? null;
1224
        return $regionCodes === null ? static::UNKNOWN_REGION : $regionCodes[0];
1225
    }
1226
 
1227
    /**
1228
     * Note in some regions, the national number can be written in two completely different ways
1229
     * depending on whether it forms part of the NATIONAL format or INTERNATIONAL format. The
1230
     * numberFormat parameter here is used to specify which format to use for those cases. If a
1231
     * carrierCode is specified, this will be inserted into the formatted string to replace $CC.
1232
     * @param int $numberFormat PhoneNumberFormat
1233
     */
1234
    protected function formatNsn(string $number, PhoneMetadata $metadata, int $numberFormat, ?string $carrierCode = null): string
1235
    {
1236
        $intlNumberFormats = $metadata->intlNumberFormats();
1237
        // When the intlNumberFormats exists, we use that to format national number for the
1238
        // INTERNATIONAL format instead of using the numberDesc.numberFormats.
1239
        $availableFormats = (empty($intlNumberFormats) || $numberFormat === PhoneNumberFormat::NATIONAL)
1240
            ? $metadata->numberFormats()
1241
            : $metadata->intlNumberFormats();
1242
        $formattingPattern = $this->chooseFormattingPatternForNumber($availableFormats, $number);
1243
        return ($formattingPattern === null)
1244
            ? $number
1245
            : $this->formatNsnUsingPattern($number, $formattingPattern, $numberFormat, $carrierCode);
1246
    }
1247
 
1248
    /**
1249
     * @param NumberFormat[] $availableFormats
1250
     */
1251
    public function chooseFormattingPatternForNumber(array $availableFormats, string $nationalNumber): ?NumberFormat
1252
    {
1253
        foreach ($availableFormats as $numFormat) {
1254
            $leadingDigitsPatternMatcher = null;
1255
            $size = $numFormat->leadingDigitsPatternSize();
1256
            // We always use the last leading_digits_pattern, as it is the most detailed.
1257
            if ($size > 0) {
1258
                $leadingDigitsPatternMatcher = new Matcher(
1259
                    $numFormat->getLeadingDigitsPattern($size - 1),
1260
                    $nationalNumber
1261
                );
1262
            }
1263
            if ($size === 0 || $leadingDigitsPatternMatcher->lookingAt()) {
1264
                $m = new Matcher($numFormat->getPattern(), $nationalNumber);
1265
                if ($m->matches() > 0) {
1266
                    return $numFormat;
1267
                }
1268
            }
1269
        }
1270
        return null;
1271
    }
1272
 
1273
    /**
1274
     * Note that carrierCode is optional - if null or an empty string, no carrier code replacement
1275
     * will take place.
1276
     * @param int $numberFormat PhoneNumberFormat
1277
     */
1278
    public function formatNsnUsingPattern(
1279
        string $nationalNumber,
1280
        NumberFormat $formattingPattern,
1281
        int $numberFormat,
1282
        ?string $carrierCode = null
1283
    ): string {
1284
        $numberFormatRule = $formattingPattern->getFormat();
1285
        $m = new Matcher($formattingPattern->getPattern(), $nationalNumber);
1286
        if ($numberFormat === PhoneNumberFormat::NATIONAL &&
1287
            $carrierCode !== null && $carrierCode !== '' &&
1288
            $formattingPattern->getDomesticCarrierCodeFormattingRule() !== ''
1289
        ) {
1290
            // Replace the $CC in the formatting rule with the desired carrier code.
1291
            $carrierCodeFormattingRule = $formattingPattern->getDomesticCarrierCodeFormattingRule();
1292
            $carrierCodeFormattingRule = str_replace(static::CC_STRING, $carrierCode, $carrierCodeFormattingRule);
1293
            // Now replace the $FG in the formatting rule with the first group and the carrier code
1294
            // combined in the appropriate way.
1295
            $firstGroupMatcher = new Matcher(static::FIRST_GROUP_PATTERN, $numberFormatRule);
1296
            $numberFormatRule = $firstGroupMatcher->replaceFirst($carrierCodeFormattingRule);
1297
            $formattedNationalNumber = $m->replaceAll($numberFormatRule);
1298
        } else {
1299
            // Use the national prefix formatting rule instead.
1300
            $nationalPrefixFormattingRule = $formattingPattern->getNationalPrefixFormattingRule();
1301
            if ($numberFormat === PhoneNumberFormat::NATIONAL &&
1302
                $nationalPrefixFormattingRule !== ''
1303
            ) {
1304
                $firstGroupMatcher = new Matcher(static::FIRST_GROUP_PATTERN, $numberFormatRule);
1305
                $formattedNationalNumber = $m->replaceAll(
1306
                    $firstGroupMatcher->replaceFirst($nationalPrefixFormattingRule)
1307
                );
1308
            } else {
1309
                $formattedNationalNumber = $m->replaceAll($numberFormatRule);
1310
            }
1311
        }
1312
        if ($numberFormat === PhoneNumberFormat::RFC3966) {
1313
            // Strip any leading punctuation.
1314
            $matcher = new Matcher(static::SEPARATOR_PATTERN, $formattedNationalNumber);
1315
            if ($matcher->lookingAt()) {
1316
                $formattedNationalNumber = $matcher->replaceFirst('');
1317
            }
1318
            // Replace the rest with a dash between each number group.
1319
            $formattedNationalNumber = $matcher->reset($formattedNationalNumber)->replaceAll('-');
1320
        }
1321
        return $formattedNationalNumber;
1322
    }
1323
 
1324
    /**
1325
     * Appends the formatted extension of a phone number to formattedNumber, if the phone number had
1326
     * an extension specified.
1327
     *
1328
     * @param int $numberFormat PhoneNumberFormat
1329
     */
1330
    protected function maybeAppendFormattedExtension(PhoneNumber $number, ?PhoneMetadata $metadata, int $numberFormat, string &$formattedNumber): void
1331
    {
1332
        if ($number->hasExtension() && $number->getExtension() !== '') {
1333
            if ($numberFormat === PhoneNumberFormat::RFC3966) {
1334
                $formattedNumber .= static::RFC3966_EXTN_PREFIX . $number->getExtension();
1335
            } elseif ($metadata !== null && $metadata->hasPreferredExtnPrefix()) {
1336
                $formattedNumber .= $metadata->getPreferredExtnPrefix() . $number->getExtension();
1337
            } else {
1338
                $formattedNumber .= static::DEFAULT_EXTN_PREFIX . $number->getExtension();
1339
            }
1340
        }
1341
    }
1342
 
1343
    /**
1344
     * Returns the mobile token for the provided country calling code if it has one, otherwise
1345
     * returns an empty string. A mobile token is a number inserted before the area code when dialing
1346
     * a mobile number from that country from abroad.
1347
     *
1348
     * @param int $countryCallingCode the country calling code for which we want the mobile token
1349
     * @return string the mobile token, as a string, for the given country calling code
1350
     */
1351
    public static function getCountryMobileToken(int $countryCallingCode): string
1352
    {
1353
        return static::MOBILE_TOKEN_MAPPINGS[$countryCallingCode] ?? '';
1354
    }
1355
 
1356
    /**
1357
     * Checks if the number is a valid vanity (alpha) number such as 800 MICROSOFT. A valid vanity
1358
     * number will start with at least 3 digits and will have three or more alpha characters. This
1359
     * does not do region-specific checks - to work out if this number is actually valid for a region,
1360
     * it should be parsed and methods such as {@link #isPossibleNumberWithReason} and
1361
     * {@link #isValidNumber} should be used.
1362
     *
1363
     * @param string $number the number that needs to be checked
1364
     * @return bool true if the number is a valid vanity number
1365
     */
1366
    public function isAlphaNumber(string $number): bool
1367
    {
1368
        if (!static::isViablePhoneNumber($number)) {
1369
            // Number is too short, or doesn't match the basic phone number pattern.
1370
            return false;
1371
        }
1372
        $this->maybeStripExtension($number);
1373
        return preg_match('/' . static::VALID_ALPHA_PHONE_PATTERN . '/' . static::REGEX_FLAGS, $number) === 1;
1374
    }
1375
 
1376
    /**
1377
     * Checks to see if the string of characters could possibly be a phone number at all. At the
1378
     * moment, checks to see that the string begins with at least 2 digits, ignoring any punctuation
1379
     * commonly found in phone numbers.
1380
     * This method does not require the number to be normalized in advance - but does assume that
1381
     * leading non-number symbols have been removed, such as by the method extractPossibleNumber.
1382
     *
1383
     * @param string $number to be checked for viability as a phone number
1384
     * @return boolean true if the number could be a phone number of some sort, otherwise false
1385
     */
1386
    public static function isViablePhoneNumber(string $number): bool
1387
    {
1388
        if (!isset(static::$VALID_PHONE_NUMBER_PATTERN)) {
1389
            static::initValidPhoneNumberPatterns();
1390
        }
1391
 
1392
        if (mb_strlen($number) < static::MIN_LENGTH_FOR_NSN) {
1393
            return false;
1394
        }
1395
 
1396
        $validPhoneNumberPattern = static::getValidPhoneNumberPattern();
1397
 
1398
        $m = preg_match($validPhoneNumberPattern, $number);
1399
        return $m > 0;
1400
    }
1401
 
1402
    /**
1403
     * We append optionally the extension pattern to the end here, as a valid phone number may
1404
     * have an extension prefix appended, followed by 1 or more digits.
1405
     */
1406
    protected static function getValidPhoneNumberPattern(): string
1407
    {
1408
        return static::$VALID_PHONE_NUMBER_PATTERN;
1409
    }
1410
 
1411
    /**
1412
     * Strips any extension (as in, the part of the number dialled after the call is connected,
1413
     * usually indicated with extn, ext, x or similar) from the end of the number, and returns it.
1414
     *
1415
     * @param string $number the non-normalized telephone number that we wish to strip the extension from
1416
     * @return string the phone extension
1417
     */
1418
    protected function maybeStripExtension(string &$number): string
1419
    {
1420
        $matches = [];
1421
        $find = preg_match(static::$EXTN_PATTERN, $number, $matches, PREG_OFFSET_CAPTURE);
1422
        // If we find a potential extension, and the number preceding this is a viable number, we assume
1423
        // it is an extension.
1424
        if ($find > 0 && static::isViablePhoneNumber(substr($number, 0, $matches[0][1]))) {
1425
            // The numbers are captured into groups in the regular expression.
1426
 
1427
            for ($i = 1, $length = count($matches); $i <= $length; $i++) {
1428
                if ($matches[$i][0] !== '') {
1429
                    // We go through the capturing groups until we find one that captured some digits. If none
1430
                    // did, then we will return the empty string.
1431
                    $extension = $matches[$i][0];
1432
                    $number = substr($number, 0, $matches[0][1]);
1433
                    return $extension;
1434
                }
1435
            }
1436
        }
1437
        return '';
1438
    }
1439
 
1440
    /**
1441
     * Parses a string and returns it in proto buffer format. This method differs from {@link #parse}
1442
     * in that it always populates the raw_input field of the protocol buffer with numberToParse as
1443
     * well as the country_code_source field.
1444
     *
1445
     * @param string $numberToParse number that we are attempting to parse. This can contain formatting
1446
     *                                  such as +, ( and -, as well as a phone number extension. It can also
1447
     *                                  be provided in RFC3966 format.
1448
     * @param string|null $defaultRegion region that we are expecting the number to be from. This is only used
1449
     *                                  if the number being parsed is not written in international format.
1450
     *                                  The country calling code for the number in this case would be stored
1451
     *                                  as that of the default region supplied.
1452
     * @return PhoneNumber              a phone number proto buffer filled with the parsed number
1453
     */
1454
    public function parseAndKeepRawInput(string $numberToParse, ?string $defaultRegion, ?PhoneNumber $phoneNumber = null): PhoneNumber
1455
    {
1456
        if ($phoneNumber === null) {
1457
            $phoneNumber = new PhoneNumber();
1458
        }
1459
        $this->parseHelper($numberToParse, $defaultRegion, true, true, $phoneNumber);
1460
        return $phoneNumber;
1461
    }
1462
 
1463
    /**
1464
     * A helper function to set the values related to leading zeros in a PhoneNumber.
1465
     */
1466
    public static function setItalianLeadingZerosForPhoneNumber(string $nationalNumber, PhoneNumber $phoneNumber): void
1467
    {
1468
        if (strlen($nationalNumber) > 1 && str_starts_with($nationalNumber, '0')) {
1469
            $phoneNumber->setItalianLeadingZero(true);
1470
            $numberOfLeadingZeros = 1;
1471
            // Note that if the national number is all "0"s, the last "0" is not counted as a leading
1472
            // zero.
1473
            while ($numberOfLeadingZeros < (strlen($nationalNumber) - 1) &&
1474
                substr($nationalNumber, $numberOfLeadingZeros, 1) === '0') {
1475
                $numberOfLeadingZeros++;
1476
            }
1477
 
1478
            if ($numberOfLeadingZeros !== 1) {
1479
                $phoneNumber->setNumberOfLeadingZeros($numberOfLeadingZeros);
1480
            }
1481
        }
1482
    }
1483
 
1484
    /**
1485
     * Parses a string and fills up the phoneNumber. This method is the same as the public
1486
     * parse() method, with the exception that it allows the default region to be null, for use by
1487
     * isNumberMatch(). checkRegion should be set to false if it is permitted for the default region
1488
     * to be null or unknown ("ZZ").
1489
     * @throws NumberParseException
1490
     */
1491
    protected function parseHelper(string $numberToParse, ?string $defaultRegion, bool $keepRawInput, bool $checkRegion, PhoneNumber $phoneNumber): void
1492
    {
1493
        $numberToParse = trim($numberToParse);
1494
 
1495
        if (mb_strlen($numberToParse) > static::MAX_INPUT_STRING_LENGTH) {
1496
            throw new NumberParseException(
1497
                NumberParseException::TOO_LONG,
1498
                'The string supplied was too long to parse.'
1499
            );
1500
        }
1501
 
1502
        $nationalNumber = '';
1503
        $this->buildNationalNumberForParsing($numberToParse, $nationalNumber);
1504
 
1505
        if (!static::isViablePhoneNumber($nationalNumber)) {
1506
            throw new NumberParseException(
1507
                NumberParseException::NOT_A_NUMBER,
1508
                'The string supplied did not seem to be a phone number.'
1509
            );
1510
        }
1511
 
1512
        // Check the region supplied is valid, or that the extracted number starts with some sort of +
1513
        // sign so the number's region can be determined.
1514
        if ($checkRegion && !$this->checkRegionForParsing($nationalNumber, $defaultRegion)) {
1515
            throw new NumberParseException(
1516
                NumberParseException::INVALID_COUNTRY_CODE,
1517
                'Missing or invalid default region.'
1518
            );
1519
        }
1520
 
1521
        if ($keepRawInput) {
1522
            $phoneNumber->setRawInput($numberToParse);
1523
        }
1524
        // Attempt to parse extension first, since it doesn't require region-specific data and we want
1525
        // to have the non-normalised number here.
1526
        $extension = $this->maybeStripExtension($nationalNumber);
1527
        if ($extension !== '') {
1528
            $phoneNumber->setExtension($extension);
1529
        }
1530
 
1531
        $regionMetadata = $this->getMetadataForRegion($defaultRegion);
1532
        // Check to see if the number is given in international format so we know whether this number is
1533
        // from the default region or not.
1534
        $normalizedNationalNumber = '';
1535
        try {
1536
            // TODO: This method should really just take in the string buffer that has already
1537
            // been created, and just remove the prefix, rather than taking in a string and then
1538
            // outputting a string buffer.
1539
            $countryCode = $this->maybeExtractCountryCode(
1540
                $nationalNumber,
1541
                $regionMetadata,
1542
                $normalizedNationalNumber,
1543
                $keepRawInput,
1544
                $phoneNumber
1545
            );
1546
        } catch (NumberParseException $e) {
1547
            $matcher = new Matcher(static::PLUS_CHARS_PATTERN, $nationalNumber);
1548
            if ($e->getErrorType() === NumberParseException::INVALID_COUNTRY_CODE && $matcher->lookingAt()) {
1549
                // Strip the plus-char, and try again.
1550
                $countryCode = $this->maybeExtractCountryCode(
1551
                    substr($nationalNumber, $matcher->end()),
1552
                    $regionMetadata,
1553
                    $normalizedNationalNumber,
1554
                    $keepRawInput,
1555
                    $phoneNumber
1556
                );
1557
                if ($countryCode === 0) {
1558
                    throw new NumberParseException(
1559
                        NumberParseException::INVALID_COUNTRY_CODE,
1560
                        'Could not interpret numbers after plus-sign.'
1561
                    );
1562
                }
1563
            } else {
1564
                throw new NumberParseException($e->getErrorType(), $e->getMessage(), $e);
1565
            }
1566
        }
1567
        if ($countryCode !== 0) {
1568
            $phoneNumberRegion = $this->getRegionCodeForCountryCode($countryCode);
1569
            if ($phoneNumberRegion !== $defaultRegion) {
1570
                // Metadata cannot be null because the country calling code is valid.
1571
                $regionMetadata = $this->getMetadataForRegionOrCallingCode($countryCode, $phoneNumberRegion);
1572
            }
1573
        } else {
1574
            // If no extracted country calling code, use the region supplied instead. The national number
1575
            // is just the normalized version of the number we were given to parse.
1576
 
1577
            $normalizedNationalNumber .= static::normalize($nationalNumber);
1578
            if ($defaultRegion !== null) {
1579
                $countryCode = $regionMetadata->getCountryCode();
1580
                $phoneNumber->setCountryCode($countryCode);
1581
            } elseif ($keepRawInput) {
1582
                $phoneNumber->clearCountryCodeSource();
1583
            }
1584
        }
1585
        if (mb_strlen($normalizedNationalNumber) < static::MIN_LENGTH_FOR_NSN) {
1586
            throw new NumberParseException(
1587
                NumberParseException::TOO_SHORT_NSN,
1588
                'The string supplied is too short to be a phone number.'
1589
            );
1590
        }
1591
        if ($regionMetadata !== null) {
1592
            $carrierCode = '';
1593
            $potentialNationalNumber = $normalizedNationalNumber;
1594
            $this->maybeStripNationalPrefixAndCarrierCode($potentialNationalNumber, $regionMetadata, $carrierCode);
1595
            // We require that the NSN remaining after stripping the national prefix and carrier code be
1596
            // long enough to be a possible length for the region. Otherwise, we don't do the stripping,
1597
            // since the original number could be a valid short number.
1598
            $validationResult = $this->testNumberLength($potentialNationalNumber, $regionMetadata);
1599
            if ($validationResult !== ValidationResult::TOO_SHORT
1600
                && $validationResult !== ValidationResult::IS_POSSIBLE_LOCAL_ONLY
1601
                && $validationResult !== ValidationResult::INVALID_LENGTH) {
1602
                $normalizedNationalNumber = $potentialNationalNumber;
1603
                if ($keepRawInput && $carrierCode !== '') {
1604
                    $phoneNumber->setPreferredDomesticCarrierCode($carrierCode);
1605
                }
1606
            }
1607
        }
1608
        $lengthOfNationalNumber = mb_strlen($normalizedNationalNumber);
1609
        if ($lengthOfNationalNumber < static::MIN_LENGTH_FOR_NSN) {
1610
            throw new NumberParseException(
1611
                NumberParseException::TOO_SHORT_NSN,
1612
                'The string supplied is too short to be a phone number.'
1613
            );
1614
        }
1615
        if ($lengthOfNationalNumber > static::MAX_LENGTH_FOR_NSN) {
1616
            throw new NumberParseException(
1617
                NumberParseException::TOO_LONG,
1618
                'The string supplied is too long to be a phone number.'
1619
            );
1620
        }
1621
        static::setItalianLeadingZerosForPhoneNumber($normalizedNationalNumber, $phoneNumber);
1622
 
1623
        /*
1624
         * We have to store the National Number as a string instead of a "long" as Google do
1625
         *
1626
         * Since PHP doesn't always support 64 bit INTs, this was a float, but that had issues
1627
         * with long numbers.
1628
         *
1629
         * We have to remove the leading zeroes ourself though
1630
         */
1631
        if ((int) $normalizedNationalNumber === 0) {
1632
            $normalizedNationalNumber = '0';
1633
        } else {
1634
            $normalizedNationalNumber = ltrim($normalizedNationalNumber, '0');
1635
        }
1636
 
1637
        $phoneNumber->setNationalNumber($normalizedNationalNumber);
1638
    }
1639
 
1640
    /**
1641
     * Extracts the value of the phone-context parameter of numberToExtractFrom where the index of
1642
     * ";phone-context=" is the parameter indexOfPhoneContext, following the syntax defined in
1643
     * RFC3966.
1644
     * @return string|null the extracted string (possibly empty), or null if no phone-context parameter is found.
1645
     */
1646
    protected function extractPhoneContext(string $numberToExtractFrom, int|false $indexOfPhoneContext): ?string
1647
    {
1648
        // If no phone-context parameter is present
1649
        if ($indexOfPhoneContext === false) {
1650
            return null;
1651
        }
1652
 
1653
        $phoneContextStart = $indexOfPhoneContext + strlen(static::RFC3966_PHONE_CONTEXT);
1654
        // If phone-context parameter is empty
1655
        if ($phoneContextStart >= mb_strlen($numberToExtractFrom)) {
1656
            return '';
1657
        }
1658
 
1659
        $phoneContextEnd = strpos($numberToExtractFrom, ';', $phoneContextStart);
1660
        // If phone-context is not the last parameter
1661
        if ($phoneContextEnd !== false) {
1662
            return substr($numberToExtractFrom, $phoneContextStart, $phoneContextEnd - $phoneContextStart);
1663
        }
1664
 
1665
        return substr($numberToExtractFrom, $phoneContextStart);
1666
    }
1667
 
1668
    /**
1669
     * Returns whether the value of phoneContext follows the syntax defined in RFC3966.
1670
     */
1671
    protected function isPhoneContextValid(?string $phoneContext): bool
1672
    {
1673
        if ($phoneContext === null) {
1674
            return true;
1675
        }
1676
 
1677
        if ($phoneContext === '') {
1678
            return false;
1679
        }
1680
 
1681
        $numberDigitsPattern = '/' . static::$RFC3966_GLOBAL_NUMBER_DIGITS . '/' . static::REGEX_FLAGS;
1682
        $domainNamePattern = '/' . static::$RFC3966_DOMAINNAME . '/' . static::REGEX_FLAGS;
1683
 
1684
        // Does phone-context value match pattern of global-number-digits or domainname
1685
        return preg_match($numberDigitsPattern, $phoneContext) || preg_match($domainNamePattern, $phoneContext);
1686
    }
1687
 
1688
    /**
1689
     * Returns a new phone number containing only the fields needed to uniquely identify a phone
1690
     * number, rather than any fields that capture the context in which  the phone number was created.
1691
     * These fields correspond to those set in parse() rather than parseAndKeepRawInput()
1692
     */
1693
    protected static function copyCoreFieldsOnly(PhoneNumber $phoneNumberIn): PhoneNumber
1694
    {
1695
        $phoneNumber = new PhoneNumber();
1696
        $phoneNumber->setCountryCode($phoneNumberIn->getCountryCode());
1697
        $phoneNumber->setNationalNumber($phoneNumberIn->getNationalNumber());
1698
        if ($phoneNumberIn->hasExtension() && $phoneNumberIn->getExtension() !== '') {
1699
            $phoneNumber->setExtension($phoneNumberIn->getExtension());
1700
        }
1701
        if ($phoneNumberIn->isItalianLeadingZero()) {
1702
            $phoneNumber->setItalianLeadingZero(true);
1703
            // This field is only relevant if there are leading zeros at all.
1704
            $phoneNumber->setNumberOfLeadingZeros($phoneNumberIn->getNumberOfLeadingZeros());
1705
        }
1706
        return $phoneNumber;
1707
    }
1708
 
1709
    /**
1710
     * Converts numberToParse to a form that we can parse and write it to nationalNumber if it is
1711
     * written in RFC3966; otherwise extract a possible number out of it and write to nationalNumber.
1712
     * @throws NumberParseException
1713
     */
1714
    protected function buildNationalNumberForParsing(string $numberToParse, string &$nationalNumber): void
1715
    {
1716
        $indexOfPhoneContext = strpos($numberToParse, static::RFC3966_PHONE_CONTEXT);
1717
        $phoneContext = $this->extractPhoneContext($numberToParse, $indexOfPhoneContext);
1718
 
1719
        if (!$this->isPhoneContextValid($phoneContext)) {
1720
            throw new NumberParseException(NumberParseException::NOT_A_NUMBER, 'The phone-context valid is invalid.');
1721
        }
1722
 
1723
        if ($phoneContext !== null) {
1724
            // If the phone context contains a phone number prefix, we need to capture it, whereas domains
1725
            // will be ignored.
1726
            if (str_starts_with($phoneContext, self::PLUS_SIGN)) {
1727
                // Additional parameters might follow the phone context. If so, we will remove them here
1728
                // because the parameters after phone context are not important for parsing the phone
1729
                // number.
1730
                $nationalNumber .= $phoneContext;
1731
            }
1732
 
1733
            // Now append everything between the "tel:" prefix and the phone-context. This should include
1734
            // the national number, an optional extension or isdn-subaddress component. Note we also
1735
            // handle the case when "tel:" is missing, as we have seen in some of the phone number inputs.
1736
            // In that case, we append everything from the beginning.
1737
 
1738
            $indexOfRfc3966Prefix = strpos($numberToParse, static::RFC3966_PREFIX);
1739
            $indexOfNationalNumber = ($indexOfRfc3966Prefix !== false) ? $indexOfRfc3966Prefix + strlen(static::RFC3966_PREFIX) : 0;
1740
            $nationalNumber .= substr(
1741
                $numberToParse,
1742
                $indexOfNationalNumber,
1743
                $indexOfPhoneContext - $indexOfNationalNumber
1744
            );
1745
        } else {
1746
            // Extract a possible number from the string passed in (this strips leading characters that
1747
            // could not be the start of a phone number.)
1748
            $nationalNumber .= static::extractPossibleNumber($numberToParse);
1749
        }
1750
 
1751
        // Delete the isdn-subaddress and everything after it if it is present. Note extension won't
1752
        // appear at the same time with isdn-subaddress according to paragraph 5.3 of the RFC3966 spec,
1753
        $indexOfIsdn = strpos($nationalNumber, static::RFC3966_ISDN_SUBADDRESS);
1754
        if ($indexOfIsdn > 0) {
1755
            $nationalNumber = substr($nationalNumber, 0, $indexOfIsdn);
1756
        }
1757
        // If both phone context and isdn-subaddress are absent but other parameters are present, the
1758
        // parameters are left in nationalNumber. This is because we are concerned about deleting
1759
        // content from a potential number string when there is no strong evidence that the number is
1760
        // actually written in RFC3966.
1761
    }
1762
 
1763
    /**
1764
     * Attempts to extract a possible number from the string passed in. This currently strips all
1765
     * leading characters that cannot be used to start a phone number. Characters that can be used to
1766
     * start a phone number are defined in the VALID_START_CHAR_PATTERN. If none of these characters
1767
     * are found in the number passed in, an empty string is returned. This function also attempts to
1768
     * strip off any alternative extensions or endings if two or more are present, such as in the case
1769
     * of: (530) 583-6985 x302/x2303. The second extension here makes this actually two phone numbers,
1770
     * (530) 583-6985 x302 and (530) 583-6985 x2303. We remove the second extension so that the first
1771
     * number is parsed correctly.
1772
     *
1773
     * @param string $number the string that might contain a phone number
1774
     * @return string the number, stripped of any non-phone-number prefix (such as "Tel:") or an empty
1775
     *                string if no character used to start phone numbers (such as + or any digit) is
1776
     *                found in the number
1777
     */
1778
    public static function extractPossibleNumber(string $number): string
1779
    {
1780
        $matches = [];
1781
        $match = preg_match('/' . static::VALID_START_CHAR_PATTERN . '/ui', $number, $matches, PREG_OFFSET_CAPTURE);
1782
        if ($match > 0) {
1783
            $number = substr($number, $matches[0][1]);
1784
            // Remove trailing non-alpha non-numerical characters.
1785
            $trailingCharsMatcher = new Matcher(static::UNWANTED_END_CHAR_PATTERN, $number);
1786
            if ($trailingCharsMatcher->find() && $trailingCharsMatcher->start() > 0) {
1787
                $number = substr($number, 0, $trailingCharsMatcher->start());
1788
            }
1789
 
1790
            // Check for extra numbers at the end.
1791
            $match = preg_match('%' . static::SECOND_NUMBER_START_PATTERN . '%', $number, $matches, PREG_OFFSET_CAPTURE);
1792
            if ($match > 0) {
1793
                $number = substr($number, 0, $matches[0][1]);
1794
            }
1795
 
1796
            return $number;
1797
        }
1798
 
1799
        return '';
1800
    }
1801
 
1802
    /**
1803
     * Checks to see that the region code used is valid, or if it is not valid, that the number to
1804
     * parse starts with a + symbol so that we can attempt to infer the region from the number.
1805
     * Returns false if it cannot use the region provided and the region cannot be inferred.
1806
     */
1807
    protected function checkRegionForParsing(?string $numberToParse, ?string $defaultRegion): bool
1808
    {
1809
        if (!$this->isValidRegionCode($defaultRegion)) {
1810
            // If the number is null or empty, we can't infer the region.
1811
            $plusCharsPatternMatcher = new Matcher(static::PLUS_CHARS_PATTERN, $numberToParse);
1812
            if ($numberToParse === null || $numberToParse === '' || !$plusCharsPatternMatcher->lookingAt()) {
1813
                return false;
1814
            }
1815
        }
1816
        return true;
1817
    }
1818
 
1819
    /**
1820
     * Tries to extract a country calling code from a number. This method will return zero if no
1821
     * country calling code is considered to be present. Country calling codes are extracted in the
1822
     * following ways:
1823
     * <ul>
1824
     *  <li> by stripping the international dialing prefix of the region the person is dialing from,
1825
     *       if this is present in the number, and looking at the next digits
1826
     *  <li> by stripping the '+' sign if present and then looking at the next digits
1827
     *  <li> by comparing the start of the number and the country calling code of the default region.
1828
     *       If the number is not considered possible for the numbering plan of the default region
1829
     *       initially, but starts with the country calling code of this region, validation will be
1830
     *       reattempted after stripping this country calling code. If this number is considered a
1831
     *       possible number, then the first digits will be considered the country calling code and
1832
     *       removed as such.
1833
     * </ul>
1834
     * It will throw a NumberParseException if the number starts with a '+' but the country calling
1835
     * code supplied after this does not match that of any known region.
1836
     *
1837
     * @param string $number non-normalized telephone number that we wish to extract a country calling
1838
     *     code from - may begin with '+'
1839
     * @param PhoneMetadata|null $defaultRegionMetadata metadata about the region this number may be from
1840
     * @param string $nationalNumber a string buffer to store the national significant number in, in the case
1841
     *     that a country calling code was extracted. The number is appended to any existing contents.
1842
     *     If no country calling code was extracted, this will be left unchanged.
1843
     * @param bool $keepRawInput true if the country_code_source and preferred_carrier_code fields of
1844
     *     phoneNumber should be populated.
1845
     * @param PhoneNumber $phoneNumber the PhoneNumber object where the country_code and country_code_source need
1846
     *     to be populated. Note the country_code is always populated, whereas country_code_source is
1847
     *     only populated when keepCountryCodeSource is true.
1848
     * @return int the country calling code extracted or 0 if none could be extracted
1849
     * @throws NumberParseException
1850
     */
1851
    public function maybeExtractCountryCode(
1852
        string $number,
1853
        ?PhoneMetadata $defaultRegionMetadata,
1854
        string &$nationalNumber,
1855
        bool $keepRawInput,
1856
        PhoneNumber $phoneNumber
1857
    ): int {
1858
        if ($number === '') {
1859
            return 0;
1860
        }
1861
        $fullNumber = $number;
1862
        // Set the default prefix to be something that will never match.
1863
        $possibleCountryIddPrefix = 'NonMatch';
1864
        if ($defaultRegionMetadata !== null) {
1865
            $possibleCountryIddPrefix = $defaultRegionMetadata->getInternationalPrefix();
1866
        }
1867
        $countryCodeSource = $this->maybeStripInternationalPrefixAndNormalize($fullNumber, $possibleCountryIddPrefix);
1868
 
1869
        if ($keepRawInput) {
1870
            $phoneNumber->setCountryCodeSource($countryCodeSource);
1871
        }
1872
        if ($countryCodeSource !== CountryCodeSource::FROM_DEFAULT_COUNTRY) {
1873
            if (mb_strlen($fullNumber) <= static::MIN_LENGTH_FOR_NSN) {
1874
                throw new NumberParseException(
1875
                    NumberParseException::TOO_SHORT_AFTER_IDD,
1876
                    'Phone number had an IDD, but after this was not long enough to be a viable phone number.'
1877
                );
1878
            }
1879
            $potentialCountryCode = $this->extractCountryCode($fullNumber, $nationalNumber);
1880
 
1881
            if ($potentialCountryCode !== 0) {
1882
                $phoneNumber->setCountryCode($potentialCountryCode);
1883
                return $potentialCountryCode;
1884
            }
1885
 
1886
            // If this fails, they must be using a strange country calling code that we don't recognize,
1887
            // or that doesn't exist.
1888
            throw new NumberParseException(
1889
                NumberParseException::INVALID_COUNTRY_CODE,
1890
                'Country calling code supplied was not recognised.'
1891
            );
1892
        }
1893
 
1894
        if ($defaultRegionMetadata !== null) {
1895
            // Check to see if the number starts with the country calling code for the default region. If
1896
            // so, we remove the country calling code, and do some checks on the validity of the number
1897
            // before and after.
1898
            $defaultCountryCode = $defaultRegionMetadata->getCountryCode();
1899
            $defaultCountryCodeString = (string) $defaultCountryCode;
1900
            $normalizedNumber = $fullNumber;
1901
            if (str_starts_with($normalizedNumber, $defaultCountryCodeString)) {
1902
                $potentialNationalNumber = substr($normalizedNumber, mb_strlen($defaultCountryCodeString));
1903
                $generalDesc = $defaultRegionMetadata->getGeneralDesc();
1904
                // Don't need the carrier code.
1905
                $carrierCode = null;
1906
                $this->maybeStripNationalPrefixAndCarrierCode(
1907
                    $potentialNationalNumber,
1908
                    $defaultRegionMetadata,
1909
                    $carrierCode
1910
                );
1911
                // If the number was not valid before but is valid now, or if it was too long before, we
1912
                // consider the number with the country calling code stripped to be a better result and
1913
                // keep that instead.
1914
                if ((!$this->matcherAPI->matchNationalNumber($fullNumber, $generalDesc, false)
1915
                        && $this->matcherAPI->matchNationalNumber($potentialNationalNumber, $generalDesc, false))
1916
                    || $this->testNumberLength($fullNumber, $defaultRegionMetadata) === ValidationResult::TOO_LONG
1917
                ) {
1918
                    $nationalNumber .= $potentialNationalNumber;
1919
                    if ($keepRawInput) {
1920
                        $phoneNumber->setCountryCodeSource(CountryCodeSource::FROM_NUMBER_WITHOUT_PLUS_SIGN);
1921
                    }
1922
                    $phoneNumber->setCountryCode($defaultCountryCode);
1923
                    return $defaultCountryCode;
1924
                }
1925
            }
1926
        }
1927
        // No country calling code present.
1928
        $phoneNumber->setCountryCode(0);
1929
        return 0;
1930
    }
1931
 
1932
    /**
1933
     * Strips any international prefix (such as +, 00, 011) present in the number provided, normalizes
1934
     * the resulting number, and indicates if an international prefix was present.
1935
     *
1936
     * @param string $number the non-normalized telephone number that we wish to strip any international
1937
     *     dialing prefix from.
1938
     * @param string $possibleIddPrefix string the international direct dialing prefix from the region we
1939
     *     think this number may be dialed in
1940
     * @return int the corresponding CountryCodeSource if an international dialing prefix could be
1941
     *     removed from the number, otherwise CountryCodeSource.FROM_DEFAULT_COUNTRY if the number did
1942
     *     not seem to be in international format.
1943
     */
1944
    public function maybeStripInternationalPrefixAndNormalize(string &$number, string $possibleIddPrefix): int
1945
    {
1946
        if ($number === '') {
1947
            return CountryCodeSource::FROM_DEFAULT_COUNTRY;
1948
        }
1949
        $matches = [];
1950
        // Check to see if the number begins with one or more plus signs.
1951
        $match = preg_match('/^' . static::PLUS_CHARS_PATTERN . '/' . static::REGEX_FLAGS, $number, $matches, PREG_OFFSET_CAPTURE);
1952
        if ($match > 0) {
1953
            $number = mb_substr($number, $matches[0][1] + mb_strlen($matches[0][0]));
1954
            // Can now normalize the rest of the number since we've consumed the "+" sign at the start.
1955
            $number = static::normalize($number);
1956
            return CountryCodeSource::FROM_NUMBER_WITH_PLUS_SIGN;
1957
        }
1958
        // Attempt to parse the first digits as an international prefix.
1959
        $iddPattern = $possibleIddPrefix;
1960
        $number = static::normalize($number);
1961
        return $this->parsePrefixAsIdd($iddPattern, $number)
1962
            ? CountryCodeSource::FROM_NUMBER_WITH_IDD
1963
            : CountryCodeSource::FROM_DEFAULT_COUNTRY;
1964
    }
1965
 
1966
    /**
1967
     * Normalizes a string of characters representing a phone number. This performs
1968
     * the following conversions:
1969
     *   Punctuation is stripped.
1970
     *   For ALPHA/VANITY numbers:
1971
     *   Letters are converted to their numeric representation on a telephone
1972
     *       keypad. The keypad used here is the one defined in ITU Recommendation
1973
     *       E.161. This is only done if there are 3 or more letters in the number,
1974
     *       to lessen the risk that such letters are typos.
1975
     *   For other numbers:
1976
     *    - Wide-ascii digits are converted to normal ASCII (European) digits.
1977
     *    - Arabic-Indic numerals are converted to European numerals.
1978
     *    - Spurious alpha characters are stripped.
1979
     *
1980
     * @param string $number a string of characters representing a phone number.
1981
     * @return string the normalized string version of the phone number.
1982
     */
1983
    public static function normalize(string $number): string
1984
    {
1985
        $m = new Matcher(static::VALID_ALPHA_PHONE_PATTERN, $number);
1986
        if ($m->matches()) {
1987
            return static::normalizeHelper($number, static::ALPHA_PHONE_MAPPINGS, true);
1988
        }
1989
 
1990
        return static::normalizeDigitsOnly($number);
1991
    }
1992
 
1993
    /**
1994
     * Normalizes a string of characters representing a phone number. This converts wide-ascii and
1995
     * arabic-indic numerals to European numerals, and strips punctuation and alpha characters.
1996
     *
1997
     * @param string $number a string of characters representing a phone number
1998
     * @return string the normalized string version of the phone number
1999
     */
2000
    public static function normalizeDigitsOnly(string $number): string
2001
    {
2002
        return static::normalizeDigits($number, false /* strip non-digits */);
2003
    }
2004
 
2005
    /**
2006
     */
2007
    public static function normalizeDigits(string $number, bool $keepNonDigits): string
2008
    {
2009
        $normalizedDigits = '';
2010
        $numberAsArray = preg_split('/(?<!^)(?!$)/u', $number);
2011
        if ($numberAsArray === false) {
2012
            return $normalizedDigits;
2013
        }
2014
        foreach ($numberAsArray as $character) {
2015
            // Check if we are in the unicode number range
2016
            if (array_key_exists($character, static::NUMERIC_CHARACTERS)) {
2017
                $normalizedDigits .= static::NUMERIC_CHARACTERS[$character];
2018
            } elseif (is_numeric($character)) {
2019
                $normalizedDigits .= $character;
2020
            } elseif ($keepNonDigits) {
2021
                $normalizedDigits .= $character;
2022
            }
2023
        }
2024
        return $normalizedDigits;
2025
    }
2026
 
2027
    /**
2028
     * Strips the IDD from the start of the number if present. Helper function used by
2029
     * maybeStripInternationalPrefixAndNormalize.
2030
     */
2031
    protected function parsePrefixAsIdd(string $iddPattern, string &$number): bool
2032
    {
2033
        $m = new Matcher($iddPattern, $number);
2034
        if ($m->lookingAt()) {
2035
            $matchEnd = $m->end();
2036
            // Only strip this if the first digit after the match is not a 0, since country calling codes
2037
            // cannot begin with 0.
2038
            $digitMatcher = new Matcher(static::CAPTURING_DIGIT_PATTERN, substr($number, $matchEnd));
2039
            if ($digitMatcher->find()) {
2040
                $normalizedGroup = static::normalizeDigitsOnly($digitMatcher->group(1));
2041
                if ($normalizedGroup === '0') {
2042
                    return false;
2043
                }
2044
            }
2045
            $number = substr($number, $matchEnd);
2046
            return true;
2047
        }
2048
        return false;
2049
    }
2050
 
2051
    /**
2052
     * Extracts country calling code from fullNumber, returns it and places the remaining number in  nationalNumber.
2053
     * It assumes that the leading plus sign or IDD has already been removed.
2054
     * Returns 0 if fullNumber doesn't start with a valid country calling code, and leaves nationalNumber unmodified.
2055
     * @internal
2056
     */
2057
    protected function extractCountryCode(string $fullNumber, string &$nationalNumber): int
2058
    {
2059
        if (($fullNumber === '') || ($fullNumber[0] === '0')) {
2060
            // Country codes do not begin with a '0'.
2061
            return 0;
2062
        }
2063
        $numberLength = strlen($fullNumber);
2064
        for ($i = 1; $i <= static::MAX_LENGTH_COUNTRY_CODE && $i <= $numberLength; $i++) {
2065
            $potentialCountryCode = (int) substr($fullNumber, 0, $i);
2066
            if (isset($this->countryCallingCodeToRegionCodeMap[$potentialCountryCode])) {
2067
                $nationalNumber .= substr($fullNumber, $i);
2068
                return $potentialCountryCode;
2069
            }
2070
        }
2071
        return 0;
2072
    }
2073
 
2074
    /**
2075
     * Strips any national prefix (such as 0, 1) present in the number provided.
2076
     *
2077
     * @param string $number the normalized telephone number that we wish to strip any national
2078
     *     dialing prefix from
2079
     * @param PhoneMetadata $metadata the metadata for the region that we think this number is from
2080
     * @param string|null $carrierCode a place to insert the carrier code if one is extracted
2081
     * @return bool true if a national prefix or carrier code (or both) could be extracted.
2082
     */
2083
    public function maybeStripNationalPrefixAndCarrierCode(string &$number, PhoneMetadata $metadata, ?string &$carrierCode): bool
2084
    {
2085
        $possibleNationalPrefix = $metadata->getNationalPrefixForParsing();
2086
        if ($number === '' || $possibleNationalPrefix === null || $possibleNationalPrefix === '') {
2087
            // Early return for numbers of zero length.
2088
            return false;
2089
        }
2090
 
2091
        // Attempt to parse the first digits as a national prefix.
2092
        $prefixMatcher = new Matcher($possibleNationalPrefix, $number);
2093
        if ($prefixMatcher->lookingAt()) {
2094
            $generalDesc = $metadata->getGeneralDesc();
2095
            // Check if the original number is viable.
2096
            $isViableOriginalNumber = $this->matcherAPI->matchNationalNumber($number, $generalDesc, false);
2097
            // $prefixMatcher->group($numOfGroups) === null implies nothing was captured by the capturing
2098
            // groups in $possibleNationalPrefix; therefore, no transformation is necessary, and we just
2099
            // remove the national prefix
2100
            $numOfGroups = $prefixMatcher->groupCount();
2101
            $transformRule = $metadata->getNationalPrefixTransformRule();
2102
            if ($transformRule === null
2103
                || $transformRule === ''
2104
                || $prefixMatcher->group($numOfGroups - 1) === null
2105
            ) {
2106
                // If the original number was viable, and the resultant number is not, we return.
2107
                if ($isViableOriginalNumber &&
2108
                    !$this->matcherAPI->matchNationalNumber(
2109
                        substr($number, $prefixMatcher->end()),
2110
                        $generalDesc,
2111
                        false
2112
                    )) {
2113
                    return false;
2114
                }
2115
                if ($carrierCode !== null && $numOfGroups > 0 && $prefixMatcher->group($numOfGroups) !== null) {
2116
                    $carrierCode .= $prefixMatcher->group(1);
2117
                }
2118
 
2119
                $number = substr($number, $prefixMatcher->end());
2120
                return true;
2121
            }
2122
 
2123
            // Check that the resultant number is still viable. If not, return. Check this by copying
2124
            // the string and making the transformation on the copy first.
2125
            $transformedNumber = $number;
2126
            $numberLength = mb_strlen($number);
2127
            $transformedNumber = substr_replace(
2128
                $transformedNumber,
2129
                $prefixMatcher->replaceFirst($transformRule),
2130
                0,
2131
                $numberLength
2132
            );
2133
            if ($isViableOriginalNumber
2134
                && !$this->matcherAPI->matchNationalNumber($transformedNumber, $generalDesc, false)) {
2135
                return false;
2136
            }
2137
            if ($carrierCode !== null && $numOfGroups > 1) {
2138
                $carrierCode .= $prefixMatcher->group(1);
2139
            }
2140
            $number = substr_replace($number, $transformedNumber, 0, mb_strlen($number));
2141
            return true;
2142
        }
2143
        return false;
2144
    }
2145
 
2146
    /**
2147
     * Convenience wrapper around isPossibleNumberForTypeWithReason. Instead of returning the reason
2148
     * for failure, this method returns true if the number is either a possible fully-qualified
2149
     * number (containing the area code and country code), or if the number could be a possible local
2150
     * number (with a country code, but missing an area code). Local numbers are considered possible
2151
     * if they could be possibly dialled in this format: if the area code is needed for a call to
2152
     * connect, the number is not considered possible without it.
2153
     *
2154
     * @param PhoneNumber $number The number that needs to be checked
2155
     * @param int $type PhoneNumberType The type we are interested in
2156
     * @return bool true if the number is possible for this particular type
2157
     */
2158
    public function isPossibleNumberForType(PhoneNumber $number, int $type): bool
2159
    {
2160
        $result = $this->isPossibleNumberForTypeWithReason($number, $type);
2161
        return $result === ValidationResult::IS_POSSIBLE
2162
            || $result === ValidationResult::IS_POSSIBLE_LOCAL_ONLY;
2163
    }
2164
 
2165
    /**
2166
     * Helper method to check a number against possible lengths for this number type, and determine
2167
     * whether it matches, or is too short or too long.
2168
     *
2169
     * @param int $type PhoneNumberType
2170
     * @return int ValidationResult
2171
     */
2172
    protected function testNumberLength(string $number, PhoneMetadata $metadata, int $type = PhoneNumberType::UNKNOWN): int
2173
    {
2174
        $descForType = $this->getNumberDescByType($metadata, $type);
2175
        // There should always be "possibleLengths" set for every element. This is declared in the XML
2176
        // schema which is verified by PhoneNumberMetadataSchemaTest.
2177
        // For size efficiency, where a sub-description (e.g. fixed-line) has the same possibleLengths
2178
        // as the parent, this is missing, so we fall back to the general desc (where no numbers of the
2179
        // type exist at all, there is one possible length (-1) which is guaranteed not to match the
2180
        // length of any real phone number).
2181
        $possibleLengths = (count($descForType->getPossibleLength()) === 0)
2182
            ? $metadata->getGeneralDesc()->getPossibleLength() : $descForType->getPossibleLength();
2183
 
2184
        $localLengths = $descForType->getPossibleLengthLocalOnly();
2185
 
2186
        if ($type === PhoneNumberType::FIXED_LINE_OR_MOBILE) {
2187
            if (!static::descHasPossibleNumberData($this->getNumberDescByType($metadata, PhoneNumberType::FIXED_LINE))) {
2188
                // The rate case has been encountered where no fixedLine data is available (true for some
2189
                // non-geographical entities), so we just check mobile.
2190
                return $this->testNumberLength($number, $metadata, PhoneNumberType::MOBILE);
2191
            }
2192
 
2193
            $mobileDesc = $this->getNumberDescByType($metadata, PhoneNumberType::MOBILE);
2194
            if (static::descHasPossibleNumberData($mobileDesc)) {
2195
                // Note that when adding the possible lengths from mobile, we have to again check they
2196
                // aren't empty since if they are this indicates they are the same as the general desc and
2197
                // should be obtained from there.
2198
                $possibleLengths = array_merge(
2199
                    $possibleLengths,
2200
                    (count($mobileDesc->getPossibleLength()) === 0)
2201
                        ? $metadata->getGeneralDesc()->getPossibleLength() : $mobileDesc->getPossibleLength()
2202
                );
2203
 
2204
                // The current list is sorted; we need to merge in the new list and re-sort (duplicates
2205
                // are okay). Sorting isn't so expensive because the lists are very small.
2206
                sort($possibleLengths);
2207
 
2208
                if (count($localLengths) === 0) {
2209
                    $localLengths = $mobileDesc->getPossibleLengthLocalOnly();
2210
                } else {
2211
                    $localLengths = array_merge($localLengths, $mobileDesc->getPossibleLengthLocalOnly());
2212
                    sort($localLengths);
2213
                }
2214
            }
2215
        }
2216
 
2217
 
2218
        // If the type is not supported at all (indicated by the possible lengths containing -1 at this
2219
        // point) we return invalid length.
2220
 
2221
        if ($possibleLengths[0] === -1) {
2222
            return ValidationResult::INVALID_LENGTH;
2223
        }
2224
 
2225
        $actualLength = mb_strlen($number);
2226
 
2227
        // This is safe because there is never an overlap between the possible lengths and the local-only
2228
        // lengths; this is checked at build time.
2229
 
2230
        if (in_array($actualLength, $localLengths)) {
2231
            return ValidationResult::IS_POSSIBLE_LOCAL_ONLY;
2232
        }
2233
 
2234
        $minimumLength = reset($possibleLengths);
2235
        if ($minimumLength === $actualLength) {
2236
            return ValidationResult::IS_POSSIBLE;
2237
        }
2238
 
2239
        if ($minimumLength > $actualLength) {
2240
            return ValidationResult::TOO_SHORT;
2241
        }
2242
 
2243
        if (isset($possibleLengths[count($possibleLengths) - 1]) && $possibleLengths[count($possibleLengths) - 1] < $actualLength) {
2244
            return ValidationResult::TOO_LONG;
2245
        }
2246
 
2247
        // We skip the first element; we've already checked it.
2248
        array_shift($possibleLengths);
2249
        return in_array($actualLength, $possibleLengths) ? ValidationResult::IS_POSSIBLE : ValidationResult::INVALID_LENGTH;
2250
    }
2251
 
2252
    /**
2253
     * Returns a list with the region codes that match the specific country calling code. For
2254
     * non-geographical country calling codes, the region code 001 is returned. Also, in the case
2255
     * of no region code being found, an empty list is returned.
2256
     * @return string[]
2257
     */
2258
    public function getRegionCodesForCountryCode(int $countryCallingCode): array
2259
    {
2260
        $regionCodes = $this->countryCallingCodeToRegionCodeMap[$countryCallingCode] ?? null;
2261
        return $regionCodes ?? [];
2262
    }
2263
 
2264
    /**
2265
     * Returns the country calling code for a specific region. For example, this would be 1 for the
2266
     * United States, and 64 for New Zealand. Assumes the region is already valid.
2267
     *
2268
     * @param string|null $regionCode the region that we want to get the country calling code for
2269
     * @return int the country calling code for the region denoted by regionCode
2270
     */
2271
    public function getCountryCodeForRegion(?string $regionCode): int
2272
    {
2273
        if (!$this->isValidRegionCode($regionCode)) {
2274
            return 0;
2275
        }
2276
        return $this->getCountryCodeForValidRegion($regionCode);
2277
    }
2278
 
2279
    /**
2280
     * Returns the country calling code for a specific region. For example, this would be 1 for the
2281
     * United States, and 64 for New Zealand. Assumes the region is already valid.
2282
     *
2283
     * @param string $regionCode the region that we want to get the country calling code for
2284
     * @return int the country calling code for the region denoted by regionCode
2285
     * @throws \InvalidArgumentException if the region is invalid
2286
     */
2287
    protected function getCountryCodeForValidRegion(string $regionCode): int
2288
    {
2289
        $metadata = $this->getMetadataForRegion($regionCode);
2290
        if ($metadata === null) {
2291
            throw new \InvalidArgumentException('Invalid region code: ' . $regionCode);
2292
        }
2293
        return $metadata->getCountryCode();
2294
    }
2295
 
2296
    /**
2297
     * Returns a number formatted in such a way that it can be dialed from a mobile phone in a
2298
     * specific region. If the number cannot be reached from the region (e.g. some countries block
2299
     * toll-free numbers from being called outside of the country), the method returns an empty
2300
     * string.
2301
     *
2302
     * @param PhoneNumber $number the phone number to be formatted
2303
     * @param string $regionCallingFrom the region where the call is being placed
2304
     * @param boolean $withFormatting whether the number should be returned with formatting symbols, such as
2305
     *     spaces and dashes.
2306
     * @return string the formatted phone number
2307
     */
2308
    public function formatNumberForMobileDialing(PhoneNumber $number, string $regionCallingFrom, bool $withFormatting): string
2309
    {
2310
        $countryCallingCode = $number->getCountryCode();
2311
        if (!$this->hasValidCountryCallingCode($countryCallingCode)) {
2312
            return $number->hasRawInput() ? $number->getRawInput() : '';
2313
        }
2314
 
2315
        $formattedNumber = '';
2316
        // Clear the extension, as that part cannot normally be dialed together with the main number.
2317
        $numberNoExt = new PhoneNumber();
2318
        $numberNoExt->mergeFrom($number)->clearExtension();
2319
        $regionCode = $this->getRegionCodeForCountryCode($countryCallingCode);
2320
        $numberType = $this->getNumberType($numberNoExt);
2321
        $isValidNumber = ($numberType !== PhoneNumberType::UNKNOWN);
2322
        if (strtoupper($regionCallingFrom) === $regionCode) {
2323
            $isFixedLineOrMobile = ($numberType === PhoneNumberType::FIXED_LINE || $numberType === PhoneNumberType::MOBILE || $numberType === PhoneNumberType::FIXED_LINE_OR_MOBILE);
2324
            // Carrier codes may be needed in some countries. We handle this here.
2325
            if ($regionCode === 'BR' && $isFixedLineOrMobile) {
2326
                // Historically, we set this to an empty string when parsing with raw input if none was
2327
                // found in the input string. However, this doesn't result in a number we can dial. For this
2328
                // reason, we treat the empty string the same as if it isn't set at all.
2329
                $formattedNumber = $numberNoExt->getPreferredDomesticCarrierCode() !== ''
2330
                    ? $this->formatNationalNumberWithPreferredCarrierCode($numberNoExt, '')
2331
                    // Brazilian fixed line and mobile numbers need to be dialed with a carrier code when
2332
                    // called within Brazil. Without that, most of the carriers won't connect the call.
2333
                    // Because of that, we return an empty string here.
2334
                    : '';
2335
            } elseif ($countryCallingCode === static::NANPA_COUNTRY_CODE) {
2336
                // For NANPA countries, we output international format for numbers that can be dialed
2337
                // internationally, since that always works, except for numbers which might potentially be
2338
                // short numbers, which are always dialled in national format.
2339
                $regionMetadata = $this->getMetadataForRegion($regionCallingFrom);
2340
                if ($this->canBeInternationallyDialled($numberNoExt)
2341
                    && $this->testNumberLength($this->getNationalSignificantNumber($numberNoExt), $regionMetadata)
2342
                    !== ValidationResult::TOO_SHORT
2343
                ) {
2344
                    $formattedNumber = $this->format($numberNoExt, PhoneNumberFormat::INTERNATIONAL);
2345
                } else {
2346
                    $formattedNumber = $this->format($numberNoExt, PhoneNumberFormat::NATIONAL);
2347
                }
2348
            } elseif ((
2349
                $regionCode === static::REGION_CODE_FOR_NON_GEO_ENTITY ||
2350
                    // MX fixed line and mobile numbers should always be formatted in international format,
2351
                    // even when dialed within MX. For national format to work, a carrier code needs to be
2352
                    // used, and the correct carrier code depends on if the caller and callee are from the
2353
                    // same local area. It is trickier to get that to work correctly than using
2354
                    // international format, which is tested to work fine on all carriers.
2355
                    // CL fixed line numbers need the national prefix when dialing in the national format,
2356
                    // but don't have it when used for display. The reverse is true for mobile numbers.
2357
                    // As a result, we output them in the international format to make it work.
2358
                    (
2359
                        ($regionCode === 'MX' || $regionCode === 'CL' || $regionCode === 'UZ')
2360
                        && $isFixedLineOrMobile
2361
                    )
2362
            ) && $this->canBeInternationallyDialled($numberNoExt)
2363
            ) {
2364
                $formattedNumber = $this->format($numberNoExt, PhoneNumberFormat::INTERNATIONAL);
2365
            } else {
2366
                $formattedNumber = $this->format($numberNoExt, PhoneNumberFormat::NATIONAL);
2367
            }
2368
        } elseif ($isValidNumber && $this->canBeInternationallyDialled($numberNoExt)) {
2369
            // We assume that short numbers are not diallable from outside their region, so if a number
2370
            // is not a valid regular length phone number, we treat it as if it cannot be internationally
2371
            // dialled.
2372
            return $withFormatting ?
2373
                $this->format($numberNoExt, PhoneNumberFormat::INTERNATIONAL) :
2374
                $this->format($numberNoExt, PhoneNumberFormat::E164);
2375
        }
2376
        return $withFormatting ? $formattedNumber : static::normalizeDiallableCharsOnly($formattedNumber);
2377
    }
2378
 
2379
    /**
2380
     * Formats a phone number in national format for dialing using the carrier as specified in the
2381
     * {@code carrierCode}. The {@code carrierCode} will always be used regardless of whether the
2382
     * phone number already has a preferred domestic carrier code stored. If {@code carrierCode}
2383
     * contains an empty string, returns the number in national format without any carrier code.
2384
     *
2385
     * @param PhoneNumber $number the phone number to be formatted
2386
     * @param string $carrierCode the carrier selection code to be used
2387
     * @return string the formatted phone number in national format for dialing using the carrier as
2388
     * specified in the {@code carrierCode}
2389
     */
2390
    public function formatNationalNumberWithCarrierCode(PhoneNumber $number, string $carrierCode): string
2391
    {
2392
        $countryCallingCode = $number->getCountryCode();
2393
        $nationalSignificantNumber = $this->getNationalSignificantNumber($number);
2394
        if (!$this->hasValidCountryCallingCode($countryCallingCode)) {
2395
            return $nationalSignificantNumber;
2396
        }
2397
 
2398
        // Note getRegionCodeForCountryCode() is used because formatting information for regions which
2399
        // share a country calling code is contained by only one region for performance reasons. For
2400
        // example, for NANPA regions it will be contained in the metadata for US.
2401
        $regionCode = $this->getRegionCodeForCountryCode($countryCallingCode);
2402
        // Metadata cannot be null because the country calling code is valid.
2403
        $metadata = $this->getMetadataForRegionOrCallingCode($countryCallingCode, $regionCode);
2404
 
2405
        $formattedNumber = $this->formatNsn(
2406
            $nationalSignificantNumber,
2407
            $metadata,
2408
            PhoneNumberFormat::NATIONAL,
2409
            $carrierCode
2410
        );
2411
        $this->maybeAppendFormattedExtension($number, $metadata, PhoneNumberFormat::NATIONAL, $formattedNumber);
2412
        $this->prefixNumberWithCountryCallingCode(
2413
            $countryCallingCode,
2414
            PhoneNumberFormat::NATIONAL,
2415
            $formattedNumber
2416
        );
2417
        return $formattedNumber;
2418
    }
2419
 
2420
    /**
2421
     * Formats a phone number in national format for dialing using the carrier as specified in the
2422
     * preferredDomesticCarrierCode field of the PhoneNumber object passed in. If that is missing,
2423
     * use the {@code fallbackCarrierCode} passed in instead. If there is no
2424
     * {@code preferredDomesticCarrierCode}, and the {@code fallbackCarrierCode} contains an empty
2425
     * string, return the number in national format without any carrier code.
2426
     *
2427
     * <p>Use {@link #formatNationalNumberWithCarrierCode} instead if the carrier code passed in
2428
     * should take precedence over the number's {@code preferredDomesticCarrierCode} when formatting.
2429
     *
2430
     * @param PhoneNumber $number the phone number to be formatted
2431
     * @param string $fallbackCarrierCode the carrier selection code to be used, if none is found in the
2432
     *     phone number itself
2433
     * @return string the formatted phone number in national format for dialing using the number's
2434
     *     {@code preferredDomesticCarrierCode}, or the {@code fallbackCarrierCode} passed in if
2435
     *     none is found
2436
     */
2437
    public function formatNationalNumberWithPreferredCarrierCode(PhoneNumber $number, string $fallbackCarrierCode): string
2438
    {
2439
        return $this->formatNationalNumberWithCarrierCode(
2440
            $number,
2441
            // Historically, we set this to an empty string when parsing with raw input if none was
2442
            // found in the input string. However, this doesn't result in a number we can dial. For this
2443
            // reason, we treat the empty string the same as if it isn't set at all.
2444
            $number->hasPreferredDomesticCarrierCode() && $number->getPreferredDomesticCarrierCode() !== ''
2445
                ? $number->getPreferredDomesticCarrierCode()
2446
                : $fallbackCarrierCode
2447
        );
2448
    }
2449
 
2450
    /**
2451
     * Returns true if the number can be dialled from outside the region, or unknown. If the number
2452
     * can only be dialled from within the region, returns false. Does not check the number is a valid
2453
     * number. Note that, at the moment, this method does not handle short numbers (which are
2454
     * currently all presumed to not be diallable from outside their country).
2455
     *
2456
     * @param PhoneNumber $number the phone-number for which we want to know whether it is diallable from outside the region
2457
     */
2458
    public function canBeInternationallyDialled(PhoneNumber $number): bool
2459
    {
2460
        $metadata = $this->getMetadataForRegion($this->getRegionCodeForNumber($number));
2461
        if ($metadata === null) {
2462
            // Note numbers belonging to non-geographical entities (e.g. +800 numbers) are always
2463
            // internationally diallable, and will be caught here.
2464
            return true;
2465
        }
2466
        $nationalSignificantNumber = $this->getNationalSignificantNumber($number);
2467
        return !$this->isNumberMatchingDesc($nationalSignificantNumber, $metadata->getNoInternationalDialling());
2468
    }
2469
 
2470
    /**
2471
     * Normalizes a string of characters representing a phone number. This strips all characters which
2472
     * are not diallable on a mobile phone keypad (including all non-ASCII digits).
2473
     *
2474
     * @param string $number a string of characters representing a phone number
2475
     * @return string the normalized string version of the phone number
2476
     */
2477
    public static function normalizeDiallableCharsOnly(string $number): string
2478
    {
2479
        return static::normalizeHelper($number, static::DIALLABLE_CHAR_MAPPINGS, true /* remove non matches */);
2480
    }
2481
 
2482
    /**
2483
     * Formats a phone number for out-of-country dialing purposes.
2484
     *
2485
     * Note that in this version, if the number was entered originally using alpha characters and
2486
     * this version of the number is stored in raw_input, this representation of the number will be
2487
     * used rather than the digit representation. Grouping information, as specified by characters
2488
     * such as "-" and " ", will be retained.
2489
     *
2490
     * <p><b>Caveats:</b></p>
2491
     * <ul>
2492
     *  <li> This will not produce good results if the country calling code is both present in the raw
2493
     *       input _and_ is the start of the national number. This is not a problem in the regions
2494
     *       which typically use alpha numbers.
2495
     *  <li> This will also not produce good results if the raw input has any grouping information
2496
     *       within the first three digits of the national number, and if the function needs to strip
2497
     *       preceding digits/words in the raw input before these digits. Normally people group the
2498
     *       first three digits together so this is not a huge problem - and will be fixed if it
2499
     *       proves to be so.
2500
     * </ul>
2501
     *
2502
     * @param PhoneNumber $number the phone number that needs to be formatted
2503
     * @param string $regionCallingFrom the region where the call is being placed
2504
     * @return string the formatted phone number
2505
     */
2506
    public function formatOutOfCountryKeepingAlphaChars(PhoneNumber $number, string $regionCallingFrom): string
2507
    {
2508
        $rawInput = $number->getRawInput();
2509
        // If there is no raw input, then we can't keep alpha characters because there aren't any.
2510
        // In this case, we return formatOutOfCountryCallingNumber.
2511
        if ($rawInput === null || $rawInput === '') {
2512
            return $this->formatOutOfCountryCallingNumber($number, $regionCallingFrom);
2513
        }
2514
        $countryCode = $number->getCountryCode();
2515
        if (!$this->hasValidCountryCallingCode($countryCode)) {
2516
            return $rawInput;
2517
        }
2518
        // Strip any prefix such as country calling code, IDD, that was present. We do this by comparing
2519
        // the number in raw_input with the parsed number.
2520
        // To do this, first we normalize punctuation. We retain number grouping symbols such as " "
2521
        // only.
2522
        $rawInput = self::normalizeHelper($rawInput, static::$ALL_PLUS_NUMBER_GROUPING_SYMBOLS, true);
2523
        // Now we trim everything before the first three digits in the parsed number. We choose three
2524
        // because all valid alpha numbers have 3 digits at the start - if it does not, then we don't
2525
        // trim anything at all. Similarly, if the national number was less than three digits, we don't
2526
        // trim anything at all.
2527
        $nationalNumber = $this->getNationalSignificantNumber($number);
2528
        if (strlen($nationalNumber) > 3) {
2529
            $firstNationalNumberDigit = strpos($rawInput, substr($nationalNumber, 0, 3));
2530
            if ($firstNationalNumberDigit !== false) {
2531
                $rawInput = substr($rawInput, $firstNationalNumberDigit);
2532
            }
2533
        }
2534
        $metadataForRegionCallingFrom = $this->getMetadataForRegion($regionCallingFrom);
2535
        if ($countryCode === static::NANPA_COUNTRY_CODE) {
2536
            if ($this->isNANPACountry($regionCallingFrom)) {
2537
                return $countryCode . ' ' . $rawInput;
2538
            }
2539
        } elseif ($metadataForRegionCallingFrom !== null &&
2540
            $countryCode === $this->getCountryCodeForValidRegion($regionCallingFrom)
2541
        ) {
2542
            $formattingPattern =
2543
                $this->chooseFormattingPatternForNumber(
2544
                    $metadataForRegionCallingFrom->numberFormats(),
2545
                    $nationalNumber
2546
                );
2547
            if ($formattingPattern === null) {
2548
                // If no pattern above is matched, we format the original input.
2549
                return $rawInput;
2550
            }
2551
            $newFormat = new NumberFormat();
2552
            $newFormat->mergeFrom($formattingPattern);
2553
            // The first group is the first group of digits that the user wrote together.
2554
            $newFormat->setPattern('(\\d+)(.*)');
2555
            // Here we just concatenate them back together after the national prefix has been fixed.
2556
            $newFormat->setFormat('$1$2');
2557
            // Now we format using this pattern instead of the default pattern, but with the national
2558
            // prefix prefixed if necessary.
2559
            // This will not work in the cases where the pattern (and not the leading digits) decide
2560
            // whether a national prefix needs to be used, since we have overridden the pattern to match
2561
            // anything, but that is not the case in the metadata to date.
2562
            return $this->formatNsnUsingPattern($rawInput, $newFormat, PhoneNumberFormat::NATIONAL);
2563
        }
2564
        $internationalPrefixForFormatting = '';
2565
        // If an unsupported region-calling-from is entered, or a country with multiple international
2566
        // prefixes, the international format of the number is returned, unless there is a preferred
2567
        // international prefix.
2568
        if ($metadataForRegionCallingFrom !== null) {
2569
            $internationalPrefix = $metadataForRegionCallingFrom->getInternationalPrefix();
2570
            $uniqueInternationalPrefixMatcher = new Matcher(static::SINGLE_INTERNATIONAL_PREFIX, $internationalPrefix);
2571
            $internationalPrefixForFormatting =
2572
                $uniqueInternationalPrefixMatcher->matches()
2573
                    ? $internationalPrefix
2574
                    : $metadataForRegionCallingFrom->getPreferredInternationalPrefix();
2575
        }
2576
        $formattedNumber = $rawInput;
2577
        $regionCode = $this->getRegionCodeForCountryCode($countryCode);
2578
        // Metadata cannot be null because the country calling code is valid.
2579
        $metadataForRegion = $this->getMetadataForRegionOrCallingCode($countryCode, $regionCode);
2580
        // Strip any extension
2581
        $this->maybeStripExtension($formattedNumber);
2582
        // Append the formatted extension
2583
        $this->maybeAppendFormattedExtension(
2584
            $number,
2585
            $metadataForRegion,
2586
            PhoneNumberFormat::INTERNATIONAL,
2587
            $formattedNumber
2588
        );
2589
        if (isset($internationalPrefixForFormatting) && $internationalPrefixForFormatting !== '') {
2590
            $formattedNumber = $internationalPrefixForFormatting . ' ' . $countryCode . ' ' . $formattedNumber;
2591
        } else {
2592
            // Invalid region entered as country-calling-from (so no metadata was found for it) or the
2593
            // region chosen has multiple international dialling prefixes.
2594
            $this->prefixNumberWithCountryCallingCode(
2595
                $countryCode,
2596
                PhoneNumberFormat::INTERNATIONAL,
2597
                $formattedNumber
2598
            );
2599
        }
2600
        return $formattedNumber;
2601
    }
2602
 
2603
    /**
2604
     * Formats a phone number for out-of-country dialing purposes. If no regionCallingFrom is
2605
     * supplied, we format the number in its INTERNATIONAL format. If the country calling code is the
2606
     * same as that of the region where the number is from, then NATIONAL formatting will be applied.
2607
     *
2608
     * <p>If the number itself has a country calling code of zero or an otherwise invalid country
2609
     * calling code, then we return the number with no formatting applied.
2610
     *
2611
     * <p>Note this function takes care of the case for calling inside of NANPA and between Russia and
2612
     * Kazakhstan (who share the same country calling code). In those cases, no international prefix
2613
     * is used. For regions which have multiple international prefixes, the number in its
2614
     * INTERNATIONAL format will be returned instead.
2615
     *
2616
     * @param PhoneNumber $number the phone number to be formatted
2617
     * @param string $regionCallingFrom the region where the call is being placed
2618
     * @return string  the formatted phone number
2619
     */
2620
    public function formatOutOfCountryCallingNumber(PhoneNumber $number, string $regionCallingFrom): string
2621
    {
2622
        if (!$this->isValidRegionCode($regionCallingFrom)) {
2623
            return $this->format($number, PhoneNumberFormat::INTERNATIONAL);
2624
        }
2625
        $countryCallingCode = $number->getCountryCode();
2626
        $nationalSignificantNumber = $this->getNationalSignificantNumber($number);
2627
        if (!$this->hasValidCountryCallingCode($countryCallingCode)) {
2628
            return $nationalSignificantNumber;
2629
        }
2630
        if ($countryCallingCode === static::NANPA_COUNTRY_CODE) {
2631
            if ($this->isNANPACountry($regionCallingFrom)) {
2632
                // For NANPA regions, return the national format for these regions but prefix it with the
2633
                // country calling code.
2634
                return $countryCallingCode . ' ' . $this->format($number, PhoneNumberFormat::NATIONAL);
2635
            }
2636
        } elseif ($countryCallingCode === $this->getCountryCodeForValidRegion($regionCallingFrom)) {
2637
            // If regions share a country calling code, the country calling code need not be dialled.
2638
            // This also applies when dialling within a region, so this if clause covers both these cases.
2639
            // Technically this is the case for dialling from La Reunion to other overseas departments of
2640
            // France (French Guiana, Martinique, Guadeloupe), but not vice versa - so we don't cover this
2641
            // edge case for now and for those cases return the version including country calling code.
2642
            // Details here: http://www.petitfute.com/voyage/225-info-pratiques-reunion
2643
            return $this->format($number, PhoneNumberFormat::NATIONAL);
2644
        }
2645
        // Metadata cannot be null because we checked 'isValidRegionCode()' above.
2646
        /** @var PhoneMetadata $metadataForRegionCallingFrom */
2647
        $metadataForRegionCallingFrom = $this->getMetadataForRegion($regionCallingFrom);
2648
 
2649
        $internationalPrefix = $metadataForRegionCallingFrom->getInternationalPrefix();
2650
 
2651
        // In general, if there is a preferred international prefix, use that. Otherwise, for regions
2652
        // that have multiple international prefixes, the international format of the number is
2653
        // returned since we would not know which one to use.
2654
        $internationalPrefixForFormatting = '';
2655
        if ($metadataForRegionCallingFrom->hasPreferredInternationalPrefix()) {
2656
            $internationalPrefixForFormatting = $metadataForRegionCallingFrom->getPreferredInternationalPrefix();
2657
        } else {
2658
            $uniqueInternationalPrefixMatcher = new Matcher(static::SINGLE_INTERNATIONAL_PREFIX, $internationalPrefix);
2659
 
2660
            if ($uniqueInternationalPrefixMatcher->matches()) {
2661
                $internationalPrefixForFormatting = $internationalPrefix;
2662
            }
2663
        }
2664
 
2665
        $regionCode = $this->getRegionCodeForCountryCode($countryCallingCode);
2666
        // Metadata cannot be null because the country calling code is valid.
2667
        /** @var PhoneMetadata $metadataForRegion */
2668
        $metadataForRegion = $this->getMetadataForRegionOrCallingCode($countryCallingCode, $regionCode);
2669
        $formattedNationalNumber = $this->formatNsn(
2670
            $nationalSignificantNumber,
2671
            $metadataForRegion,
2672
            PhoneNumberFormat::INTERNATIONAL
2673
        );
2674
        $formattedNumber = $formattedNationalNumber;
2675
        $this->maybeAppendFormattedExtension(
2676
            $number,
2677
            $metadataForRegion,
2678
            PhoneNumberFormat::INTERNATIONAL,
2679
            $formattedNumber
2680
        );
2681
        if ($internationalPrefixForFormatting !== '') {
2682
            $formattedNumber = $internationalPrefixForFormatting . ' ' . $countryCallingCode . ' ' . $formattedNumber;
2683
        } else {
2684
            $this->prefixNumberWithCountryCallingCode(
2685
                $countryCallingCode,
2686
                PhoneNumberFormat::INTERNATIONAL,
2687
                $formattedNumber
2688
            );
2689
        }
2690
        return $formattedNumber;
2691
    }
2692
 
2693
    /**
2694
     * Checks if this is a region under the North American Numbering Plan Administration (NANPA).
2695
     * @return boolean true if regionCode is one of the regions under NANPA
2696
     */
2697
    public function isNANPACountry(string $regionCode): bool
2698
    {
2699
        return in_array(strtoupper($regionCode), $this->nanpaRegions);
2700
    }
2701
 
2702
    /**
2703
     * Formats a phone number using the original phone number format (e.g. INTERNATIONAL or NATIONAL)
2704
     * that the number is parsed from, provided that the number has been parsed with
2705
     * parseAndKeepRawInput. Otherwise the number will be formatted in NATIONAL format.
2706
     *
2707
     * The original format is embedded in the country_code_source field of the PhoneNumber object
2708
     * passed in, which is only set when parsing keeps the raw input. When we don't have a formatting
2709
     * pattern for the number, the method falls back to returning the raw input.
2710
     *
2711
     * Note this method guarantees no digit will be inserted, removed or modified as a result of
2712
     * formatting.
2713
     *
2714
     * @param PhoneNumber $number the phone number that needs to be formatted in its original number format
2715
     * @param string $regionCallingFrom the region whose IDD needs to be prefixed if the original number
2716
     *     has one
2717
     * @return string the formatted phone number in its original number format
2718
     */
2719
    public function formatInOriginalFormat(PhoneNumber $number, string $regionCallingFrom): string
2720
    {
2721
        if ($number->hasRawInput() && !$this->hasFormattingPatternForNumber($number)) {
2722
            // We check if we have the formatting pattern because without that, we might format the number
2723
            // as a group without national prefix.
2724
            return $number->getRawInput();
2725
        }
2726
        if (!$number->hasCountryCodeSource()) {
2727
            return $this->format($number, PhoneNumberFormat::NATIONAL);
2728
        }
2729
        switch ($number->getCountryCodeSource()) {
2730
            case CountryCodeSource::FROM_NUMBER_WITH_PLUS_SIGN:
2731
                $formattedNumber = $this->format($number, PhoneNumberFormat::INTERNATIONAL);
2732
                break;
2733
            case CountryCodeSource::FROM_NUMBER_WITH_IDD:
2734
                $formattedNumber = $this->formatOutOfCountryCallingNumber($number, $regionCallingFrom);
2735
                break;
2736
            case CountryCodeSource::FROM_NUMBER_WITHOUT_PLUS_SIGN:
2737
                $formattedNumber = substr($this->format($number, PhoneNumberFormat::INTERNATIONAL), 1);
2738
                break;
2739
            case CountryCodeSource::FROM_DEFAULT_COUNTRY:
2740
                // Fall-through to default case.
2741
            default:
2742
 
2743
                $regionCode = $this->getRegionCodeForCountryCode($number->getCountryCode());
2744
                // We strip non-digits from the NDD here, and from the raw input later, so that we can
2745
                // compare them easily.
2746
                $nationalPrefix = $this->getNddPrefixForRegion($regionCode, true /* strip non-digits */);
2747
                $nationalFormat = $this->format($number, PhoneNumberFormat::NATIONAL);
2748
                if ($nationalPrefix === null || $nationalPrefix === '') {
2749
                    // If the region doesn't have a national prefix at all, we can safely return the national
2750
                    // format without worrying about a national prefix being added.
2751
                    $formattedNumber = $nationalFormat;
2752
                    break;
2753
                }
2754
                // Otherwise, we check if the original number was entered with a national prefix.
2755
                if ($this->rawInputContainsNationalPrefix(
2756
                    $number->getRawInput(),
2757
                    $nationalPrefix,
2758
                    $regionCode
2759
                )
2760
                ) {
2761
                    // If so, we can safely return the national format.
2762
                    $formattedNumber = $nationalFormat;
2763
                    break;
2764
                }
2765
                // Metadata cannot be null here because getNddPrefixForRegion() (above) returns null if
2766
                // there is no metadata for the region.
2767
                $metadata = $this->getMetadataForRegion($regionCode);
2768
                $nationalNumber = $this->getNationalSignificantNumber($number);
2769
                $formatRule = $this->chooseFormattingPatternForNumber($metadata->numberFormats(), $nationalNumber);
2770
                // The format rule could still be null here if the national number was 0 and there was no
2771
                // raw input (this should not be possible for numbers generated by the phonenumber library
2772
                // as they would also not have a country calling code and we would have exited earlier).
2773
                if ($formatRule === null) {
2774
                    $formattedNumber = $nationalFormat;
2775
                    break;
2776
                }
2777
                // When the format we apply to this number doesn't contain national prefix, we can just
2778
                // return the national format.
2779
                // TODO: Refactor the code below with the code in isNationalPrefixPresentIfRequired.
2780
                $candidateNationalPrefixRule = $formatRule->getNationalPrefixFormattingRule();
2781
                // We assume that the first-group symbol will never be _before_ the national prefix.
2782
                $indexOfFirstGroup = strpos($candidateNationalPrefixRule, '$1');
2783
                if ($indexOfFirstGroup <= 0) {
2784
                    $formattedNumber = $nationalFormat;
2785
                    break;
2786
                }
2787
                $candidateNationalPrefixRule = substr($candidateNationalPrefixRule, 0, $indexOfFirstGroup);
2788
                $candidateNationalPrefixRule = static::normalizeDigitsOnly($candidateNationalPrefixRule);
2789
                if ($candidateNationalPrefixRule === '') {
2790
                    // National prefix not used when formatting this number.
2791
                    $formattedNumber = $nationalFormat;
2792
                    break;
2793
                }
2794
                // Otherwise, we need to remove the national prefix from our output.
2795
                $numFormatCopy = new NumberFormat();
2796
                $numFormatCopy->mergeFrom($formatRule);
2797
                $numFormatCopy->clearNationalPrefixFormattingRule();
2798
                $numberFormats = [];
2799
                $numberFormats[] = $numFormatCopy;
2800
                $formattedNumber = $this->formatByPattern($number, PhoneNumberFormat::NATIONAL, $numberFormats);
2801
                break;
2802
        }
2803
        $rawInput = $number->getRawInput();
2804
        // If no digit is inserted/removed/modified as a result of our formatting, we return the
2805
        // formatted phone number; otherwise we return the raw input the user entered.
2806
        if ($formattedNumber !== null && $rawInput !== '') {
2807
            $normalizedFormattedNumber = static::normalizeDiallableCharsOnly($formattedNumber);
2808
            $normalizedRawInput = static::normalizeDiallableCharsOnly($rawInput);
2809
            if ($normalizedFormattedNumber !== $normalizedRawInput) {
2810
                $formattedNumber = $rawInput;
2811
            }
2812
        }
2813
        return $formattedNumber;
2814
    }
2815
 
2816
    /**
2817
     */
2818
    protected function hasFormattingPatternForNumber(PhoneNumber $number): bool
2819
    {
2820
        $countryCallingCode = $number->getCountryCode();
2821
        $phoneNumberRegion = $this->getRegionCodeForCountryCode($countryCallingCode);
2822
        $metadata = $this->getMetadataForRegionOrCallingCode($countryCallingCode, $phoneNumberRegion);
2823
        if ($metadata === null) {
2824
            return false;
2825
        }
2826
        $nationalNumber = $this->getNationalSignificantNumber($number);
2827
        $formatRule = $this->chooseFormattingPatternForNumber($metadata->numberFormats(), $nationalNumber);
2828
        return $formatRule !== null;
2829
    }
2830
 
2831
    /**
2832
     * Returns the national dialling prefix for a specific region. For example, this would be 1 for
2833
     * the United States, and 0 for New Zealand. Set stripNonDigits to true to strip symbols like "~"
2834
     * (which indicates a wait for a dialling tone) from the prefix returned. If no national prefix is
2835
     * present, we return null.
2836
     *
2837
     * <p>Warning: Do not use this method for do-your-own formatting - for some regions, the
2838
     * national dialling prefix is used only for certain types of numbers. Use the library's
2839
     * formatting functions to prefix the national prefix when required.
2840
     *
2841
     * @param string $regionCode the region that we want to get the dialling prefix for
2842
     * @param boolean $stripNonDigits true to strip non-digits from the national dialling prefix
2843
     * @return string|null the dialling prefix for the region denoted by regionCode
2844
     */
2845
    public function getNddPrefixForRegion(string $regionCode, bool $stripNonDigits): ?string
2846
    {
2847
        $metadata = $this->getMetadataForRegion($regionCode);
2848
        if ($metadata === null) {
2849
            return null;
2850
        }
2851
        $nationalPrefix = $metadata->getNationalPrefix();
2852
        // If no national prefix was found, we return null.
2853
        if ($nationalPrefix === null || $nationalPrefix === '') {
2854
            return null;
2855
        }
2856
        if ($stripNonDigits) {
2857
            // Note: if any other non-numeric symbols are ever used in national prefixes, these would have
2858
            // to be removed here as well.
2859
            $nationalPrefix = str_replace('~', '', $nationalPrefix);
2860
        }
2861
        return $nationalPrefix;
2862
    }
2863
 
2864
    /**
2865
     * Check if rawInput, which is assumed to be in the national format, has a national prefix. The
2866
     * national prefix is assumed to be in digits-only form.
2867
     */
2868
    protected function rawInputContainsNationalPrefix(string $rawInput, string $nationalPrefix, string $regionCode): bool
2869
    {
2870
        $normalizedNationalNumber = static::normalizeDigitsOnly($rawInput);
2871
        if (str_starts_with($normalizedNationalNumber, $nationalPrefix)) {
2872
            try {
2873
                // Some Japanese numbers (e.g. 00777123) might be mistaken to contain the national prefix
2874
                // when written without it (e.g. 0777123) if we just do prefix matching. To tackle that, we
2875
                // check the validity of the number if the assumed national prefix is removed (777123 won't
2876
                // be valid in Japan).
2877
                return $this->isValidNumber(
2878
                    $this->parse(substr($normalizedNationalNumber, mb_strlen($nationalPrefix)), $regionCode)
2879
                );
2880
            } catch (NumberParseException) {
2881
                return false;
2882
            }
2883
        }
2884
        return false;
2885
    }
2886
 
2887
    /**
2888
     * Tests whether a phone number matches a valid pattern. Note this doesn't verify the number
2889
     * is actually in use, which is impossible to tell by just looking at a number itself. It only
2890
     * verifies whether the parsed, canonicalised number is valid: not whether a particular series of
2891
     * digits entered by the user is diallable from the region provided when parsing. For example, the
2892
     * number +41 (0) 78 927 2696 can be parsed into a number with country code "41" and national
2893
     * significant number "789272696". This is valid, while the original string is not diallable.
2894
     *
2895
     * @param PhoneNumber $number the phone number that we want to validate
2896
     * @return boolean that indicates whether the number is of a valid pattern
2897
     */
2898
    public function isValidNumber(PhoneNumber $number): bool
2899
    {
2900
        $regionCode = $this->getRegionCodeForNumber($number);
2901
 
2902
        if ($regionCode === null) {
2903
            return false;
2904
        }
2905
 
2906
        return $this->isValidNumberForRegion($number, $regionCode);
2907
    }
2908
 
2909
    /**
2910
     * Tests whether a phone number is valid for a certain region. Note this doesn't verify the number
2911
     * is actually in use, which is impossible to tell by just looking at a number itself. If the
2912
     * country calling code is not the same as the country calling code for the region, this
2913
     * immediately exits with false. After this, the specific number pattern rules for the region are
2914
     * examined. This is useful for determining for example whether a particular number is valid for
2915
     * Canada, rather than just a valid NANPA number.
2916
     * Warning: In most cases, you want to use {@link #isValidNumber} instead. For example, this
2917
     * method will mark numbers from British Crown dependencies such as the Isle of Man as invalid for
2918
     * the region "GB" (United Kingdom), since it has its own region code, "IM", which may be
2919
     * undesirable.
2920
     *
2921
     * @param PhoneNumber $number the phone number that we want to validate
2922
     * @param string $regionCode the region that we want to validate the phone number for
2923
     * @return boolean that indicates whether the number is of a valid pattern
2924
     */
2925
    public function isValidNumberForRegion(PhoneNumber $number, string $regionCode): bool
2926
    {
2927
        $countryCode = $number->getCountryCode();
2928
        $metadata = $this->getMetadataForRegionOrCallingCode($countryCode, $regionCode);
2929
        if (($metadata === null) ||
2930
            (static::REGION_CODE_FOR_NON_GEO_ENTITY !== $regionCode &&
2931
                $countryCode !== $this->getCountryCodeForValidRegion($regionCode))
2932
        ) {
2933
            // Either the region code was invalid, or the country calling code for this number does not
2934
            // match that of the region code.
2935
            return false;
2936
        }
2937
        $nationalSignificantNumber = $this->getNationalSignificantNumber($number);
2938
 
2939
        return $this->getNumberTypeHelper($nationalSignificantNumber, $metadata) !== PhoneNumberType::UNKNOWN;
2940
    }
2941
 
2942
    /**
2943
     * Parses a string and returns it as a phone number in proto buffer format. The method is quite
2944
     * lenient and looks for a number in the input text (raw input) and does not check whether the
2945
     * string is definitely only a phone number. To do this, it ignores punctuation and white-space,
2946
     * as well as any text before the number (e.g. a leading “Tel: ”) and trims the non-number bits.
2947
     * It will accept a number in any format (E164, national, international etc), assuming it can
2948
     * interpreted with the defaultRegion supplied. It also attempts to convert any alpha characters
2949
     * into digits if it thinks this is a vanity number of the type "1800 MICROSOFT".
2950
     *
2951
     * <p> This method will throw a {@link NumberParseException} if the number is not considered to
2952
     * be a possible number. Note that validation of whether the number is actually a valid number
2953
     * for a particular region is not performed. This can be done separately with {@link #isValidNumber}.
2954
     *
2955
     * <p> Note this method canonicalizes the phone number such that different representations can be
2956
     * easily compared, no matter what form it was originally entered in (e.g. national,
2957
     * international). If you want to record context about the number being parsed, such as the raw
2958
     * input that was entered, how the country code was derived etc. then call {@link
2959
     * #parseAndKeepRawInput} instead.
2960
     *
2961
     * @param string $numberToParse number that we are attempting to parse. This can contain formatting
2962
     *                          such as +, ( and -, as well as a phone number extension.
2963
     * @param string|null $defaultRegion region that we are expecting the number to be from. This is only used
2964
     *                          if the number being parsed is not written in international format.
2965
     *                          The country_code for the number in this case would be stored as that
2966
     *                          of the default region supplied. If the number is guaranteed to
2967
     *                          start with a '+' followed by the country calling code, then
2968
     *                          "ZZ" or null can be supplied.
2969
     * @return PhoneNumber a phone number proto buffer filled with the parsed number
2970
     * @throws NumberParseException  if the string is not considered to be a viable phone number (e.g.
2971
     *                               too few or too many digits) or if no default region was supplied
2972
     *                               and the number is not in international format (does not start
2973
     *                               with +)
2974
     */
2975
    public function parse(string $numberToParse, ?string $defaultRegion = null, ?PhoneNumber $phoneNumber = null, bool $keepRawInput = false): PhoneNumber
2976
    {
2977
        if ($phoneNumber === null) {
2978
            $phoneNumber = new PhoneNumber();
2979
        }
2980
        $this->parseHelper($numberToParse, $defaultRegion, $keepRawInput, true, $phoneNumber);
2981
        return $phoneNumber;
2982
    }
2983
 
2984
    /**
2985
     * Formats a phone number in the specified format using client-defined formatting rules. Note that
2986
     * if the phone number has a country calling code of zero or an otherwise invalid country calling
2987
     * code, we cannot work out things like whether there should be a national prefix applied, or how
2988
     * to format extensions, so we return the national significant number with no formatting applied.
2989
     *
2990
     * @param PhoneNumber $number the phone number to be formatted
2991
     * @param int $numberFormat the format the phone number should be formatted into
2992
     * @param NumberFormat[] $userDefinedFormats formatting rules specified by clients
2993
     * @return String the formatted phone number
2994
     */
2995
    public function formatByPattern(PhoneNumber $number, int $numberFormat, array $userDefinedFormats): string
2996
    {
2997
        $countryCallingCode = $number->getCountryCode();
2998
        $nationalSignificantNumber = $this->getNationalSignificantNumber($number);
2999
        if (!$this->hasValidCountryCallingCode($countryCallingCode)) {
3000
            return $nationalSignificantNumber;
3001
        }
3002
        // Note getRegionCodeForCountryCode() is used because formatting information for regions which
3003
        // share a country calling code is contained by only one region for performance reasons. For
3004
        // example, for NANPA regions it will be contained in the metadata for US.
3005
        $regionCode = $this->getRegionCodeForCountryCode($countryCallingCode);
3006
        // Metadata cannot be null because the country calling code is valid.
3007
        $metadata = $this->getMetadataForRegionOrCallingCode($countryCallingCode, $regionCode);
3008
 
3009
        $formattedNumber = '';
3010
 
3011
        $formattingPattern = $this->chooseFormattingPatternForNumber($userDefinedFormats, $nationalSignificantNumber);
3012
        if ($formattingPattern === null) {
3013
            // If no pattern above is matched, we format the number as a whole.
3014
            $formattedNumber .= $nationalSignificantNumber;
3015
        } else {
3016
            $numFormatCopy = new NumberFormat();
3017
            // Before we do a replacement of the national prefix pattern $NP with the national prefix, we
3018
            // need to copy the rule so that subsequent replacements for different numbers have the
3019
            // appropriate national prefix.
3020
            $numFormatCopy->mergeFrom($formattingPattern);
3021
            $nationalPrefixFormattingRule = $formattingPattern->getNationalPrefixFormattingRule();
3022
            if ($nationalPrefixFormattingRule !== '') {
3023
                $nationalPrefix = $metadata->getNationalPrefix();
3024
                if (isset($nationalPrefix) && $nationalPrefix !== '') {
3025
                    // Replace $NP with national prefix and $FG with the first group ($1).
3026
                    $nationalPrefixFormattingRule = str_replace(
3027
                        [static::NP_STRING, static::FG_STRING],
3028
                        [$nationalPrefix, '$1'],
3029
                        $nationalPrefixFormattingRule
3030
                    );
3031
                    $numFormatCopy->setNationalPrefixFormattingRule($nationalPrefixFormattingRule);
3032
                } else {
3033
                    // We don't want to have a rule for how to format the national prefix if there isn't one.
3034
                    $numFormatCopy->clearNationalPrefixFormattingRule();
3035
                }
3036
            }
3037
            $formattedNumber .= $this->formatNsnUsingPattern($nationalSignificantNumber, $numFormatCopy, $numberFormat);
3038
        }
3039
        $this->maybeAppendFormattedExtension($number, $metadata, $numberFormat, $formattedNumber);
3040
        $this->prefixNumberWithCountryCallingCode($countryCallingCode, $numberFormat, $formattedNumber);
3041
        return $formattedNumber;
3042
    }
3043
 
3044
    /**
3045
     * Gets a valid number for the specified region.
3046
     *
3047
     * @param string $regionCode the region for which an example number is needed
3048
     * @return PhoneNumber|null a valid fixed-line number for the specified region. Returns null when the metadata
3049
     *    does not contain such information, or the region 001 is passed in. For 001 (representing
3050
     *    non-geographical numbers), call {@link #getExampleNumberForNonGeoEntity} instead.
3051
     */
3052
    public function getExampleNumber(string $regionCode): ?PhoneNumber
3053
    {
3054
        return $this->getExampleNumberForType($regionCode, PhoneNumberType::FIXED_LINE);
3055
    }
3056
 
3057
    /**
3058
     * Gets an invalid number for the specified region. This is useful for unit-testing purposes,
3059
     * where you want to test what will happen with an invalid number. Note that the number that is
3060
     * returned will always be able to be parsed and will have the correct country code. It may also
3061
     * be a valid *short* number/code for this region. Validity checking such numbers is handled with
3062
     * {@link ShortNumberInfo}.
3063
     *
3064
     * @param string $regionCode The region for which an example number is needed
3065
     * @return PhoneNumber|null An invalid number for the specified region. Returns null when an unsupported region
3066
     * or the region 001 (Earth) is passed in.
3067
     */
3068
    public function getInvalidExampleNumber(string $regionCode): ?PhoneNumber
3069
    {
3070
        if (!$this->isValidRegionCode($regionCode)) {
3071
            return null;
3072
        }
3073
 
3074
        // We start off with a valid fixed-line number since every country supports this. Alternatively
3075
        // we could start with a different number type, since fixed-line numbers typically have a wide
3076
        // breadth of valid number lengths and we may have to make it very short before we get an
3077
        // invalid number.
3078
 
3079
        $desc = $this->getNumberDescByType($this->getMetadataForRegion($regionCode), PhoneNumberType::FIXED_LINE);
3080
 
3081
        if ($desc->getExampleNumber() === '') {
3082
            // This shouldn't happen; we have a test for this.
3083
            return null;
3084
        }
3085
 
3086
        $exampleNumber = $desc->getExampleNumber();
3087
 
3088
        // Try and make the number invalid. We do this by changing the length. We try reducing the
3089
        // length of the number, since currently no region has a number that is the same length as
3090
        // MIN_LENGTH_FOR_NSN. This is probably quicker than making the number longer, which is another
3091
        // alternative. We could also use the possible number pattern to extract the possible lengths of
3092
        // the number to make this faster, but this method is only for unit-testing so simplicity is
3093
        // preferred to performance.  We don't want to return a number that can't be parsed, so we check
3094
        // the number is long enough. We try all possible lengths because phone number plans often have
3095
        // overlapping prefixes so the number 123456 might be valid as a fixed-line number, and 12345 as
3096
        // a mobile number. It would be faster to loop in a different order, but we prefer numbers that
3097
        // look closer to real numbers (and it gives us a variety of different lengths for the resulting
3098
        // phone numbers - otherwise they would all be MIN_LENGTH_FOR_NSN digits long.)
3099
        for ($phoneNumberLength = mb_strlen($exampleNumber) - 1; $phoneNumberLength >= static::MIN_LENGTH_FOR_NSN; $phoneNumberLength--) {
3100
            $numberToTry = mb_substr($exampleNumber, 0, $phoneNumberLength);
3101
            try {
3102
                $possiblyValidNumber = $this->parse($numberToTry, $regionCode);
3103
                if (!$this->isValidNumber($possiblyValidNumber)) {
3104
                    return $possiblyValidNumber;
3105
                }
3106
            } catch (NumberParseException) {
3107
                // Shouldn't happen: we have already checked the length, we know example numbers have
3108
                // only valid digits, and we know the region code is fine.
3109
            }
3110
        }
3111
        // We have a test to check that this doesn't happen for any of our supported regions.
3112
        return null;
3113
    }
3114
 
3115
    /**
3116
     * Gets a valid number for the specified region and number type.
3117
     *
3118
     * @param string|int $regionCodeOrType the region for which an example number is needed
3119
     * @param int $type the PhoneNumberType of number that is needed
3120
     * @return PhoneNumber|null a valid number for the specified region and type. Returns null when the metadata
3121
     *     does not contain such information or if an invalid region or region 001 was entered.
3122
     *     For 001 (representing non-geographical numbers), call
3123
     *     {@link #getExampleNumberForNonGeoEntity} instead.
3124
     *
3125
     * If $regionCodeOrType is the only parameter supplied, then a valid number for the specified number type
3126
     * will be returned that may belong to any country.
3127
     */
3128
    public function getExampleNumberForType(string|int $regionCodeOrType, ?int $type = null): ?PhoneNumber
3129
    {
3130
        if (is_int($regionCodeOrType) && $type === null) {
3131
            /*
3132
             * Gets a valid number for the specified number type (it may belong to any country).
3133
             */
3134
            foreach ($this->getSupportedRegions() as $regionCode) {
3135
                $exampleNumber = $this->getExampleNumberForType($regionCode, $regionCodeOrType);
3136
                if ($exampleNumber !== null) {
3137
                    return $exampleNumber;
3138
                }
3139
            }
3140
 
3141
            // If there wasn't an example number for a region, try the non-geographical entities.
3142
            foreach ($this->getSupportedGlobalNetworkCallingCodes() as $countryCallingCode) {
3143
                $desc = $this->getNumberDescByType($this->getMetadataForNonGeographicalRegion($countryCallingCode), $regionCodeOrType);
3144
                try {
3145
                    if ($desc->getExampleNumber() !== '') {
3146
                        return $this->parse('+' . $countryCallingCode . $desc->getExampleNumber(), static::UNKNOWN_REGION);
3147
                    }
3148
                } catch (NumberParseException) {
3149
                    // noop
3150
                }
3151
            }
3152
            // There are no example numbers of this type for any country in the library.
3153
            return null;
3154
        }
3155
 
3156
        if (is_int($regionCodeOrType)) {
3157
            // This should be a string by now
3158
            return null;
3159
        }
3160
 
3161
        // Check the region code is valid.
3162
        if (!$this->isValidRegionCode($regionCodeOrType)) {
3163
            return null;
3164
        }
3165
        $desc = $this->getNumberDescByType($this->getMetadataForRegion($regionCodeOrType), $type);
3166
        try {
3167
            if ($desc->hasExampleNumber()) {
3168
                return $this->parse($desc->getExampleNumber(), $regionCodeOrType);
3169
            }
3170
        } catch (NumberParseException) {
3171
            // noop
3172
        }
3173
        return null;
3174
    }
3175
 
3176
    /**
3177
     * @param int $type PhoneNumberType
3178
     */
3179
    protected function getNumberDescByType(PhoneMetadata $metadata, int $type): PhoneNumberDesc
3180
    {
3181
        return match ($type) {
3182
            PhoneNumberType::PREMIUM_RATE => $metadata->getPremiumRate(),
3183
            PhoneNumberType::TOLL_FREE => $metadata->getTollFree(),
3184
            PhoneNumberType::MOBILE => $metadata->getMobile(),
3185
            PhoneNumberType::FIXED_LINE, PhoneNumberType::FIXED_LINE_OR_MOBILE => $metadata->getFixedLine(),
3186
            PhoneNumberType::SHARED_COST => $metadata->getSharedCost(),
3187
            PhoneNumberType::VOIP => $metadata->getVoip(),
3188
            PhoneNumberType::PERSONAL_NUMBER => $metadata->getPersonalNumber(),
3189
            PhoneNumberType::PAGER => $metadata->getPager(),
3190
            PhoneNumberType::UAN => $metadata->getUan(),
3191
            PhoneNumberType::VOICEMAIL => $metadata->getVoicemail(),
3192
            default => $metadata->getGeneralDesc(),
3193
        };
3194
    }
3195
 
3196
    /**
3197
     * Gets a valid number for the specified country calling code for a non-geographical entity.
3198
     *
3199
     * @param int $countryCallingCode the country calling code for a non-geographical entity
3200
     * @return PhoneNumber|null a valid number for the non-geographical entity. Returns null when the metadata
3201
     *    does not contain such information, or the country calling code passed in does not belong
3202
     *    to a non-geographical entity.
3203
     */
3204
    public function getExampleNumberForNonGeoEntity(int $countryCallingCode): ?PhoneNumber
3205
    {
3206
        $metadata = $this->getMetadataForNonGeographicalRegion($countryCallingCode);
3207
        if ($metadata !== null) {
3208
            // For geographical entities, fixed-line data is always present. However, for non-geographical
3209
            // entities, this is not the case, so we have to go through different types to find the
3210
            // example number. We don't check fixed-line or personal number since they aren't used by
3211
            // non-geographical entities (if this changes, a unit-test will catch this.)
3212
            /** @var PhoneNumberDesc[] $list */
3213
            $list = [
3214
                $metadata->getMobile(),
3215
                $metadata->getTollFree(),
3216
                $metadata->getSharedCost(),
3217
                $metadata->getVoip(),
3218
                $metadata->getVoicemail(),
3219
                $metadata->getUan(),
3220
                $metadata->getPremiumRate(),
3221
            ];
3222
            foreach ($list as $desc) {
3223
                try {
3224
                    if ($desc !== null && $desc->hasExampleNumber()) {
3225
                        return $this->parse('+' . $countryCallingCode . $desc->getExampleNumber(), self::UNKNOWN_REGION);
3226
                    }
3227
                } catch (NumberParseException) {
3228
                    // noop
3229
                }
3230
            }
3231
        }
3232
        return null;
3233
    }
3234
 
3235
 
3236
    /**
3237
     * Takes two phone numbers and compares them for equality.
3238
     *
3239
     * <p>Returns EXACT_MATCH if the country_code, NSN, presence of a leading zero
3240
     * for Italian numbers and any extension present are the same. Returns NSN_MATCH
3241
     * if either or both has no region specified, and the NSNs and extensions are
3242
     * the same. Returns SHORT_NSN_MATCH if either or both has no region specified,
3243
     * or the region specified is the same, and one NSN could be a shorter version
3244
     * of the other number. This includes the case where one has an extension
3245
     * specified, and the other does not. Returns NO_MATCH otherwise. For example,
3246
     * the numbers +1 345 657 1234 and 657 1234 are a SHORT_NSN_MATCH. The numbers
3247
     * +1 345 657 1234 and 345 657 are a NO_MATCH.
3248
     *
3249
     * @param $firstNumberIn PhoneNumber|string First number to compare. If it is a
3250
     * string it can contain formatting, and can have country calling code specified
3251
     * with + at the start.
3252
     * @param $secondNumberIn PhoneNumber|string Second number to compare. If it is a
3253
     * string it can contain formatting, and can have country calling code specified
3254
     * with + at the start.
3255
     * @throws \InvalidArgumentException
3256
     * @return int {MatchType} NOT_A_NUMBER, NO_MATCH,
3257
     */
3258
    public function isNumberMatch(PhoneNumber|string $firstNumberIn, PhoneNumber|string $secondNumberIn): int
3259
    {
3260
        if (is_string($firstNumberIn) && is_string($secondNumberIn)) {
3261
            try {
3262
                $firstNumberAsProto = $this->parse($firstNumberIn, static::UNKNOWN_REGION);
3263
                return $this->isNumberMatch($firstNumberAsProto, $secondNumberIn);
3264
            } catch (NumberParseException $e) {
3265
                if ($e->getErrorType() === NumberParseException::INVALID_COUNTRY_CODE) {
3266
                    try {
3267
                        $secondNumberAsProto = $this->parse($secondNumberIn, static::UNKNOWN_REGION);
3268
                        return $this->isNumberMatch($secondNumberAsProto, $firstNumberIn);
3269
                    } catch (NumberParseException $e2) {
3270
                        if ($e2->getErrorType() === NumberParseException::INVALID_COUNTRY_CODE) {
3271
                            try {
3272
                                $firstNumberProto = new PhoneNumber();
3273
                                $secondNumberProto = new PhoneNumber();
3274
                                $this->parseHelper($firstNumberIn, null, false, false, $firstNumberProto);
3275
                                $this->parseHelper($secondNumberIn, null, false, false, $secondNumberProto);
3276
                                return $this->isNumberMatch($firstNumberProto, $secondNumberProto);
3277
                            } catch (NumberParseException) {
3278
                                // Fall through and return MatchType::NOT_A_NUMBER
3279
                            }
3280
                        }
3281
                    }
3282
                }
3283
            }
3284
            return MatchType::NOT_A_NUMBER;
3285
        }
3286
        if ($firstNumberIn instanceof PhoneNumber && is_string($secondNumberIn)) {
3287
            // First see if the second number has an implicit country calling code, by attempting to parse
3288
            // it.
3289
            try {
3290
                $secondNumberAsProto = $this->parse($secondNumberIn, static::UNKNOWN_REGION);
3291
                return $this->isNumberMatch($firstNumberIn, $secondNumberAsProto);
3292
            } catch (NumberParseException $e) {
3293
                if ($e->getErrorType() === NumberParseException::INVALID_COUNTRY_CODE) {
3294
                    // The second number has no country calling code. EXACT_MATCH is no longer possible.
3295
                    // We parse it as if the region was the same as that for the first number, and if
3296
                    // EXACT_MATCH is returned, we replace this with NSN_MATCH.
3297
                    $firstNumberRegion = $this->getRegionCodeForCountryCode($firstNumberIn->getCountryCode());
3298
                    try {
3299
                        if ($firstNumberRegion !== static::UNKNOWN_REGION) {
3300
                            $secondNumberWithFirstNumberRegion = $this->parse($secondNumberIn, $firstNumberRegion);
3301
                            $match = $this->isNumberMatch($firstNumberIn, $secondNumberWithFirstNumberRegion);
3302
                            if ($match === MatchType::EXACT_MATCH) {
3303
                                return MatchType::NSN_MATCH;
3304
                            }
3305
                            return $match;
3306
                        }
3307
 
3308
                        // If the first number didn't have a valid country calling code, then we parse the
3309
                        // second number without one as well.
3310
                        $secondNumberProto = new PhoneNumber();
3311
                        $this->parseHelper($secondNumberIn, null, false, false, $secondNumberProto);
3312
                        return $this->isNumberMatch($firstNumberIn, $secondNumberProto);
3313
                    } catch (NumberParseException) {
3314
                        // Fall-through to return NOT_A_NUMBER.
3315
                    }
3316
                }
3317
            }
3318
        }
3319
        if ($firstNumberIn instanceof PhoneNumber && $secondNumberIn instanceof PhoneNumber) {
3320
            // We only care about the fields that uniquely define a number, so we copy these across
3321
            // explicitly.
3322
            $firstNumber = self::copyCoreFieldsOnly($firstNumberIn);
3323
            $secondNumber = self::copyCoreFieldsOnly($secondNumberIn);
3324
 
3325
            // Early exit if both had extensions and these are different.
3326
            if ($firstNumber->hasExtension() && $secondNumber->hasExtension() &&
3327
                $firstNumber->getExtension() !== $secondNumber->getExtension()
3328
            ) {
3329
                return MatchType::NO_MATCH;
3330
            }
3331
 
3332
            $firstNumberCountryCode = $firstNumber->getCountryCode();
3333
            $secondNumberCountryCode = $secondNumber->getCountryCode();
3334
            // Both had country_code specified.
3335
            if ($firstNumberCountryCode !== 0 && $secondNumberCountryCode !== 0) {
3336
                if ($firstNumber->equals($secondNumber)) {
3337
                    return MatchType::EXACT_MATCH;
3338
                }
3339
 
3340
                if ($firstNumberCountryCode === $secondNumberCountryCode &&
3341
                    $this->isNationalNumberSuffixOfTheOther($firstNumber, $secondNumber)) {
3342
                    // A SHORT_NSN_MATCH occurs if there is a difference because of the presence or absence of
3343
                    // an 'Italian leading zero', the presence or absence of an extension, or one NSN being a
3344
                    // shorter variant of the other.
3345
                    return MatchType::SHORT_NSN_MATCH;
3346
                }
3347
                // This is not a match.
3348
                return MatchType::NO_MATCH;
3349
            }
3350
            // Checks cases where one or both country_code fields were not specified. To make equality
3351
            // checks easier, we first set the country_code fields to be equal.
3352
            $firstNumber->setCountryCode($secondNumberCountryCode);
3353
            // If all else was the same, then this is an NSN_MATCH.
3354
            if ($firstNumber->equals($secondNumber)) {
3355
                return MatchType::NSN_MATCH;
3356
            }
3357
            if ($this->isNationalNumberSuffixOfTheOther($firstNumber, $secondNumber)) {
3358
                return MatchType::SHORT_NSN_MATCH;
3359
            }
3360
            return MatchType::NO_MATCH;
3361
        }
3362
        return MatchType::NOT_A_NUMBER;
3363
    }
3364
 
3365
    /**
3366
     * Returns true when one national number is the suffix of the other or both are the same.
3367
     */
3368
    protected function isNationalNumberSuffixOfTheOther(PhoneNumber $firstNumber, PhoneNumber $secondNumber): bool
3369
    {
3370
        $firstNumberNationalNumber = trim((string) $firstNumber->getNationalNumber());
3371
        $secondNumberNationalNumber = trim((string) $secondNumber->getNationalNumber());
3372
        return str_ends_with($firstNumberNationalNumber, $secondNumberNationalNumber) ||
3373
        str_ends_with($secondNumberNationalNumber, $firstNumberNationalNumber);
3374
    }
3375
 
3376
    /**
3377
     * Returns true if the supplied region supports mobile number portability. Returns false for
3378
     * invalid, unknown or regions that don't support mobile number portability.
3379
     *
3380
     * @param string $regionCode the region for which we want to know whether it supports mobile number
3381
     *                    portability or not.
3382
     */
3383
    public function isMobileNumberPortableRegion(string $regionCode): bool
3384
    {
3385
        $metadata = $this->getMetadataForRegion($regionCode);
3386
        if ($metadata === null) {
3387
            return false;
3388
        }
3389
 
3390
        return $metadata->isMobileNumberPortableRegion();
3391
    }
3392
 
3393
    /**
3394
     * Check whether a phone number is a possible number given a number in the form of a string, and
3395
     * the region where the number could be dialed from. It provides a more lenient check than
3396
     * {@link #isValidNumber}. See {@link #isPossibleNumber(PhoneNumber)} for details.
3397
     *
3398
     * Convenience wrapper around {@link #isPossibleNumberWithReason}. Instead of returning the reason
3399
     * for failure, this method returns a boolean value.
3400
     * For failure, this method returns true if the number is either a possible fully-qualified number
3401
     * (containing the area code and country code), or if the number could be a possible local number
3402
     * (with a country code, but missing an area code). Local numbers are considered possible if they
3403
     * could be possibly dialled in this format: if the area code is needed for a call to connect, the
3404
     * number is not considered possible without it.
3405
     *
3406
     * Note: There are two ways to call this method.
3407
     *
3408
     * isPossibleNumber(PhoneNumber $numberObject)
3409
     * isPossibleNumber(string '+441174960126', string 'GB')
3410
     *
3411
     * @param PhoneNumber|string $number the number that needs to be checked, in the form of a string
3412
     * @param string|null $regionDialingFrom the region that we are expecting the number to be dialed from.
3413
     *     Note this is different from the region where the number belongs.  For example, the number
3414
     *     +1 650 253 0000 is a number that belongs to US. When written in this form, it can be
3415
     *     dialed from any region. When it is written as 00 1 650 253 0000, it can be dialed from any
3416
     *     region which uses an international dialling prefix of 00. When it is written as
3417
     *     650 253 0000, it can only be dialed from within the US, and when written as 253 0000, it
3418
     *     can only be dialed from within a smaller area in the US (Mountain View, CA, to be more
3419
     *     specific).
3420
     * @return boolean true if the number is possible
3421
     */
3422
    public function isPossibleNumber(PhoneNumber|string $number, ?string $regionDialingFrom = null): bool
3423
    {
3424
        if (is_string($number)) {
3425
            try {
3426
                return $this->isPossibleNumber($this->parse($number, $regionDialingFrom));
3427
            } catch (NumberParseException) {
3428
                return false;
3429
            }
3430
        } else {
3431
            $result = $this->isPossibleNumberWithReason($number);
3432
            return $result === ValidationResult::IS_POSSIBLE
3433
                || $result === ValidationResult::IS_POSSIBLE_LOCAL_ONLY;
3434
        }
3435
    }
3436
 
3437
 
3438
    /**
3439
     * Check whether a phone number is a possible number. It provides a more lenient check than
3440
     * {@link #isValidNumber} in the following sense:
3441
     * <ol>
3442
     *   <li> It only checks the length of phone numbers. In particular, it doesn't check starting
3443
     *        digits of the number.
3444
     *   <li> It doesn't attempt to figure out the type of the number, but uses general rules which
3445
     *        applies to all types of phone numbers in a region. Therefore, it is much faster than
3446
     *        isValidNumber.
3447
     *   <li> For some numbers (particularly fixed-line), many regions have the concept of area code,
3448
     *        which together with subscriber number constitute the national significant number. It is
3449
     *        sometimes okay to dial only the subscriber number when dialing in the same area. This
3450
     *        function will return IS_POSSIBLE_LOCAL_ONLY if the subscriber-number-only version is
3451
     *        passed in. On the other hand, because isValidNumber validates using information on both
3452
     *        starting digits (for fixed line numbers, that would most likely be area codes) and
3453
     *        length (obviously includes the length of area codes for fixed line numbers), it will
3454
     *        return false for the subscriber-number-only version.
3455
     * </ol>
3456
     * There is a known <a href="https://issuetracker.google.com/issues/335892662">issue</a> with this
3457
     * method: if a number is possible only in a certain region among several regions that share the
3458
     * same country calling code, this method will consider only the "main" region. For example,
3459
     * +1310xxxx are valid numbers in Canada. However, they are not possible in the US. As a result,
3460
     * this method will return IS_POSSIBLE_LOCAL_ONLY for +1310xxxx.
3461
     *
3462
     * @param PhoneNumber $number the number that needs to be checked
3463
     * @return int a ValidationResult object which indicates whether the number is possible
3464
     */
3465
    public function isPossibleNumberWithReason(PhoneNumber $number): int
3466
    {
3467
        return $this->isPossibleNumberForTypeWithReason($number, PhoneNumberType::UNKNOWN);
3468
    }
3469
 
3470
    /**
3471
     * Check whether a phone number is a possible number of a particular type. For types that don't
3472
     * exist in a particular region, this will return a result that isn't so useful; it is recommended
3473
     * that you use {@link #getSupportedTypesForRegion} or {@link #getSupportedTypesForNonGeoEntity}
3474
     * respectively before calling this method to determine whether you should call it for this number
3475
     * at all.
3476
     *
3477
     * This provides a more lenient check than {@link #isValidNumber} in the following sense:
3478
     *
3479
     * <ol>
3480
     *   <li> It only checks the length of phone numbers. In particular, it doesn't check starting
3481
     *        digits of the number.
3482
     *   <li> For some numbers (particularly fixed-line), many regions have the concept of area code,
3483
     *        which together with subscriber number constitute the national significant number. It is
3484
     *        sometimes okay to dial only the subscriber number when dialing in the same area. This
3485
     *        function will return IS_POSSIBLE_LOCAL_ONLY if the subscriber-number-only version is
3486
     *        passed in. On the other hand, because isValidNumber validates using information on both
3487
     *        starting digits (for fixed line numbers, that would most likely be area codes) and
3488
     *        length (obviously includes the length of area codes for fixed line numbers), it will
3489
     *        return false for the subscriber-number-only version.
3490
     * </ol>
3491
     *
3492
     * There is a known <a href="https://issuetracker.google.com/issues/335892662">issue</a> with this
3493
     * method: if a number is possible only in a certain region among several regions that share the
3494
     * same country calling code, this method will consider only the "main" region. For example,
3495
     * +1310xxxx are valid numbers in Canada. However, they are not possible in the US. As a result,
3496
     * this method will return IS_POSSIBLE_LOCAL_ONLY for +1310xxxx.
3497
     *
3498
     * @param PhoneNumber $number the number that needs to be checked
3499
     * @param int $type the PhoneNumberType we are interested in
3500
     * @return int a ValidationResult object which indicates whether the number is possible
3501
     */
3502
    public function isPossibleNumberForTypeWithReason(PhoneNumber $number, int $type): int
3503
    {
3504
        $nationalNumber = $this->getNationalSignificantNumber($number);
3505
        $countryCode = $number->getCountryCode();
3506
 
3507
        // Note: For regions that share a country calling code, like NANPA numbers, we just use the
3508
        // rules from the default region (US in this case) since the getRegionCodeForNumber will not
3509
        // work if the number is possible but not valid. There is in fact one country calling code (290)
3510
        // where the possible number pattern differs between various regions (Saint Helena and Tristan
3511
        // da Cuñha), but this is handled by putting all possible lengths for any country with this
3512
        // country calling code in the metadata for the default region in this case.
3513
        if (!$this->hasValidCountryCallingCode($countryCode)) {
3514
            return ValidationResult::INVALID_COUNTRY_CODE;
3515
        }
3516
 
3517
        $regionCode = $this->getRegionCodeForCountryCode($countryCode);
3518
        // Metadata cannot be null because the country calling code is valid.
3519
        $metadata = $this->getMetadataForRegionOrCallingCode($countryCode, $regionCode);
3520
        return $this->testNumberLength($nationalNumber, $metadata, $type);
3521
    }
3522
 
3523
    /**
3524
     * Attempts to extract a valid number from a phone number that is too long to be valid, and resets
3525
     * the PhoneNumber object passed in to that valid version. If no valid number could be extracted,
3526
     * the PhoneNumber object passed in will not be modified.
3527
     *
3528
     * @param PhoneNumber $number a PhoneNumber object which contains a number that is too long to be valid.
3529
     * @return boolean true if a valid phone number can be successfully extracted.
3530
     */
3531
    public function truncateTooLongNumber(PhoneNumber $number): bool
3532
    {
3533
        if ($this->isValidNumber($number)) {
3534
            return true;
3535
        }
3536
        $numberCopy = new PhoneNumber();
3537
        $numberCopy->mergeFrom($number);
3538
        $nationalNumber = $number->getNationalNumber();
3539
        do {
3540
            $nationalNumber = substr($nationalNumber, 0, -1);
3541
            $numberCopy->setNationalNumber($nationalNumber);
3542
            if ($nationalNumber === '0' || $this->isPossibleNumberWithReason($numberCopy) === ValidationResult::TOO_SHORT) {
3543
                return false;
3544
            }
3545
        } while (!$this->isValidNumber($numberCopy));
3546
        $number->setNationalNumber($nationalNumber);
3547
        return true;
3548
    }
3549
}