Completed
Push — upstream-8.4.1 ( 022db7 )
by Joshua
09:58
created

PhoneNumberUtil::isPossibleNumber()   B

Complexity

Conditions 5
Paths 4

Size

Total Lines 14
Code Lines 10

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
c 0
b 0
f 0
dl 0
loc 14
rs 8.8571
cc 5
eloc 10
nc 4
nop 2
1
<?php
2
3
namespace libphonenumber;
4
5
use libphonenumber\Leniency\AbstractLeniency;
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
 *
19
 * @author Shaopeng Jia
20
 * @see https://github.com/googlei18n/libphonenumber
21
 */
22
class PhoneNumberUtil
23
{
24
    /** Flags to use when compiling regular expressions for phone numbers */
25
    const REGEX_FLAGS = 'ui'; //Unicode and case insensitive
26
    // The minimum and maximum length of the national significant number.
27
    const MIN_LENGTH_FOR_NSN = 2;
28
    // The ITU says the maximum length should be 15, but we have found longer numbers in Germany.
29
    const MAX_LENGTH_FOR_NSN = 17;
30
31
    // We don't allow input strings for parsing to be longer than 250 chars. This prevents malicious
32
    // input from overflowing the regular-expression engine.
33
    const MAX_INPUT_STRING_LENGTH = 250;
34
35
    // The maximum length of the country calling code.
36
    const MAX_LENGTH_COUNTRY_CODE = 3;
37
38
    const REGION_CODE_FOR_NON_GEO_ENTITY = "001";
39
    const META_DATA_FILE_PREFIX = 'PhoneNumberMetadata';
40
    const TEST_META_DATA_FILE_PREFIX = 'PhoneNumberMetadataForTesting';
41
42
    // Region-code for the unknown region.
43
    const UNKNOWN_REGION = "ZZ";
44
45
    const NANPA_COUNTRY_CODE = 1;
46
    /*
47
     * The prefix that needs to be inserted in front of a Colombian landline number when dialed from
48
     * a mobile number in Colombia.
49
     */
50
    const COLOMBIA_MOBILE_TO_FIXED_LINE_PREFIX = "3";
51
    // The PLUS_SIGN signifies the international prefix.
52
    const PLUS_SIGN = '+';
53
    const PLUS_CHARS = '++';
54
    const STAR_SIGN = '*';
55
56
    const RFC3966_EXTN_PREFIX = ";ext=";
57
    const RFC3966_PREFIX = "tel:";
58
    const RFC3966_PHONE_CONTEXT = ";phone-context=";
59
    const RFC3966_ISDN_SUBADDRESS = ";isub=";
60
61
    // We use this pattern to check if the phone number has at least three letters in it - if so, then
62
    // we treat it as a number where some phone-number digits are represented by letters.
63
    const VALID_ALPHA_PHONE_PATTERN = "(?:.*?[A-Za-z]){3}.*";
64
    // We accept alpha characters in phone numbers, ASCII only, upper and lower case.
65
    const VALID_ALPHA = "A-Za-z";
66
67
68
    // Default extension prefix to use when formatting. This will be put in front of any extension
69
    // component of the number, after the main national number is formatted. For example, if you wish
70
    // the default extension formatting to be " extn: 3456", then you should specify " extn: " here
71
    // as the default extension prefix. This can be overridden by region-specific preferences.
72
    const DEFAULT_EXTN_PREFIX = " ext. ";
73
74
    // Regular expression of acceptable punctuation found in phone numbers. This excludes punctuation
75
    // found as a leading character only.
76
    // This consists of dash characters, white space characters, full stops, slashes,
77
    // square brackets, parentheses and tildes. It also includes the letter 'x' as that is found as a
78
    // placeholder for carrier information in some phone numbers. Full-width variants are also
79
    // present.
80
    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";
81
    const DIGITS = "\\p{Nd}";
82
83
    // Pattern that makes it easy to distinguish whether a region has a unique international dialing
84
    // prefix or not. If a region has a unique international prefix (e.g. 011 in USA), it will be
85
    // represented as a string that contains a sequence of ASCII digits. If there are multiple
86
    // available international prefixes in a region, they will be represented as a regex string that
87
    // always contains character(s) other than ASCII digits.
88
    // Note this regex also includes tilde, which signals waiting for the tone.
89
    const UNIQUE_INTERNATIONAL_PREFIX = "[\\d]+(?:[~\xE2\x81\x93\xE2\x88\xBC\xEF\xBD\x9E][\\d]+)?";
90
    const NON_DIGITS_PATTERN = "(\\D+)";
91
92
    // The FIRST_GROUP_PATTERN was originally set to $1 but there are some countries for which the
93
    // first group is not used in the national pattern (e.g. Argentina) so the $1 group does not match
94
    // correctly.  Therefore, we use \d, so that the first group actually used in the pattern will be
95
    // matched.
96
    const FIRST_GROUP_PATTERN = "(\\$\\d)";
97
    const NP_PATTERN = '\\$NP';
98
    const FG_PATTERN = '\\$FG';
99
    const CC_PATTERN = '\\$CC';
100
101
    // A pattern that is used to determine if the national prefix formatting rule has the first group
102
    // only, i.e., does not start with the national prefix. Note that the pattern explicitly allows
103
    // for unbalanced parentheses.
104
    const FIRST_GROUP_ONLY_PREFIX_PATTERN = '\\(?\\$1\\)?';
105
    public static $PLUS_CHARS_PATTERN;
106
    protected static $SEPARATOR_PATTERN;
107
    protected static $CAPTURING_DIGIT_PATTERN;
108
    protected static $VALID_START_CHAR_PATTERN = null;
109
    public static $SECOND_NUMBER_START_PATTERN = '[\\\\/] *x';
110
    public static $UNWANTED_END_CHAR_PATTERN = "[[\\P{N}&&\\P{L}]&&[^#]]+$";
111
    protected static $DIALLABLE_CHAR_MAPPINGS = array();
112
    protected static $CAPTURING_EXTN_DIGITS;
113
114
    /**
115
     * @var PhoneNumberUtil
116
     */
117
    protected static $instance = null;
118
119
    /**
120
     * Only upper-case variants of alpha characters are stored.
121
     * @var array
122
     */
123
    protected static $ALPHA_MAPPINGS = array(
124
        'A' => '2',
125
        'B' => '2',
126
        'C' => '2',
127
        'D' => '3',
128
        'E' => '3',
129
        'F' => '3',
130
        'G' => '4',
131
        'H' => '4',
132
        'I' => '4',
133
        'J' => '5',
134
        'K' => '5',
135
        'L' => '5',
136
        'M' => '6',
137
        'N' => '6',
138
        'O' => '6',
139
        'P' => '7',
140
        'Q' => '7',
141
        'R' => '7',
142
        'S' => '7',
143
        'T' => '8',
144
        'U' => '8',
145
        'V' => '8',
146
        'W' => '9',
147
        'X' => '9',
148
        'Y' => '9',
149
        'Z' => '9',
150
    );
151
152
    /**
153
     * Map of country calling codes that use a mobile token before the area code. One example of when
154
     * this is relevant is when determining the length of the national destination code, which should
155
     * be the length of the area code plus the length of the mobile token.
156
     * @var array
157
     */
158
    protected static $MOBILE_TOKEN_MAPPINGS = array();
159
160
    /**
161
     * Set of country codes that have geographically assigned mobile numbers (see GEO_MOBILE_COUNTRIES
162
     * below) which are not based on *area codes*. For example, in China mobile numbers start with a
163
     * carrier indicator, and beyond that are geographically assigned: this carrier indicator is not
164
     * considered to be an area code.
165
     *
166
     * @var array
167
     */
168
    protected static $GEO_MOBILE_COUNTRIES_WITHOUT_MOBILE_AREA_CODES;
169
170
    /**
171
     * Set of country calling codes that have geographically assigned mobile numbers. This may not be
172
     * complete; we add calling codes case by case, as we find geographical mobile numbers or hear
173
     * from user reports. Note that countries like the US, where we can't distinguish between
174
     * fixed-line or mobile numbers, are not listed here, since we consider FIXED_LINE_OR_MOBILE to be
175
     * a possibly geographically-related type anyway (like FIXED_LINE).
176
     *
177
     * @var array
178
     */
179
    protected static $GEO_MOBILE_COUNTRIES;
180
181
    /**
182
     * For performance reasons, amalgamate both into one map.
183
     * @var array
184
     */
185
    protected static $ALPHA_PHONE_MAPPINGS = null;
186
187
    /**
188
     * Separate map of all symbols that we wish to retain when formatting alpha numbers. This
189
     * includes digits, ASCII letters and number grouping symbols such as "-" and " ".
190
     * @var array
191
     */
192
    protected static $ALL_PLUS_NUMBER_GROUPING_SYMBOLS;
193
194
    /**
195
     * Simple ASCII digits map used to populate ALPHA_PHONE_MAPPINGS and
196
     * ALL_PLUS_NUMBER_GROUPING_SYMBOLS.
197
     * @var array
198
     */
199
    protected static $asciiDigitMappings = array(
200
        '0' => '0',
201
        '1' => '1',
202
        '2' => '2',
203
        '3' => '3',
204
        '4' => '4',
205
        '5' => '5',
206
        '6' => '6',
207
        '7' => '7',
208
        '8' => '8',
209
        '9' => '9',
210
    );
211
212
    /**
213
     * Regexp of all possible ways to write extensions, for use when parsing. This will be run as a
214
     * case-insensitive regexp match. Wide character versions are also provided after each ASCII
215
     * version.
216
     * @var String
217
     */
218
    protected static $EXTN_PATTERNS_FOR_PARSING;
219
    /**
220
     * @var string
221
     * @internal
222
     */
223
    public static $EXTN_PATTERNS_FOR_MATCHING;
224
    protected static $EXTN_PATTERN = null;
225
    protected static $VALID_PHONE_NUMBER_PATTERN = null;
226
    protected static $MIN_LENGTH_PHONE_NUMBER_PATTERN;
227
    /**
228
     *  Regular expression of viable phone numbers. This is location independent. Checks we have at
229
     * least three leading digits, and only valid punctuation, alpha characters and
230
     * digits in the phone number. Does not include extension data.
231
     * The symbol 'x' is allowed here as valid punctuation since it is often used as a placeholder for
232
     * carrier codes, for example in Brazilian phone numbers. We also allow multiple "+" characters at
233
     * the start.
234
     * Corresponds to the following:
235
     * [digits]{minLengthNsn}|
236
     * plus_sign*(([punctuation]|[star])*[digits]){3,}([punctuation]|[star]|[digits]|[alpha])*
237
     *
238
     * The first reg-ex is to allow short numbers (two digits long) to be parsed if they are entered
239
     * as "15" etc, but only if there is no punctuation in them. The second expression restricts the
240
     * number of digits to three or more, but then allows them to be in international form, and to
241
     * have alpha-characters and punctuation.
242
     *
243
     * Note VALID_PUNCTUATION starts with a -, so must be the first in the range.
244
     * @var string
245
     */
246
    protected static $VALID_PHONE_NUMBER;
247
    protected static $numericCharacters = array(
248
        "\xef\xbc\x90" => 0,
249
        "\xef\xbc\x91" => 1,
250
        "\xef\xbc\x92" => 2,
251
        "\xef\xbc\x93" => 3,
252
        "\xef\xbc\x94" => 4,
253
        "\xef\xbc\x95" => 5,
254
        "\xef\xbc\x96" => 6,
255
        "\xef\xbc\x97" => 7,
256
        "\xef\xbc\x98" => 8,
257
        "\xef\xbc\x99" => 9,
258
259
        "\xd9\xa0" => 0,
260
        "\xd9\xa1" => 1,
261
        "\xd9\xa2" => 2,
262
        "\xd9\xa3" => 3,
263
        "\xd9\xa4" => 4,
264
        "\xd9\xa5" => 5,
265
        "\xd9\xa6" => 6,
266
        "\xd9\xa7" => 7,
267
        "\xd9\xa8" => 8,
268
        "\xd9\xa9" => 9,
269
270
        "\xdb\xb0" => 0,
271
        "\xdb\xb1" => 1,
272
        "\xdb\xb2" => 2,
273
        "\xdb\xb3" => 3,
274
        "\xdb\xb4" => 4,
275
        "\xdb\xb5" => 5,
276
        "\xdb\xb6" => 6,
277
        "\xdb\xb7" => 7,
278
        "\xdb\xb8" => 8,
279
        "\xdb\xb9" => 9,
280
281
        "\xe1\xa0\x90" => 0,
282
        "\xe1\xa0\x91" => 1,
283
        "\xe1\xa0\x92" => 2,
284
        "\xe1\xa0\x93" => 3,
285
        "\xe1\xa0\x94" => 4,
286
        "\xe1\xa0\x95" => 5,
287
        "\xe1\xa0\x96" => 6,
288
        "\xe1\xa0\x97" => 7,
289
        "\xe1\xa0\x98" => 8,
290
        "\xe1\xa0\x99" => 9,
291
    );
292
293
    /**
294
     * The set of county calling codes that map to the non-geo entity region ("001").
295
     * @var array
296
     */
297
    protected $countryCodesForNonGeographicalRegion = array();
298
    /**
299
     * The set of regions the library supports.
300
     * @var array
301
     */
302
    protected $supportedRegions = array();
303
304
    /**
305
     * A mapping from a country calling code to the region codes which denote the region represented
306
     * by that country calling code. In the case of multiple regions sharing a calling code, such as
307
     * the NANPA regions, the one indicated with "isMainCountryForCode" in the metadata should be
308
     * first.
309
     * @var array
310
     */
311
    protected $countryCallingCodeToRegionCodeMap = array();
312
    /**
313
     * The set of regions that share country calling code 1.
314
     * @var array
315
     */
316
    protected $nanpaRegions = array();
317
318
    /**
319
     * @var MetadataSourceInterface
320
     */
321
    protected $metadataSource;
322
323
    /**
324
     * This class implements a singleton, so the only constructor is protected.
325
     * @param MetadataSourceInterface $metadataSource
326
     * @param $countryCallingCodeToRegionCodeMap
327
     */
328
    protected function __construct(MetadataSourceInterface $metadataSource, $countryCallingCodeToRegionCodeMap)
329
    {
330
        $this->metadataSource = $metadataSource;
331
        $this->countryCallingCodeToRegionCodeMap = $countryCallingCodeToRegionCodeMap;
332
        $this->init();
333
        static::initCapturingExtnDigits();
334
        static::initExtnPatterns();
335
        static::initExtnPattern();
336
        static::$PLUS_CHARS_PATTERN = "[" . static::PLUS_CHARS . "]+";
337
        static::$SEPARATOR_PATTERN = "[" . static::VALID_PUNCTUATION . "]+";
338
        static::$CAPTURING_DIGIT_PATTERN = "(" . static::DIGITS . ")";
339
        static::initValidStartCharPattern();
340
        static::initAlphaPhoneMappings();
341
        static::initDiallableCharMappings();
342
343
        static::$ALL_PLUS_NUMBER_GROUPING_SYMBOLS = array();
344
        // Put (lower letter -> upper letter) and (upper letter -> upper letter) mappings.
345
        foreach (static::$ALPHA_MAPPINGS as $c => $value) {
346
            static::$ALL_PLUS_NUMBER_GROUPING_SYMBOLS[strtolower($c)] = $c;
347
            static::$ALL_PLUS_NUMBER_GROUPING_SYMBOLS[$c] = $c;
348
        }
349
        static::$ALL_PLUS_NUMBER_GROUPING_SYMBOLS += static::$asciiDigitMappings;
350
        static::$ALL_PLUS_NUMBER_GROUPING_SYMBOLS["-"] = '-';
351
        static::$ALL_PLUS_NUMBER_GROUPING_SYMBOLS["\xEF\xBC\x8D"] = '-';
352
        static::$ALL_PLUS_NUMBER_GROUPING_SYMBOLS["\xE2\x80\x90"] = '-';
353
        static::$ALL_PLUS_NUMBER_GROUPING_SYMBOLS["\xE2\x80\x91"] = '-';
354
        static::$ALL_PLUS_NUMBER_GROUPING_SYMBOLS["\xE2\x80\x92"] = '-';
355
        static::$ALL_PLUS_NUMBER_GROUPING_SYMBOLS["\xE2\x80\x93"] = '-';
356
        static::$ALL_PLUS_NUMBER_GROUPING_SYMBOLS["\xE2\x80\x94"] = '-';
357
        static::$ALL_PLUS_NUMBER_GROUPING_SYMBOLS["\xE2\x80\x95"] = '-';
358
        static::$ALL_PLUS_NUMBER_GROUPING_SYMBOLS["\xE2\x88\x92"] = '-';
359
        static::$ALL_PLUS_NUMBER_GROUPING_SYMBOLS["/"] = "/";
360
        static::$ALL_PLUS_NUMBER_GROUPING_SYMBOLS["\xEF\xBC\x8F"] = "/";
361
        static::$ALL_PLUS_NUMBER_GROUPING_SYMBOLS[" "] = " ";
362
        static::$ALL_PLUS_NUMBER_GROUPING_SYMBOLS["\xE3\x80\x80"] = " ";
363
        static::$ALL_PLUS_NUMBER_GROUPING_SYMBOLS["\xE2\x81\xA0"] = " ";
364
        static::$ALL_PLUS_NUMBER_GROUPING_SYMBOLS["."] = ".";
365
        static::$ALL_PLUS_NUMBER_GROUPING_SYMBOLS["\xEF\xBC\x8E"] = ".";
366
367
368
        static::initValidPhoneNumberPatterns();
369
370
        static::$UNWANTED_END_CHAR_PATTERN = "[^" . static::DIGITS . static::VALID_ALPHA . "#]+$";
371
372
        static::initMobileTokenMappings();
373
374
        static::$GEO_MOBILE_COUNTRIES_WITHOUT_MOBILE_AREA_CODES = array();
375
        static::$GEO_MOBILE_COUNTRIES_WITHOUT_MOBILE_AREA_CODES[] = 86; // China
376
377
        static::$GEO_MOBILE_COUNTRIES = array();
378
        static::$GEO_MOBILE_COUNTRIES[] = 52; // Mexico
379
        static::$GEO_MOBILE_COUNTRIES[] = 54; // Argentina
380
        static::$GEO_MOBILE_COUNTRIES[] = 55; // Brazil
381
        static::$GEO_MOBILE_COUNTRIES[] = 62; // Indonesia: some prefixes only (fixed CMDA wireless)
382
383
        static::$GEO_MOBILE_COUNTRIES = array_merge(static::$GEO_MOBILE_COUNTRIES, static::$GEO_MOBILE_COUNTRIES_WITHOUT_MOBILE_AREA_CODES);
384
    }
385
386
    /**
387
     * Gets a {@link PhoneNumberUtil} instance to carry out international phone number formatting,
388
     * parsing, or validation. The instance is loaded with phone number metadata for a number of most
389
     * commonly used regions.
390
     *
391
     * <p>The {@link PhoneNumberUtil} is implemented as a singleton. Therefore, calling getInstance
392
     * multiple times will only result in one instance being created.
393
     *
394
     * @param string $baseFileLocation
395
     * @param array|null $countryCallingCodeToRegionCodeMap
396
     * @param MetadataLoaderInterface|null $metadataLoader
397
     * @param MetadataSourceInterface|null $metadataSource
398
     * @return PhoneNumberUtil instance
399
     */
400
    public static function getInstance($baseFileLocation = self::META_DATA_FILE_PREFIX, array $countryCallingCodeToRegionCodeMap = null, MetadataLoaderInterface $metadataLoader = null, MetadataSourceInterface $metadataSource = null)
401
    {
402
        if (static::$instance === null) {
403
            if ($countryCallingCodeToRegionCodeMap === null) {
404
                $countryCallingCodeToRegionCodeMap = CountryCodeToRegionCodeMap::$countryCodeToRegionCodeMap;
405
            }
406
407
            if ($metadataLoader === null) {
408
                $metadataLoader = new DefaultMetadataLoader();
409
            }
410
411
            if ($metadataSource === null) {
412
                $metadataSource = new MultiFileMetadataSourceImpl($metadataLoader, __DIR__ . '/data/' . $baseFileLocation);
413
            }
414
415
            static::$instance = new static($metadataSource, $countryCallingCodeToRegionCodeMap);
416
        }
417
        return static::$instance;
418
    }
419
420
    protected function init()
421
    {
422
        foreach ($this->countryCallingCodeToRegionCodeMap as $countryCode => $regionCodes) {
423
            // We can assume that if the country calling code maps to the non-geo entity region code then
424
            // that's the only region code it maps to.
425
            if (count($regionCodes) == 1 && static::REGION_CODE_FOR_NON_GEO_ENTITY === $regionCodes[0]) {
426
                // This is the subset of all country codes that map to the non-geo entity region code.
427
                $this->countryCodesForNonGeographicalRegion[] = $countryCode;
428
            } else {
429
                // The supported regions set does not include the "001" non-geo entity region code.
430
                $this->supportedRegions = array_merge($this->supportedRegions, $regionCodes);
431
            }
432
        }
433
        // If the non-geo entity still got added to the set of supported regions it must be because
434
        // there are entries that list the non-geo entity alongside normal regions (which is wrong).
435
        // If we discover this, remove the non-geo entity from the set of supported regions and log.
436
        $idx_region_code_non_geo_entity = array_search(static::REGION_CODE_FOR_NON_GEO_ENTITY, $this->supportedRegions);
437
        if ($idx_region_code_non_geo_entity !== false) {
438
            unset($this->supportedRegions[$idx_region_code_non_geo_entity]);
439
        }
440
        $this->nanpaRegions = $this->countryCallingCodeToRegionCodeMap[static::NANPA_COUNTRY_CODE];
441
    }
442
443
    /**
444
     * @internal
445
     */
446
    public static function initCapturingExtnDigits()
447
    {
448
        static::$CAPTURING_EXTN_DIGITS = "(" . static::DIGITS . "{1,7})";
449
    }
450
451
    /**
452
     * @internal
453
     */
454
    public static function initExtnPatterns()
455
    {
456
        // One-character symbols that can be used to indicate an extension.
457
        $singleExtnSymbolsForMatching = "x\xEF\xBD\x98#\xEF\xBC\x83~\xEF\xBD\x9E";
458
        // For parsing, we are slightly more lenient in our interpretation than for matching. Here we
459
        // allow "comma" and "semicolon" as possible extension indicators. When matching, these are
460
        // hardly ever used to indicate this.
461
        $singleExtnSymbolsForParsing = ",;" . $singleExtnSymbolsForMatching;
462
463
        static::$EXTN_PATTERNS_FOR_PARSING = static::createExtnPattern($singleExtnSymbolsForParsing);
464
        static::$EXTN_PATTERNS_FOR_MATCHING = static::createExtnPattern($singleExtnSymbolsForMatching);
465
    }
466
467
    /**
468
     * Helper initialiser method to create the regular-expression pattern to match extensions,
469
     * allowing the one-char extension symbols provided by {@code singleExtnSymbols}.
470
     * @param string $singleExtnSymbols
471
     * @return string
472
     */
473
    protected static function createExtnPattern($singleExtnSymbols)
474
    {
475
        // There are three regular expressions here. The first covers RFC 3966 format, where the
476
        // extension is added using ";ext=". The second more generic one starts with optional white
477
        // space and ends with an optional full stop (.), followed by zero or more spaces/tabs/commas
478
        // and then the numbers themselves. The other one covers the special case of American numbers
479
        // where the extension is written with a hash at the end, such as "- 503#"
480
        // Note that the only capturing groups should be around the digits that you want to capture as
481
        // part of the extension, or else parsing will fail!
482
        // Canonical-equivalence doesn't seem to be an option with Android java, so we allow two options
483
        // for representing the accented o - the character itself, and one in the unicode decomposed
484
        // form with the combining acute accent.
485
        return (static::RFC3966_EXTN_PREFIX . static::$CAPTURING_EXTN_DIGITS . "|" . "[ \xC2\xA0\\t,]*" .
486
            "(?:e?xt(?:ensi(?:o\xCC\x81?|\xC3\xB3))?n?|(?:\xEF\xBD\x85)?\xEF\xBD\x98\xEF\xBD\x94(?:\xEF\xBD\x8E)?|" .
487
            "[" . $singleExtnSymbols . "]|int|\xEF\xBD\x89\xEF\xBD\x8E\xEF\xBD\x94|anexo)" .
488
            "[:\\.\xEF\xBC\x8E]?[ \xC2\xA0\\t,-]*" . static::$CAPTURING_EXTN_DIGITS . "\\#?|" .
489
            "[- ]+(" . static::DIGITS . "{1,5})\\#");
490
    }
491
492
    protected static function initExtnPattern()
493
    {
494
        static::$EXTN_PATTERN = "/(?:" . static::$EXTN_PATTERNS_FOR_PARSING . ")$/" . static::REGEX_FLAGS;
495
    }
496
497
    protected static function initValidPhoneNumberPatterns()
498
    {
499
        static::initCapturingExtnDigits();
500
        static::initExtnPatterns();
501
        static::$MIN_LENGTH_PHONE_NUMBER_PATTERN = "[" . static::DIGITS . "]{" . static::MIN_LENGTH_FOR_NSN . "}";
502
        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 . "]*";
503
        static::$VALID_PHONE_NUMBER_PATTERN = "%^" . static::$MIN_LENGTH_PHONE_NUMBER_PATTERN . "$|^" . static::$VALID_PHONE_NUMBER . "(?:" . static::$EXTN_PATTERNS_FOR_PARSING . ")?$%" . static::REGEX_FLAGS;
504
    }
505
506
    protected static function initAlphaPhoneMappings()
507
    {
508
        static::$ALPHA_PHONE_MAPPINGS = static::$ALPHA_MAPPINGS + static::$asciiDigitMappings;
509
    }
510
511
    protected static function initValidStartCharPattern()
512
    {
513
        static::$VALID_START_CHAR_PATTERN = "[" . static::PLUS_CHARS . static::DIGITS . "]";
514
    }
515
516
    protected static function initMobileTokenMappings()
517
    {
518
        static::$MOBILE_TOKEN_MAPPINGS = array();
519
        static::$MOBILE_TOKEN_MAPPINGS['52'] = "1";
520
        static::$MOBILE_TOKEN_MAPPINGS['54'] = "9";
521
    }
522
523
    protected static function initDiallableCharMappings()
524
    {
525
        static::$DIALLABLE_CHAR_MAPPINGS = static::$asciiDigitMappings;
526
        static::$DIALLABLE_CHAR_MAPPINGS[static::PLUS_SIGN] = static::PLUS_SIGN;
527
        static::$DIALLABLE_CHAR_MAPPINGS['*'] = '*';
528
        static::$DIALLABLE_CHAR_MAPPINGS['#'] = '#';
529
    }
530
531
    /**
532
     * Used for testing purposes only to reset the PhoneNumberUtil singleton to null.
533
     */
534
    public static function resetInstance()
535
    {
536
        static::$instance = null;
537
    }
538
539
    /**
540
     * Converts all alpha characters in a number to their respective digits on a keypad, but retains
541
     * existing formatting.
542
     * @param string $number
543
     * @return string
544
     */
545
    public static function convertAlphaCharactersInNumber($number)
546
    {
547
        if (static::$ALPHA_PHONE_MAPPINGS === null) {
548
            static::initAlphaPhoneMappings();
549
        }
550
551
        return static::normalizeHelper($number, static::$ALPHA_PHONE_MAPPINGS, false);
552
    }
553
554
    /**
555
     * Normalizes a string of characters representing a phone number by replacing all characters found
556
     * in the accompanying map with the values therein, and stripping all other characters if
557
     * removeNonMatches is true.
558
     *
559
     * @param string $number a string of characters representing a phone number
560
     * @param array $normalizationReplacements a mapping of characters to what they should be replaced by in
561
     * the normalized version of the phone number
562
     * @param bool $removeNonMatches indicates whether characters that are not able to be replaced
563
     * should be stripped from the number. If this is false, they will be left unchanged in the number.
564
     * @return string the normalized string version of the phone number
565
     */
566
    protected static function normalizeHelper($number, array $normalizationReplacements, $removeNonMatches)
567
    {
568
        $normalizedNumber = "";
569
        $strLength = mb_strlen($number, 'UTF-8');
570
        for ($i = 0; $i < $strLength; $i++) {
571
            $character = mb_substr($number, $i, 1, 'UTF-8');
572
            if (isset($normalizationReplacements[mb_strtoupper($character, 'UTF-8')])) {
573
                $normalizedNumber .= $normalizationReplacements[mb_strtoupper($character, 'UTF-8')];
574
            } else {
575
                if (!$removeNonMatches) {
576
                    $normalizedNumber .= $character;
577
                }
578
            }
579
            // If neither of the above are true, we remove this character.
580
        }
581
        return $normalizedNumber;
582
    }
583
584
    /**
585
     * Helper function to check if the national prefix formatting rule has the first group only, i.e.,
586
     * does not start with the national prefix.
587
     * @param string $nationalPrefixFormattingRule
588
     * @return bool
589
     */
590
    public static function formattingRuleHasFirstGroupOnly($nationalPrefixFormattingRule)
591
    {
592
        $firstGroupOnlyPrefixPatternMatcher = new Matcher(static::FIRST_GROUP_ONLY_PREFIX_PATTERN,
593
            $nationalPrefixFormattingRule);
594
595
        return mb_strlen($nationalPrefixFormattingRule) === 0
596
            || $firstGroupOnlyPrefixPatternMatcher->matches();
597
    }
598
599
    /**
600
     * Returns all regions the library has metadata for.
601
     *
602
     * @return array An unordered array of the two-letter region codes for every geographical region the
603
     *  library supports
604
     */
605
    public function getSupportedRegions()
606
    {
607
        return $this->supportedRegions;
608
    }
609
610
    /**
611
     * Returns all global network calling codes the library has metadata for.
612
     *
613
     * @return array An unordered array of the country calling codes for every non-geographical entity
614
     *  the library supports
615
     */
616
    public function getSupportedGlobalNetworkCallingCodes()
617
    {
618
        return $this->countryCodesForNonGeographicalRegion;
619
    }
620
621
    /**
622
     * Returns true if there is any possible number data set for a particular PhoneNumberDesc.
623
     *
624
     * @param PhoneNumberDesc $desc
625
     * @return bool
626
     */
627
    protected static function descHasPossibleNumberData(PhoneNumberDesc $desc)
628
    {
629
        // If this is empty, it means numbers of this type inherit from the "general desc" -> the value
630
        // '-1' means that no numbers exist for this type.
631
        $possibleLength = $desc->getPossibleLength();
632
        return count($possibleLength) != 1 || $possibleLength[0] != -1;
633
    }
634
635
    /**
636
     * Returns true if there is any data set for a particular PhoneNumberDesc.
637
     *
638
     * @param PhoneNumberDesc $desc
639
     * @return bool
640
     */
641
    protected static function descHasData(PhoneNumberDesc $desc)
642
    {
643
        // Checking most properties since we don't know what's present, since a custom build may have
644
        // stripped just one of them (e.g. liteBuild strips exampleNumber). We don't bother checking the
645
        // possibleLengthsLocalOnly, since if this is the only thing that's present we don't really
646
        // support the type at all: no type-specific methods will work with only this data.
647
        return $desc->hasExampleNumber()
648
            || static::descHasPossibleNumberData($desc)
649
            || ($desc->hasNationalNumberPattern() && $desc->getNationalNumberPattern() != 'NA');
650
    }
651
652
    /**
653
     * Returns the types we have metadata for based on the PhoneMetadata object passed in
654
     *
655
     * @param PhoneMetadata $metadata
656
     * @return array
657
     */
658
    private function getSupportedTypesForMetadata(PhoneMetadata $metadata)
659
    {
660
        $types = array();
661
        foreach (array_keys(PhoneNumberType::values()) as $type) {
662
            if ($type === PhoneNumberType::FIXED_LINE_OR_MOBILE || $type === PhoneNumberType::UNKNOWN) {
663
                // Never return FIXED_LINE_OR_MOBILE (it is a convenience type, and represents that a
664
                // particular number type can't be determined) or UNKNOWN (the non-type).
665
                continue;
666
            }
667
668
            if ($this->descHasData($this->getNumberDescByType($metadata, $type))) {
669
                $types[] = $type;
670
            }
671
        }
672
673
        return $types;
674
    }
675
676
    /**
677
     * Returns the types for a given region which the library has metadata for. Will not include
678
     * FIXED_LINE_OR_MOBILE (if the numbers in this region could be classified as FIXED_LINE_OR_MOBILE,
679
     * both FIXED_LINE and MOBILE would be present) and UNKNOWN.
680
     *
681
     * No types will be returned for invalid or unknown region codes.
682
     *
683
     * @param string $regionCode
684
     * @return array
685
     */
686
    public function getSupportedTypesForRegion($regionCode)
687
    {
688
        if (!$this->isValidRegionCode($regionCode)) {
689
            return array();
690
        }
691
        $metadata = $this->getMetadataForRegion($regionCode);
692
        return $this->getSupportedTypesForMetadata($metadata);
0 ignored issues
show
Bug introduced by
It seems like $metadata defined by $this->getMetadataForRegion($regionCode) on line 691 can be null; however, libphonenumber\PhoneNumb...ortedTypesForMetadata() does not accept null, maybe add an additional type check?

Unless you are absolutely sure that the expression can never be null because of other conditions, we strongly recommend to add an additional type check to your code:

/** @return stdClass|null */
function mayReturnNull() { }

function doesNotAcceptNull(stdClass $x) { }

// With potential error.
function withoutCheck() {
    $x = mayReturnNull();
    doesNotAcceptNull($x); // Potential error here.
}

// Safe - Alternative 1
function withCheck1() {
    $x = mayReturnNull();
    if ( ! $x instanceof stdClass) {
        throw new \LogicException('$x must be defined.');
    }
    doesNotAcceptNull($x);
}

// Safe - Alternative 2
function withCheck2() {
    $x = mayReturnNull();
    if ($x instanceof stdClass) {
        doesNotAcceptNull($x);
    }
}
Loading history...
693
    }
694
695
    /**
696
     * Returns the types for a country-code belonging to a non-geographical entity which the library
697
     * has metadata for. Will not include FIXED_LINE_OR_MOBILE (if numbers for this non-geographical
698
     * entity could be classified as FIXED_LINE_OR_MOBILE, both FIXED_LINE and MOBILE would be
699
     * present) and UNKNOWN.
700
     *
701
     * @param int $countryCallingCode
702
     * @return array
703
     */
704
    public function getSupportedTypesForNonGeoEntity($countryCallingCode)
705
    {
706
        $metadata = $this->getMetadataForNonGeographicalRegion($countryCallingCode);
707
        if ($metadata === null) {
708
            return array();
709
        }
710
711
        return $this->getSupportedTypesForMetadata($metadata);
712
    }
713
714
    /**
715
     * Gets the length of the geographical area code from the {@code nationalNumber} field of the
716
     * PhoneNumber object passed in, so that clients could use it to split a national significant
717
     * number into geographical area code and subscriber number. It works in such a way that the
718
     * resultant subscriber number should be diallable, at least on some devices. An example of how
719
     * this could be used:
720
     *
721
     * <code>
722
     * $phoneUtil = PhoneNumberUtil::getInstance();
723
     * $number = $phoneUtil->parse("16502530000", "US");
724
     * $nationalSignificantNumber = $phoneUtil->getNationalSignificantNumber($number);
725
     *
726
     * $areaCodeLength = $phoneUtil->getLengthOfGeographicalAreaCode($number);
727
     * if ($areaCodeLength > 0)
728
     * {
729
     *     $areaCode = substr($nationalSignificantNumber, 0,$areaCodeLength);
730
     *     $subscriberNumber = substr($nationalSignificantNumber, $areaCodeLength);
731
     * } else {
732
     *     $areaCode = "";
733
     *     $subscriberNumber = $nationalSignificantNumber;
734
     * }
735
     * </code>
736
     *
737
     * N.B.: area code is a very ambiguous concept, so the I18N team generally recommends against
738
     * using it for most purposes, but recommends using the more general {@code nationalNumber}
739
     * instead. Read the following carefully before deciding to use this method:
740
     * <ul>
741
     *  <li> geographical area codes change over time, and this method honors those changes;
742
     *    therefore, it doesn't guarantee the stability of the result it produces.
743
     *  <li> subscriber numbers may not be diallable from all devices (notably mobile devices, which
744
     *    typically requires the full national_number to be dialled in most regions).
745
     *  <li> most non-geographical numbers have no area codes, including numbers from non-geographical
746
     *    entities
747
     *  <li> some geographical numbers have no area codes.
748
     * </ul>
749
     * @param PhoneNumber $number PhoneNumber object for which clients want to know the length of the area code.
750
     * @return int the length of area code of the PhoneNumber object passed in.
751
     */
752
    public function getLengthOfGeographicalAreaCode(PhoneNumber $number)
753
    {
754
        $metadata = $this->getMetadataForRegion($this->getRegionCodeForNumber($number));
755
        if ($metadata === null) {
756
            return 0;
757
        }
758
        // If a country doesn't use a national prefix, and this number doesn't have an Italian leading
759
        // zero, we assume it is a closed dialling plan with no area codes.
760
        if (!$metadata->hasNationalPrefix() && !$number->isItalianLeadingZero()) {
0 ignored issues
show
Bug Best Practice introduced by
The expression $number->isItalianLeadingZero() of type boolean|null is loosely compared to false; this is ambiguous if the boolean can be false. You might want to explicitly use !== null instead.

If an expression can have both false, and null as possible values. It is generally a good practice to always use strict comparison to clearly distinguish between those two values.

$a = canBeFalseAndNull();

// Instead of
if ( ! $a) { }

// Better use one of the explicit versions:
if ($a !== null) { }
if ($a !== false) { }
if ($a !== null && $a !== false) { }
Loading history...
761
            return 0;
762
        }
763
764
        $type = $this->getNumberType($number);
765
        $countryCallingCode = $number->getCountryCode();
766
767
        if ($type === PhoneNumberType::MOBILE
768
            // Note this is a rough heuristic; it doesn't cover Indonesia well, for example, where area
769
            // codes are present for some mobile phones but not for others. We have no better way of
770
            // representing this in the metadata at this point.
771
            && in_array($countryCallingCode, self::$GEO_MOBILE_COUNTRIES_WITHOUT_MOBILE_AREA_CODES)
772
        ) {
773
            return 0;
774
        }
775
776
        if (!$this->isNumberGeographical($type, $countryCallingCode)) {
777
            return 0;
778
        }
779
780
        return $this->getLengthOfNationalDestinationCode($number);
781
    }
782
783
    /**
784
     * Returns the metadata for the given region code or {@code null} if the region code is invalid
785
     * or unknown.
786
     * @param string $regionCode
787
     * @return PhoneMetadata
788
     */
789
    public function getMetadataForRegion($regionCode)
790
    {
791
        if (!$this->isValidRegionCode($regionCode)) {
792
            return null;
793
        }
794
795
        return $this->metadataSource->getMetadataForRegion($regionCode);
796
    }
797
798
    /**
799
     * Helper function to check region code is not unknown or null.
800
     * @param string $regionCode
801
     * @return bool
802
     */
803
    protected function isValidRegionCode($regionCode)
804
    {
805
        return $regionCode !== null && in_array($regionCode, $this->supportedRegions);
806
    }
807
808
    /**
809
     * Returns the region where a phone number is from. This could be used for geocoding at the region
810
     * level. Only guarantees correct results for valid, full numbers (not short-codes, or invalid
811
     * numbers).
812
     *
813
     * @param PhoneNumber $number the phone number whose origin we want to know
814
     * @return null|string  the region where the phone number is from, or null if no region matches this calling
815
     * code
816
     */
817
    public function getRegionCodeForNumber(PhoneNumber $number)
818
    {
819
        $countryCode = $number->getCountryCode();
820
        if (!isset($this->countryCallingCodeToRegionCodeMap[$countryCode])) {
821
            return null;
822
        }
823
        $regions = $this->countryCallingCodeToRegionCodeMap[$countryCode];
824
        if (count($regions) == 1) {
825
            return $regions[0];
826
        } else {
827
            return $this->getRegionCodeForNumberFromRegionList($number, $regions);
828
        }
829
    }
830
831
    /**
832
     * @param PhoneNumber $number
833
     * @param array $regionCodes
834
     * @return null|string
835
     */
836
    protected function getRegionCodeForNumberFromRegionList(PhoneNumber $number, array $regionCodes)
837
    {
838
        $nationalNumber = $this->getNationalSignificantNumber($number);
839
        foreach ($regionCodes as $regionCode) {
840
            // If leadingDigits is present, use this. Otherwise, do full validation.
841
            // Metadata cannot be null because the region codes come from the country calling code map.
842
            $metadata = $this->getMetadataForRegion($regionCode);
843
            if ($metadata->hasLeadingDigits()) {
844
                $nbMatches = preg_match(
845
                    '/' . $metadata->getLeadingDigits() . '/',
846
                    $nationalNumber,
847
                    $matches,
848
                    PREG_OFFSET_CAPTURE
849
                );
850
                if ($nbMatches > 0 && $matches[0][1] === 0) {
851
                    return $regionCode;
852
                }
853
            } elseif ($this->getNumberTypeHelper($nationalNumber, $metadata) != PhoneNumberType::UNKNOWN) {
0 ignored issues
show
Bug introduced by
It seems like $metadata defined by $this->getMetadataForRegion($regionCode) on line 842 can be null; however, libphonenumber\PhoneNumb...::getNumberTypeHelper() does not accept null, maybe add an additional type check?

Unless you are absolutely sure that the expression can never be null because of other conditions, we strongly recommend to add an additional type check to your code:

/** @return stdClass|null */
function mayReturnNull() { }

function doesNotAcceptNull(stdClass $x) { }

// With potential error.
function withoutCheck() {
    $x = mayReturnNull();
    doesNotAcceptNull($x); // Potential error here.
}

// Safe - Alternative 1
function withCheck1() {
    $x = mayReturnNull();
    if ( ! $x instanceof stdClass) {
        throw new \LogicException('$x must be defined.');
    }
    doesNotAcceptNull($x);
}

// Safe - Alternative 2
function withCheck2() {
    $x = mayReturnNull();
    if ($x instanceof stdClass) {
        doesNotAcceptNull($x);
    }
}
Loading history...
854
                return $regionCode;
855
            }
856
        }
857
        return null;
858
    }
859
860
    /**
861
     * Gets the national significant number of the a phone number. Note a national significant number
862
     * doesn't contain a national prefix or any formatting.
863
     *
864
     * @param PhoneNumber $number the phone number for which the national significant number is needed
865
     * @return string the national significant number of the PhoneNumber object passed in
866
     */
867
    public function getNationalSignificantNumber(PhoneNumber $number)
868
    {
869
        // If leading zero(s) have been set, we prefix this now. Note this is not a national prefix.
870
        $nationalNumber = '';
871
        if ($number->isItalianLeadingZero() && $number->getNumberOfLeadingZeros() > 0) {
872
            $zeros = str_repeat('0', $number->getNumberOfLeadingZeros());
873
            $nationalNumber .= $zeros;
874
        }
875
        $nationalNumber .= $number->getNationalNumber();
876
        return $nationalNumber;
877
    }
878
879
    /**
880
     * @param string $nationalNumber
881
     * @param PhoneMetadata $metadata
882
     * @return int PhoneNumberType constant
883
     */
884
    protected function getNumberTypeHelper($nationalNumber, PhoneMetadata $metadata)
885
    {
886
        if (!$this->isNumberMatchingDesc($nationalNumber, $metadata->getGeneralDesc())) {
887
            return PhoneNumberType::UNKNOWN;
888
        }
889
        if ($this->isNumberMatchingDesc($nationalNumber, $metadata->getPremiumRate())) {
890
            return PhoneNumberType::PREMIUM_RATE;
891
        }
892
        if ($this->isNumberMatchingDesc($nationalNumber, $metadata->getTollFree())) {
893
            return PhoneNumberType::TOLL_FREE;
894
        }
895
896
897
        if ($this->isNumberMatchingDesc($nationalNumber, $metadata->getSharedCost())) {
898
            return PhoneNumberType::SHARED_COST;
899
        }
900
        if ($this->isNumberMatchingDesc($nationalNumber, $metadata->getVoip())) {
901
            return PhoneNumberType::VOIP;
902
        }
903
        if ($this->isNumberMatchingDesc($nationalNumber, $metadata->getPersonalNumber())) {
904
            return PhoneNumberType::PERSONAL_NUMBER;
905
        }
906
        if ($this->isNumberMatchingDesc($nationalNumber, $metadata->getPager())) {
907
            return PhoneNumberType::PAGER;
908
        }
909
        if ($this->isNumberMatchingDesc($nationalNumber, $metadata->getUan())) {
910
            return PhoneNumberType::UAN;
911
        }
912
        if ($this->isNumberMatchingDesc($nationalNumber, $metadata->getVoicemail())) {
913
            return PhoneNumberType::VOICEMAIL;
914
        }
915
        $isFixedLine = $this->isNumberMatchingDesc($nationalNumber, $metadata->getFixedLine());
916
        if ($isFixedLine) {
917
            if ($metadata->isSameMobileAndFixedLinePattern()) {
918
                return PhoneNumberType::FIXED_LINE_OR_MOBILE;
919
            } elseif ($this->isNumberMatchingDesc($nationalNumber, $metadata->getMobile())) {
920
                return PhoneNumberType::FIXED_LINE_OR_MOBILE;
921
            }
922
            return PhoneNumberType::FIXED_LINE;
923
        }
924
        // Otherwise, test to see if the number is mobile. Only do this if certain that the patterns for
925
        // mobile and fixed line aren't the same.
926
        if (!$metadata->isSameMobileAndFixedLinePattern() &&
927
            $this->isNumberMatchingDesc($nationalNumber, $metadata->getMobile())
928
        ) {
929
            return PhoneNumberType::MOBILE;
930
        }
931
        return PhoneNumberType::UNKNOWN;
932
    }
933
934
    /**
935
     * @param string $nationalNumber
936
     * @param PhoneNumberDesc $numberDesc
937
     * @return bool
938
     */
939
    public function isNumberMatchingDesc($nationalNumber, PhoneNumberDesc $numberDesc)
940
    {
941
        // Check if any possible number lengths are present; if so, we use them to avoid checking the
942
        // validation pattern if they don't match. If they are absent, this means they match the general
943
        // description, which we have already checked before checking a specific number type.
944
        $actualLength = mb_strlen($nationalNumber);
945
        $possibleLengths = $numberDesc->getPossibleLength();
946
        if (count($possibleLengths) > 0 && !in_array($actualLength, $possibleLengths)) {
947
            return false;
948
        }
949
950
        $nationalNumberPatternMatcher = new Matcher($numberDesc->getNationalNumberPattern(), $nationalNumber);
951
952
        return $nationalNumberPatternMatcher->matches();
953
    }
954
955
    /**
956
     * isNumberGeographical(PhoneNumber)
957
     *
958
     * Tests whether a phone number has a geographical association. It checks if the number is
959
     * associated to a certain region in the country where it belongs to. Note that this doesn't
960
     * verify if the number is actually in use.
961
     *
962
     * isNumberGeographical(PhoneNumberType, $countryCallingCode)
963
     *
964
     * Tests whether a phone number has a geographical association, as represented by its type and the
965
     * country it belongs to.
966
     *
967
     * This version exists since calculating the phone number type is expensive; if we have already
968
     * done this, we don't want to do it again.
969
     *
970
     * @param PhoneNumber|int $phoneNumberObjOrType A PhoneNumber object, or a PhoneNumberType integer
971
     * @param int|null $countryCallingCode Used when passing a PhoneNumberType
972
     * @return bool
973
     */
974
    public function isNumberGeographical($phoneNumberObjOrType, $countryCallingCode = null)
975
    {
976
        if ($phoneNumberObjOrType instanceof PhoneNumber) {
977
            return $this->isNumberGeographical($this->getNumberType($phoneNumberObjOrType), $phoneNumberObjOrType->getCountryCode());
978
        }
979
980
        return $phoneNumberObjOrType == PhoneNumberType::FIXED_LINE
981
        || $phoneNumberObjOrType == PhoneNumberType::FIXED_LINE_OR_MOBILE
982
        || (in_array($countryCallingCode, static::$GEO_MOBILE_COUNTRIES)
983
            && $phoneNumberObjOrType == PhoneNumberType::MOBILE);
984
    }
985
986
    /**
987
     * Gets the type of a phone number.
988
     * @param PhoneNumber $number the number the phone number that we want to know the type
989
     * @return int PhoneNumberType the type of the phone number
990
     */
991
    public function getNumberType(PhoneNumber $number)
992
    {
993
        $regionCode = $this->getRegionCodeForNumber($number);
994
        $metadata = $this->getMetadataForRegionOrCallingCode($number->getCountryCode(), $regionCode);
995
        if ($metadata === null) {
996
            return PhoneNumberType::UNKNOWN;
997
        }
998
        $nationalSignificantNumber = $this->getNationalSignificantNumber($number);
999
        return $this->getNumberTypeHelper($nationalSignificantNumber, $metadata);
1000
    }
1001
1002
    /**
1003
     * @param int $countryCallingCode
1004
     * @param string $regionCode
1005
     * @return PhoneMetadata
1006
     */
1007
    protected function getMetadataForRegionOrCallingCode($countryCallingCode, $regionCode)
1008
    {
1009
        return static::REGION_CODE_FOR_NON_GEO_ENTITY === $regionCode ?
1010
            $this->getMetadataForNonGeographicalRegion($countryCallingCode) : $this->getMetadataForRegion($regionCode);
1011
    }
1012
1013
    /**
1014
     * @param int $countryCallingCode
1015
     * @return PhoneMetadata
1016
     */
1017
    public function getMetadataForNonGeographicalRegion($countryCallingCode)
1018
    {
1019
        if (!isset($this->countryCallingCodeToRegionCodeMap[$countryCallingCode])) {
1020
            return null;
1021
        }
1022
        return $this->metadataSource->getMetadataForNonGeographicalRegion($countryCallingCode);
1023
    }
1024
1025
    /**
1026
     * Gets the length of the national destination code (NDC) from the PhoneNumber object passed in,
1027
     * so that clients could use it to split a national significant number into NDC and subscriber
1028
     * number. The NDC of a phone number is normally the first group of digit(s) right after the
1029
     * country calling code when the number is formatted in the international format, if there is a
1030
     * subscriber number part that follows. An example of how this could be used:
1031
     *
1032
     * <code>
1033
     * $phoneUtil = PhoneNumberUtil::getInstance();
1034
     * $number = $phoneUtil->parse("18002530000", "US");
1035
     * $nationalSignificantNumber = $phoneUtil->getNationalSignificantNumber($number);
1036
     *
1037
     * $nationalDestinationCodeLength = $phoneUtil->getLengthOfNationalDestinationCode($number);
1038
     * if ($nationalDestinationCodeLength > 0) {
1039
     *     $nationalDestinationCode = substr($nationalSignificantNumber, 0, $nationalDestinationCodeLength);
1040
     *     $subscriberNumber = substr($nationalSignificantNumber, $nationalDestinationCodeLength);
1041
     * } else {
1042
     *     $nationalDestinationCode = "";
1043
     *     $subscriberNumber = $nationalSignificantNumber;
1044
     * }
1045
     * </code>
1046
     *
1047
     * Refer to the unit tests to see the difference between this function and
1048
     * {@link #getLengthOfGeographicalAreaCode}.
1049
     *
1050
     * @param PhoneNumber $number the PhoneNumber object for which clients want to know the length of the NDC.
1051
     * @return int the length of NDC of the PhoneNumber object passed in.
1052
     */
1053
    public function getLengthOfNationalDestinationCode(PhoneNumber $number)
1054
    {
1055
        if ($number->hasExtension()) {
1056
            // We don't want to alter the proto given to us, but we don't want to include the extension
1057
            // when we format it, so we copy it and clear the extension here.
1058
            $copiedProto = new PhoneNumber();
1059
            $copiedProto->mergeFrom($number);
1060
            $copiedProto->clearExtension();
1061
        } else {
1062
            $copiedProto = clone $number;
1063
        }
1064
1065
        $nationalSignificantNumber = $this->format($copiedProto, PhoneNumberFormat::INTERNATIONAL);
1066
1067
        $numberGroups = preg_split('/' . static::NON_DIGITS_PATTERN . '/', $nationalSignificantNumber);
1068
1069
        // The pattern will start with "+COUNTRY_CODE " so the first group will always be the empty
1070
        // string (before the + symbol) and the second group will be the country calling code. The third
1071
        // group will be area code if it is not the last group.
1072
        if (count($numberGroups) <= 3) {
1073
            return 0;
1074
        }
1075
1076
        if ($this->getNumberType($number) == PhoneNumberType::MOBILE) {
1077
            // For example Argentinian mobile numbers, when formatted in the international format, are in
1078
            // the form of +54 9 NDC XXXX.... As a result, we take the length of the third group (NDC) and
1079
            // add the length of the second group (which is the mobile token), which also forms part of
1080
            // the national significant number. This assumes that the mobile token is always formatted
1081
            // separately from the rest of the phone number.
1082
1083
            $mobileToken = static::getCountryMobileToken($number->getCountryCode());
1084
            if ($mobileToken !== "") {
1085
                return mb_strlen($numberGroups[2]) + mb_strlen($numberGroups[3]);
1086
            }
1087
        }
1088
        return mb_strlen($numberGroups[2]);
1089
    }
1090
1091
    /**
1092
     * Formats a phone number in the specified format using default rules. Note that this does not
1093
     * promise to produce a phone number that the user can dial from where they are - although we do
1094
     * format in either 'national' or 'international' format depending on what the client asks for, we
1095
     * do not currently support a more abbreviated format, such as for users in the same "area" who
1096
     * could potentially dial the number without area code. Note that if the phone number has a
1097
     * country calling code of 0 or an otherwise invalid country calling code, we cannot work out
1098
     * which formatting rules to apply so we return the national significant number with no formatting
1099
     * applied.
1100
     *
1101
     * @param PhoneNumber $number the phone number to be formatted
1102
     * @param int $numberFormat the PhoneNumberFormat the phone number should be formatted into
1103
     * @return string the formatted phone number
1104
     */
1105
    public function format(PhoneNumber $number, $numberFormat)
1106
    {
1107
        if ($number->getNationalNumber() == 0 && $number->hasRawInput()) {
1108
            // Unparseable numbers that kept their raw input just use that.
1109
            // This is the only case where a number can be formatted as E164 without a
1110
            // leading '+' symbol (but the original number wasn't parseable anyway).
1111
            // TODO: Consider removing the 'if' above so that unparseable
1112
            // strings without raw input format to the empty string instead of "+00"
1113
            $rawInput = $number->getRawInput();
1114
            if (mb_strlen($rawInput) > 0) {
1115
                return $rawInput;
1116
            }
1117
        }
1118
1119
        $formattedNumber = "";
1120
        $countryCallingCode = $number->getCountryCode();
1121
        $nationalSignificantNumber = $this->getNationalSignificantNumber($number);
1122
1123
        if ($numberFormat == PhoneNumberFormat::E164) {
1124
            // Early exit for E164 case (even if the country calling code is invalid) since no formatting
1125
            // of the national number needs to be applied. Extensions are not formatted.
1126
            $formattedNumber .= $nationalSignificantNumber;
1127
            $this->prefixNumberWithCountryCallingCode($countryCallingCode, PhoneNumberFormat::E164, $formattedNumber);
1128
            return $formattedNumber;
1129
        }
1130
1131
        if (!$this->hasValidCountryCallingCode($countryCallingCode)) {
1132
            $formattedNumber .= $nationalSignificantNumber;
1133
            return $formattedNumber;
1134
        }
1135
1136
        // Note getRegionCodeForCountryCode() is used because formatting information for regions which
1137
        // share a country calling code is contained by only one region for performance reasons. For
1138
        // example, for NANPA regions it will be contained in the metadata for US.
1139
        $regionCode = $this->getRegionCodeForCountryCode($countryCallingCode);
1140
        // Metadata cannot be null because the country calling code is valid (which means that the
1141
        // region code cannot be ZZ and must be one of our supported region codes).
1142
        $metadata = $this->getMetadataForRegionOrCallingCode($countryCallingCode, $regionCode);
1143
        $formattedNumber .= $this->formatNsn($nationalSignificantNumber, $metadata, $numberFormat);
0 ignored issues
show
Bug introduced by
It seems like $metadata defined by $this->getMetadataForReg...llingCode, $regionCode) on line 1142 can be null; however, libphonenumber\PhoneNumberUtil::formatNsn() does not accept null, maybe add an additional type check?

Unless you are absolutely sure that the expression can never be null because of other conditions, we strongly recommend to add an additional type check to your code:

/** @return stdClass|null */
function mayReturnNull() { }

function doesNotAcceptNull(stdClass $x) { }

// With potential error.
function withoutCheck() {
    $x = mayReturnNull();
    doesNotAcceptNull($x); // Potential error here.
}

// Safe - Alternative 1
function withCheck1() {
    $x = mayReturnNull();
    if ( ! $x instanceof stdClass) {
        throw new \LogicException('$x must be defined.');
    }
    doesNotAcceptNull($x);
}

// Safe - Alternative 2
function withCheck2() {
    $x = mayReturnNull();
    if ($x instanceof stdClass) {
        doesNotAcceptNull($x);
    }
}
Loading history...
1144
        $this->maybeAppendFormattedExtension($number, $metadata, $numberFormat, $formattedNumber);
1145
        $this->prefixNumberWithCountryCallingCode($countryCallingCode, $numberFormat, $formattedNumber);
1146
        return $formattedNumber;
1147
    }
1148
1149
    /**
1150
     * A helper function that is used by format and formatByPattern.
1151
     * @param int $countryCallingCode
1152
     * @param int $numberFormat PhoneNumberFormat
1153
     * @param string $formattedNumber
1154
     */
1155
    protected function prefixNumberWithCountryCallingCode($countryCallingCode, $numberFormat, &$formattedNumber)
1156
    {
1157
        switch ($numberFormat) {
1158
            case PhoneNumberFormat::E164:
1159
                $formattedNumber = static::PLUS_SIGN . $countryCallingCode . $formattedNumber;
1160
                return;
1161
            case PhoneNumberFormat::INTERNATIONAL:
1162
                $formattedNumber = static::PLUS_SIGN . $countryCallingCode . " " . $formattedNumber;
1163
                return;
1164
            case PhoneNumberFormat::RFC3966:
1165
                $formattedNumber = static::RFC3966_PREFIX . static::PLUS_SIGN . $countryCallingCode . "-" . $formattedNumber;
1166
                return;
1167
            case PhoneNumberFormat::NATIONAL:
1168
            default:
1169
                return;
1170
        }
1171
    }
1172
1173
    /**
1174
     * Helper function to check the country calling code is valid.
1175
     * @param int $countryCallingCode
1176
     * @return bool
1177
     */
1178
    protected function hasValidCountryCallingCode($countryCallingCode)
1179
    {
1180
        return isset($this->countryCallingCodeToRegionCodeMap[$countryCallingCode]);
1181
    }
1182
1183
    /**
1184
     * Returns the region code that matches the specific country calling code. In the case of no
1185
     * region code being found, ZZ will be returned. In the case of multiple regions, the one
1186
     * designated in the metadata as the "main" region for this calling code will be returned. If the
1187
     * countryCallingCode entered is valid but doesn't match a specific region (such as in the case of
1188
     * non-geographical calling codes like 800) the value "001" will be returned (corresponding to
1189
     * the value for World in the UN M.49 schema).
1190
     *
1191
     * @param int $countryCallingCode
1192
     * @return string
1193
     */
1194
    public function getRegionCodeForCountryCode($countryCallingCode)
1195
    {
1196
        $regionCodes = isset($this->countryCallingCodeToRegionCodeMap[$countryCallingCode]) ? $this->countryCallingCodeToRegionCodeMap[$countryCallingCode] : null;
1197
        return $regionCodes === null ? static::UNKNOWN_REGION : $regionCodes[0];
1198
    }
1199
1200
    /**
1201
     * Note in some regions, the national number can be written in two completely different ways
1202
     * depending on whether it forms part of the NATIONAL format or INTERNATIONAL format. The
1203
     * numberFormat parameter here is used to specify which format to use for those cases. If a
1204
     * carrierCode is specified, this will be inserted into the formatted string to replace $CC.
1205
     * @param string $number
1206
     * @param PhoneMetadata $metadata
1207
     * @param int $numberFormat PhoneNumberFormat
1208
     * @param null|string $carrierCode
1209
     * @return string
1210
     */
1211
    protected function formatNsn($number, PhoneMetadata $metadata, $numberFormat, $carrierCode = null)
1212
    {
1213
        $intlNumberFormats = $metadata->intlNumberFormats();
1214
        // When the intlNumberFormats exists, we use that to format national number for the
1215
        // INTERNATIONAL format instead of using the numberDesc.numberFormats.
1216
        $availableFormats = (count($intlNumberFormats) == 0 || $numberFormat == PhoneNumberFormat::NATIONAL)
1217
            ? $metadata->numberFormats()
1218
            : $metadata->intlNumberFormats();
1219
        $formattingPattern = $this->chooseFormattingPatternForNumber($availableFormats, $number);
1220
        return ($formattingPattern === null)
1221
            ? $number
1222
            : $this->formatNsnUsingPattern($number, $formattingPattern, $numberFormat, $carrierCode);
1223
    }
1224
1225
    /**
1226
     * @param NumberFormat[] $availableFormats
1227
     * @param string $nationalNumber
1228
     * @return NumberFormat|null
1229
     */
1230
    public function chooseFormattingPatternForNumber(array $availableFormats, $nationalNumber)
1231
    {
1232
        foreach ($availableFormats as $numFormat) {
1233
            $leadingDigitsPatternMatcher = null;
1234
            $size = $numFormat->leadingDigitsPatternSize();
1235
            // We always use the last leading_digits_pattern, as it is the most detailed.
1236
            if ($size > 0) {
1237
                $leadingDigitsPatternMatcher = new Matcher(
1238
                    $numFormat->getLeadingDigitsPattern($size - 1),
1239
                    $nationalNumber
1240
                );
1241
            }
1242
            if ($size == 0 || $leadingDigitsPatternMatcher->lookingAt()) {
1243
                $m = new Matcher($numFormat->getPattern(), $nationalNumber);
1244
                if ($m->matches() > 0) {
1245
                    return $numFormat;
1246
                }
1247
            }
1248
        }
1249
        return null;
1250
    }
1251
1252
    /**
1253
     * Note that carrierCode is optional - if null or an empty string, no carrier code replacement
1254
     * will take place.
1255
     * @param string $nationalNumber
1256
     * @param NumberFormat $formattingPattern
1257
     * @param int $numberFormat PhoneNumberFormat
1258
     * @param null|string $carrierCode
1259
     * @return string
1260
     */
1261
    public function formatNsnUsingPattern(
1262
        $nationalNumber,
1263
        NumberFormat $formattingPattern,
1264
        $numberFormat,
1265
        $carrierCode = null
1266
    ) {
1267
        $numberFormatRule = $formattingPattern->getFormat();
1268
        $m = new Matcher($formattingPattern->getPattern(), $nationalNumber);
1269
        if ($numberFormat === PhoneNumberFormat::NATIONAL &&
1270
            $carrierCode !== null && mb_strlen($carrierCode) > 0 &&
1271
            mb_strlen($formattingPattern->getDomesticCarrierCodeFormattingRule()) > 0
1272
        ) {
1273
            // Replace the $CC in the formatting rule with the desired carrier code.
1274
            $carrierCodeFormattingRule = $formattingPattern->getDomesticCarrierCodeFormattingRule();
1275
            $ccPatternMatcher = new Matcher(static::CC_PATTERN, $carrierCodeFormattingRule);
1276
            $carrierCodeFormattingRule = $ccPatternMatcher->replaceFirst($carrierCode);
1277
            // Now replace the $FG in the formatting rule with the first group and the carrier code
1278
            // combined in the appropriate way.
1279
            $firstGroupMatcher = new Matcher(static::FIRST_GROUP_PATTERN, $numberFormatRule);
1280
            $numberFormatRule = $firstGroupMatcher->replaceFirst($carrierCodeFormattingRule);
1281
            $formattedNationalNumber = $m->replaceAll($numberFormatRule);
1282
        } else {
1283
            // Use the national prefix formatting rule instead.
1284
            $nationalPrefixFormattingRule = $formattingPattern->getNationalPrefixFormattingRule();
1285
            if ($numberFormat == PhoneNumberFormat::NATIONAL &&
1286
                $nationalPrefixFormattingRule !== null &&
1287
                mb_strlen($nationalPrefixFormattingRule) > 0
1288
            ) {
1289
                $firstGroupMatcher = new Matcher(static::FIRST_GROUP_PATTERN, $numberFormatRule);
1290
                $formattedNationalNumber = $m->replaceAll(
1291
                    $firstGroupMatcher->replaceFirst($nationalPrefixFormattingRule)
1292
                );
1293
            } else {
1294
                $formattedNationalNumber = $m->replaceAll($numberFormatRule);
1295
            }
1296
        }
1297
        if ($numberFormat == PhoneNumberFormat::RFC3966) {
1298
            // Strip any leading punctuation.
1299
            $matcher = new Matcher(static::$SEPARATOR_PATTERN, $formattedNationalNumber);
1300
            if ($matcher->lookingAt()) {
1301
                $formattedNationalNumber = $matcher->replaceFirst("");
1302
            }
1303
            // Replace the rest with a dash between each number group.
1304
            $formattedNationalNumber = $matcher->reset($formattedNationalNumber)->replaceAll("-");
1305
        }
1306
        return $formattedNationalNumber;
1307
    }
1308
1309
    /**
1310
     * Appends the formatted extension of a phone number to formattedNumber, if the phone number had
1311
     * an extension specified.
1312
     *
1313
     * @param PhoneNumber $number
1314
     * @param PhoneMetadata|null $metadata
1315
     * @param int $numberFormat PhoneNumberFormat
1316
     * @param string $formattedNumber
1317
     */
1318
    protected function maybeAppendFormattedExtension(PhoneNumber $number, $metadata, $numberFormat, &$formattedNumber)
1319
    {
1320
        if ($number->hasExtension() && mb_strlen($number->getExtension()) > 0) {
1321
            if ($numberFormat === PhoneNumberFormat::RFC3966) {
1322
                $formattedNumber .= static::RFC3966_EXTN_PREFIX . $number->getExtension();
1323
            } else {
1324
                if (!empty($metadata) && $metadata->hasPreferredExtnPrefix()) {
1325
                    $formattedNumber .= $metadata->getPreferredExtnPrefix() . $number->getExtension();
1326
                } else {
1327
                    $formattedNumber .= static::DEFAULT_EXTN_PREFIX . $number->getExtension();
1328
                }
1329
            }
1330
        }
1331
    }
1332
1333
    /**
1334
     * Returns the mobile token for the provided country calling code if it has one, otherwise
1335
     * returns an empty string. A mobile token is a number inserted before the area code when dialing
1336
     * a mobile number from that country from abroad.
1337
     *
1338
     * @param int $countryCallingCode the country calling code for which we want the mobile token
1339
     * @return string the mobile token, as a string, for the given country calling code
1340
     */
1341
    public static function getCountryMobileToken($countryCallingCode)
1342
    {
1343
        if (count(static::$MOBILE_TOKEN_MAPPINGS) === 0) {
1344
            static::initMobileTokenMappings();
1345
        }
1346
1347
        if (array_key_exists($countryCallingCode, static::$MOBILE_TOKEN_MAPPINGS)) {
1348
            return static::$MOBILE_TOKEN_MAPPINGS[$countryCallingCode];
1349
        }
1350
        return "";
1351
    }
1352
1353
    /**
1354
     * Checks if the number is a valid vanity (alpha) number such as 800 MICROSOFT. A valid vanity
1355
     * number will start with at least 3 digits and will have three or more alpha characters. This
1356
     * does not do region-specific checks - to work out if this number is actually valid for a region,
1357
     * it should be parsed and methods such as {@link #isPossibleNumberWithReason} and
1358
     * {@link #isValidNumber} should be used.
1359
     *
1360
     * @param string $number the number that needs to be checked
1361
     * @return bool true if the number is a valid vanity number
1362
     */
1363
    public function isAlphaNumber($number)
1364
    {
1365
        if (!static::isViablePhoneNumber($number)) {
1366
            // Number is too short, or doesn't match the basic phone number pattern.
1367
            return false;
1368
        }
1369
        $this->maybeStripExtension($number);
1370
        return (bool)preg_match('/' . static::VALID_ALPHA_PHONE_PATTERN . '/' . static::REGEX_FLAGS, $number);
1371
    }
1372
1373
    /**
1374
     * Checks to see if the string of characters could possibly be a phone number at all. At the
1375
     * moment, checks to see that the string begins with at least 2 digits, ignoring any punctuation
1376
     * commonly found in phone numbers.
1377
     * This method does not require the number to be normalized in advance - but does assume that
1378
     * leading non-number symbols have been removed, such as by the method extractPossibleNumber.
1379
     *
1380
     * @param string $number to be checked for viability as a phone number
1381
     * @return boolean true if the number could be a phone number of some sort, otherwise false
1382
     */
1383
    public static function isViablePhoneNumber($number)
1384
    {
1385
        if (static::$VALID_PHONE_NUMBER_PATTERN === null) {
1386
            static::initValidPhoneNumberPatterns();
1387
        }
1388
1389
        if (mb_strlen($number) < static::MIN_LENGTH_FOR_NSN) {
1390
            return false;
1391
        }
1392
1393
        $validPhoneNumberPattern = static::getValidPhoneNumberPattern();
1394
1395
        $m = preg_match($validPhoneNumberPattern, $number);
1396
        return $m > 0;
1397
    }
1398
1399
    /**
1400
     * We append optionally the extension pattern to the end here, as a valid phone number may
1401
     * have an extension prefix appended, followed by 1 or more digits.
1402
     * @return string
1403
     */
1404
    protected static function getValidPhoneNumberPattern()
1405
    {
1406
        return static::$VALID_PHONE_NUMBER_PATTERN;
1407
    }
1408
1409
    /**
1410
     * Strips any extension (as in, the part of the number dialled after the call is connected,
1411
     * usually indicated with extn, ext, x or similar) from the end of the number, and returns it.
1412
     *
1413
     * @param string $number the non-normalized telephone number that we wish to strip the extension from
1414
     * @return string the phone extension
1415
     */
1416
    protected function maybeStripExtension(&$number)
1417
    {
1418
        $matches = array();
1419
        $find = preg_match(static::$EXTN_PATTERN, $number, $matches, PREG_OFFSET_CAPTURE);
1420
        // If we find a potential extension, and the number preceding this is a viable number, we assume
1421
        // it is an extension.
1422
        if ($find > 0 && static::isViablePhoneNumber(substr($number, 0, $matches[0][1]))) {
1423
            // The numbers are captured into groups in the regular expression.
1424
1425
            for ($i = 1, $length = count($matches); $i <= $length; $i++) {
1426
                if ($matches[$i][0] != "") {
1427
                    // We go through the capturing groups until we find one that captured some digits. If none
1428
                    // did, then we will return the empty string.
1429
                    $extension = $matches[$i][0];
1430
                    $number = substr($number, 0, $matches[0][1]);
1431
                    return $extension;
1432
                }
1433
            }
1434
        }
1435
        return "";
1436
    }
1437
1438
    /**
1439
     * Parses a string and returns it in proto buffer format. This method differs from {@link #parse}
1440
     * in that it always populates the raw_input field of the protocol buffer with numberToParse as
1441
     * well as the country_code_source field.
1442
     *
1443
     * @param string $numberToParse number that we are attempting to parse. This can contain formatting
1444
     *                                  such as +, ( and -, as well as a phone number extension. It can also
1445
     *                                  be provided in RFC3966 format.
1446
     * @param string $defaultRegion region that we are expecting the number to be from. This is only used
1447
     *                                  if the number being parsed is not written in international format.
1448
     *                                  The country calling code for the number in this case would be stored
1449
     *                                  as that of the default region supplied.
1450
     * @param PhoneNumber $phoneNumber
1451
     * @return PhoneNumber              a phone number proto buffer filled with the parsed number
1452
     */
1453
    public function parseAndKeepRawInput($numberToParse, $defaultRegion, PhoneNumber $phoneNumber = null)
1454
    {
1455
        if ($phoneNumber === null) {
1456
            $phoneNumber = new PhoneNumber();
1457
        }
1458
        $this->parseHelper($numberToParse, $defaultRegion, true, true, $phoneNumber);
1459
        return $phoneNumber;
1460
    }
1461
1462
    /**
1463
     * Returns an iterable over all PhoneNumberMatches in $text
1464
     *
1465
     * @param string $text
1466
     * @param string $defaultRegion
1467
     * @param AbstractLeniency $leniency Defaults to Leniency::VALID()
1468
     * @param int $maxTries Defaults to PHP_INT_MAX
1469
     * @return PhoneNumberMatcher
1470
     */
1471
    public function findNumbers($text, $defaultRegion, AbstractLeniency $leniency = null, $maxTries = PHP_INT_MAX)
1472
    {
1473
        if ($leniency === null) {
1474
            $leniency = Leniency::VALID();
1475
        }
1476
1477
        return new PhoneNumberMatcher($this, $text, $defaultRegion, $leniency, $maxTries);
1478
    }
1479
1480
    /**
1481
     * Gets an AsYouTypeFormatter for the specific region.
1482
     *
1483
     * @param string $regionCode The region where the phone number is being entered.
1484
     * @return AsYouTypeFormatter
1485
     */
1486
    public function getAsYouTypeFormatter($regionCode)
1487
    {
1488
        return new AsYouTypeFormatter($regionCode);
1489
    }
1490
1491
    /**
1492
     * A helper function to set the values related to leading zeros in a PhoneNumber.
1493
     * @param string $nationalNumber
1494
     * @param PhoneNumber $phoneNumber
1495
     */
1496
    public static function setItalianLeadingZerosForPhoneNumber($nationalNumber, PhoneNumber $phoneNumber)
1497
    {
1498
        if (strlen($nationalNumber) > 1 && substr($nationalNumber, 0, 1) == '0') {
1499
            $phoneNumber->setItalianLeadingZero(true);
1500
            $numberOfLeadingZeros = 1;
1501
            // Note that if the national number is all "0"s, the last "0" is not counted as a leading
1502
            // zero.
1503
            while ($numberOfLeadingZeros < (strlen($nationalNumber) - 1) &&
1504
                substr($nationalNumber, $numberOfLeadingZeros, 1) == '0') {
1505
                $numberOfLeadingZeros++;
1506
            }
1507
1508
            if ($numberOfLeadingZeros != 1) {
1509
                $phoneNumber->setNumberOfLeadingZeros($numberOfLeadingZeros);
1510
            }
1511
        }
1512
    }
1513
1514
    /**
1515
     * Parses a string and fills up the phoneNumber. This method is the same as the public
1516
     * parse() method, with the exception that it allows the default region to be null, for use by
1517
     * isNumberMatch(). checkRegion should be set to false if it is permitted for the default region
1518
     * to be null or unknown ("ZZ").
1519
     * @param string $numberToParse
1520
     * @param string $defaultRegion
1521
     * @param bool $keepRawInput
1522
     * @param bool $checkRegion
1523
     * @param PhoneNumber $phoneNumber
1524
     * @throws NumberParseException
1525
     */
1526
    protected function parseHelper($numberToParse, $defaultRegion, $keepRawInput, $checkRegion, PhoneNumber $phoneNumber)
1527
    {
1528
        if ($numberToParse === null) {
1529
            throw new NumberParseException(NumberParseException::NOT_A_NUMBER, "The phone number supplied was null.");
1530
        }
1531
1532
        $numberToParse = trim($numberToParse);
1533
1534
        if (mb_strlen($numberToParse) > static::MAX_INPUT_STRING_LENGTH) {
1535
            throw new NumberParseException(
1536
                NumberParseException::TOO_LONG,
1537
                "The string supplied was too long to parse."
1538
            );
1539
        }
1540
1541
        $nationalNumber = '';
1542
        $this->buildNationalNumberForParsing($numberToParse, $nationalNumber);
1543
1544
        if (!static::isViablePhoneNumber($nationalNumber)) {
1545
            throw new NumberParseException(
1546
                NumberParseException::NOT_A_NUMBER,
1547
                "The string supplied did not seem to be a phone number."
1548
            );
1549
        }
1550
1551
        // Check the region supplied is valid, or that the extracted number starts with some sort of +
1552
        // sign so the number's region can be determined.
1553
        if ($checkRegion && !$this->checkRegionForParsing($nationalNumber, $defaultRegion)) {
1554
            throw new NumberParseException(
1555
                NumberParseException::INVALID_COUNTRY_CODE,
1556
                "Missing or invalid default region."
1557
            );
1558
        }
1559
1560
        if ($keepRawInput) {
1561
            $phoneNumber->setRawInput($numberToParse);
1562
        }
1563
        // Attempt to parse extension first, since it doesn't require region-specific data and we want
1564
        // to have the non-normalised number here.
1565
        $extension = $this->maybeStripExtension($nationalNumber);
1566
        if (mb_strlen($extension) > 0) {
1567
            $phoneNumber->setExtension($extension);
1568
        }
1569
1570
        $regionMetadata = $this->getMetadataForRegion($defaultRegion);
1571
        // Check to see if the number is given in international format so we know whether this number is
1572
        // from the default region or not.
1573
        $normalizedNationalNumber = "";
1574
        try {
1575
            // TODO: This method should really just take in the string buffer that has already
1576
            // been created, and just remove the prefix, rather than taking in a string and then
1577
            // outputting a string buffer.
1578
            $countryCode = $this->maybeExtractCountryCode(
1579
                $nationalNumber,
1580
                $regionMetadata,
1581
                $normalizedNationalNumber,
1582
                $keepRawInput,
1583
                $phoneNumber
1584
            );
1585
        } catch (NumberParseException $e) {
1586
            $matcher = new Matcher(static::$PLUS_CHARS_PATTERN, $nationalNumber);
1587
            if ($e->getErrorType() == NumberParseException::INVALID_COUNTRY_CODE && $matcher->lookingAt()) {
1588
                // Strip the plus-char, and try again.
1589
                $countryCode = $this->maybeExtractCountryCode(
1590
                    substr($nationalNumber, $matcher->end()),
1591
                    $regionMetadata,
1592
                    $normalizedNationalNumber,
1593
                    $keepRawInput,
1594
                    $phoneNumber
1595
                );
1596
                if ($countryCode == 0) {
1597
                    throw new NumberParseException(
1598
                        NumberParseException::INVALID_COUNTRY_CODE,
1599
                        "Could not interpret numbers after plus-sign."
1600
                    );
1601
                }
1602
            } else {
1603
                throw new NumberParseException($e->getErrorType(), $e->getMessage(), $e);
1604
            }
1605
        }
1606
        if ($countryCode !== 0) {
1607
            $phoneNumberRegion = $this->getRegionCodeForCountryCode($countryCode);
1608
            if ($phoneNumberRegion != $defaultRegion) {
1609
                // Metadata cannot be null because the country calling code is valid.
1610
                $regionMetadata = $this->getMetadataForRegionOrCallingCode($countryCode, $phoneNumberRegion);
1611
            }
1612
        } else {
1613
            // If no extracted country calling code, use the region supplied instead. The national number
1614
            // is just the normalized version of the number we were given to parse.
1615
1616
            $normalizedNationalNumber .= static::normalize($nationalNumber);
1617
            if ($defaultRegion !== null) {
1618
                $countryCode = $regionMetadata->getCountryCode();
1619
                $phoneNumber->setCountryCode($countryCode);
1620
            } elseif ($keepRawInput) {
1621
                $phoneNumber->clearCountryCodeSource();
1622
            }
1623
        }
1624
        if (mb_strlen($normalizedNationalNumber) < static::MIN_LENGTH_FOR_NSN) {
1625
            throw new NumberParseException(
1626
                NumberParseException::TOO_SHORT_NSN,
1627
                "The string supplied is too short to be a phone number."
1628
            );
1629
        }
1630
        if ($regionMetadata !== null) {
1631
            $carrierCode = "";
1632
            $potentialNationalNumber = $normalizedNationalNumber;
1633
            $this->maybeStripNationalPrefixAndCarrierCode($potentialNationalNumber, $regionMetadata, $carrierCode);
1634
            // We require that the NSN remaining after stripping the national prefix and carrier code be
1635
            // long enough to be a possible length for the region. Otherwise, we don't do the stripping,
1636
            // since the original number could be a valid short number.
1637
            if ($this->testNumberLength($potentialNationalNumber, $regionMetadata) !== ValidationResult::TOO_SHORT) {
1638
                $normalizedNationalNumber = $potentialNationalNumber;
1639
                if ($keepRawInput && mb_strlen($carrierCode) > 0) {
1640
                    $phoneNumber->setPreferredDomesticCarrierCode($carrierCode);
1641
                }
1642
            }
1643
        }
1644
        $lengthOfNationalNumber = mb_strlen($normalizedNationalNumber);
1645
        if ($lengthOfNationalNumber < static::MIN_LENGTH_FOR_NSN) {
1646
            throw new NumberParseException(
1647
                NumberParseException::TOO_SHORT_NSN,
1648
                "The string supplied is too short to be a phone number."
1649
            );
1650
        }
1651
        if ($lengthOfNationalNumber > static::MAX_LENGTH_FOR_NSN) {
1652
            throw new NumberParseException(
1653
                NumberParseException::TOO_LONG,
1654
                "The string supplied is too long to be a phone number."
1655
            );
1656
        }
1657
        static::setItalianLeadingZerosForPhoneNumber($normalizedNationalNumber, $phoneNumber);
1658
1659
        /*
1660
         * We have to store the National Number as a string instead of a "long" as Google do
1661
         *
1662
         * Since PHP doesn't always support 64 bit INTs, this was a float, but that had issues
1663
         * with long numbers.
1664
         *
1665
         * We have to remove the leading zeroes ourself though
1666
         */
1667
        if ((int)$normalizedNationalNumber == 0) {
1668
            $normalizedNationalNumber = "0";
1669
        } else {
1670
            $normalizedNationalNumber = ltrim($normalizedNationalNumber, '0');
1671
        }
1672
1673
        $phoneNumber->setNationalNumber($normalizedNationalNumber);
1674
    }
1675
1676
    /**
1677
     * Returns a new phone number containing only the fields needed to uniquely identify a phone
1678
     * number, rather than any fields that capture the context in which  the phone number was created.
1679
     * These fields correspond to those set in parse() rather than parseAndKeepRawInput()
1680
     *
1681
     * @param PhoneNumber $phoneNumberIn
1682
     * @return PhoneNumber
1683
     */
1684
    protected static function copyCoreFieldsOnly(PhoneNumber $phoneNumberIn)
1685
    {
1686
        $phoneNumber = new PhoneNumber();
1687
        $phoneNumber->setCountryCode($phoneNumberIn->getCountryCode());
1688
        $phoneNumber->setNationalNumber($phoneNumberIn->getNationalNumber());
1689
        if (mb_strlen($phoneNumberIn->getExtension()) > 0) {
1690
            $phoneNumber->setExtension($phoneNumberIn->getExtension());
1691
        }
1692
        if ($phoneNumberIn->isItalianLeadingZero()) {
1693
            $phoneNumber->setItalianLeadingZero(true);
1694
            // This field is only relevant if there are leading zeros at all.
1695
            $phoneNumber->setNumberOfLeadingZeros($phoneNumberIn->getNumberOfLeadingZeros());
1696
        }
1697
        return $phoneNumber;
1698
    }
1699
1700
    /**
1701
     * Converts numberToParse to a form that we can parse and write it to nationalNumber if it is
1702
     * written in RFC3966; otherwise extract a possible number out of it and write to nationalNumber.
1703
     * @param string $numberToParse
1704
     * @param string $nationalNumber
1705
     */
1706
    protected function buildNationalNumberForParsing($numberToParse, &$nationalNumber)
1707
    {
1708
        $indexOfPhoneContext = strpos($numberToParse, static::RFC3966_PHONE_CONTEXT);
1709
        if ($indexOfPhoneContext > 0) {
1710
            $phoneContextStart = $indexOfPhoneContext + mb_strlen(static::RFC3966_PHONE_CONTEXT);
1711
            // If the phone context contains a phone number prefix, we need to capture it, whereas domains
1712
            // will be ignored.
1713
            if (substr($numberToParse, $phoneContextStart, 1) == static::PLUS_SIGN) {
1714
                // Additional parameters might follow the phone context. If so, we will remove them here
1715
                // because the parameters after phone context are not important for parsing the
1716
                // phone number.
1717
                $phoneContextEnd = strpos($numberToParse, ';', $phoneContextStart);
1718
                if ($phoneContextEnd > 0) {
1719
                    $nationalNumber .= substr($numberToParse, $phoneContextStart, $phoneContextEnd - $phoneContextStart);
1720
                } else {
1721
                    $nationalNumber .= substr($numberToParse, $phoneContextStart);
1722
                }
1723
            }
1724
1725
            // Now append everything between the "tel:" prefix and the phone-context. This should include
1726
            // the national number, an optional extension or isdn-subaddress component. Note we also
1727
            // handle the case when "tel:" is missing, as we have seen in some of the phone number inputs.
1728
            // In that case, we append everything from the beginning.
1729
1730
            $indexOfRfc3966Prefix = strpos($numberToParse, static::RFC3966_PREFIX);
1731
            $indexOfNationalNumber = ($indexOfRfc3966Prefix !== false) ? $indexOfRfc3966Prefix + strlen(static::RFC3966_PREFIX) : 0;
1732
            $nationalNumber .= substr($numberToParse, $indexOfNationalNumber, ($indexOfPhoneContext - $indexOfNationalNumber));
1733
        } else {
1734
            // Extract a possible number from the string passed in (this strips leading characters that
1735
            // could not be the start of a phone number.)
1736
            $nationalNumber .= static::extractPossibleNumber($numberToParse);
1737
        }
1738
1739
        // Delete the isdn-subaddress and everything after it if it is present. Note extension won't
1740
        // appear at the same time with isdn-subaddress according to paragraph 5.3 of the RFC3966 spec,
1741
        $indexOfIsdn = strpos($nationalNumber, static::RFC3966_ISDN_SUBADDRESS);
1742
        if ($indexOfIsdn > 0) {
1743
            $nationalNumber = substr($nationalNumber, 0, $indexOfIsdn);
1744
        }
1745
        // If both phone context and isdn-subaddress are absent but other parameters are present, the
1746
        // parameters are left in nationalNumber. This is because we are concerned about deleting
1747
        // content from a potential number string when there is no strong evidence that the number is
1748
        // actually written in RFC3966.
1749
    }
1750
1751
    /**
1752
     * Attempts to extract a possible number from the string passed in. This currently strips all
1753
     * leading characters that cannot be used to start a phone number. Characters that can be used to
1754
     * start a phone number are defined in the VALID_START_CHAR_PATTERN. If none of these characters
1755
     * are found in the number passed in, an empty string is returned. This function also attempts to
1756
     * strip off any alternative extensions or endings if two or more are present, such as in the case
1757
     * of: (530) 583-6985 x302/x2303. The second extension here makes this actually two phone numbers,
1758
     * (530) 583-6985 x302 and (530) 583-6985 x2303. We remove the second extension so that the first
1759
     * number is parsed correctly.
1760
     *
1761
     * @param int $number the string that might contain a phone number
1762
     * @return string the number, stripped of any non-phone-number prefix (such as "Tel:") or an empty
1763
     *                string if no character used to start phone numbers (such as + or any digit) is
1764
     *                found in the number
1765
     */
1766
    public static function extractPossibleNumber($number)
1767
    {
1768
        if (static::$VALID_START_CHAR_PATTERN === null) {
1769
            static::initValidStartCharPattern();
1770
        }
1771
1772
        $matches = array();
1773
        $match = preg_match('/' . static::$VALID_START_CHAR_PATTERN . '/ui', $number, $matches, PREG_OFFSET_CAPTURE);
1774
        if ($match > 0) {
1775
            $number = substr($number, $matches[0][1]);
1776
            // Remove trailing non-alpha non-numerical characters.
1777
            $trailingCharsMatcher = new Matcher(static::$UNWANTED_END_CHAR_PATTERN, $number);
1778
            if ($trailingCharsMatcher->find() && $trailingCharsMatcher->start() > 0) {
1779
                $number = substr($number, 0, $trailingCharsMatcher->start());
1780
            }
1781
1782
            // Check for extra numbers at the end.
1783
            $match = preg_match('%' . static::$SECOND_NUMBER_START_PATTERN . '%', $number, $matches, PREG_OFFSET_CAPTURE);
1784
            if ($match > 0) {
1785
                $number = substr($number, 0, $matches[0][1]);
1786
            }
1787
1788
            return $number;
1789
        } else {
1790
            return "";
1791
        }
1792
    }
1793
1794
    /**
1795
     * Checks to see that the region code used is valid, or if it is not valid, that the number to
1796
     * parse starts with a + symbol so that we can attempt to infer the region from the number.
1797
     * Returns false if it cannot use the region provided and the region cannot be inferred.
1798
     * @param string $numberToParse
1799
     * @param string $defaultRegion
1800
     * @return bool
1801
     */
1802
    protected function checkRegionForParsing($numberToParse, $defaultRegion)
1803
    {
1804
        if (!$this->isValidRegionCode($defaultRegion)) {
1805
            // If the number is null or empty, we can't infer the region.
1806
            $plusCharsPatternMatcher = new Matcher(static::$PLUS_CHARS_PATTERN, $numberToParse);
1807
            if ($numberToParse === null || mb_strlen($numberToParse) == 0 || !$plusCharsPatternMatcher->lookingAt()) {
1808
                return false;
1809
            }
1810
        }
1811
        return true;
1812
    }
1813
1814
    /**
1815
     * Tries to extract a country calling code from a number. This method will return zero if no
1816
     * country calling code is considered to be present. Country calling codes are extracted in the
1817
     * following ways:
1818
     * <ul>
1819
     *  <li> by stripping the international dialing prefix of the region the person is dialing from,
1820
     *       if this is present in the number, and looking at the next digits
1821
     *  <li> by stripping the '+' sign if present and then looking at the next digits
1822
     *  <li> by comparing the start of the number and the country calling code of the default region.
1823
     *       If the number is not considered possible for the numbering plan of the default region
1824
     *       initially, but starts with the country calling code of this region, validation will be
1825
     *       reattempted after stripping this country calling code. If this number is considered a
1826
     *       possible number, then the first digits will be considered the country calling code and
1827
     *       removed as such.
1828
     * </ul>
1829
     * It will throw a NumberParseException if the number starts with a '+' but the country calling
1830
     * code supplied after this does not match that of any known region.
1831
     *
1832
     * @param string $number non-normalized telephone number that we wish to extract a country calling
1833
     *     code from - may begin with '+'
1834
     * @param PhoneMetadata $defaultRegionMetadata metadata about the region this number may be from
1835
     * @param string $nationalNumber a string buffer to store the national significant number in, in the case
1836
     *     that a country calling code was extracted. The number is appended to any existing contents.
1837
     *     If no country calling code was extracted, this will be left unchanged.
1838
     * @param bool $keepRawInput true if the country_code_source and preferred_carrier_code fields of
1839
     *     phoneNumber should be populated.
1840
     * @param PhoneNumber $phoneNumber the PhoneNumber object where the country_code and country_code_source need
1841
     *     to be populated. Note the country_code is always populated, whereas country_code_source is
1842
     *     only populated when keepCountryCodeSource is true.
1843
     * @return int the country calling code extracted or 0 if none could be extracted
1844
     * @throws NumberParseException
1845
     */
1846
    public function maybeExtractCountryCode(
1847
        $number,
1848
        PhoneMetadata $defaultRegionMetadata = null,
1849
        &$nationalNumber,
1850
        $keepRawInput,
1851
        PhoneNumber $phoneNumber
1852
    ) {
1853
        if (mb_strlen($number) == 0) {
1854
            return 0;
1855
        }
1856
        $fullNumber = $number;
1857
        // Set the default prefix to be something that will never match.
1858
        $possibleCountryIddPrefix = "NonMatch";
1859
        if ($defaultRegionMetadata !== null) {
1860
            $possibleCountryIddPrefix = $defaultRegionMetadata->getInternationalPrefix();
1861
        }
1862
        $countryCodeSource = $this->maybeStripInternationalPrefixAndNormalize($fullNumber, $possibleCountryIddPrefix);
1863
1864
        if ($keepRawInput) {
1865
            $phoneNumber->setCountryCodeSource($countryCodeSource);
1866
        }
1867
        if ($countryCodeSource != CountryCodeSource::FROM_DEFAULT_COUNTRY) {
1868
            if (mb_strlen($fullNumber) <= static::MIN_LENGTH_FOR_NSN) {
1869
                throw new NumberParseException(
1870
                    NumberParseException::TOO_SHORT_AFTER_IDD,
1871
                    "Phone number had an IDD, but after this was not long enough to be a viable phone number."
1872
                );
1873
            }
1874
            $potentialCountryCode = $this->extractCountryCode($fullNumber, $nationalNumber);
1875
1876
            if ($potentialCountryCode != 0) {
1877
                $phoneNumber->setCountryCode($potentialCountryCode);
1878
                return $potentialCountryCode;
1879
            }
1880
1881
            // If this fails, they must be using a strange country calling code that we don't recognize,
1882
            // or that doesn't exist.
1883
            throw new NumberParseException(
1884
                NumberParseException::INVALID_COUNTRY_CODE,
1885
                "Country calling code supplied was not recognised."
1886
            );
1887
        } elseif ($defaultRegionMetadata !== null) {
1888
            // Check to see if the number starts with the country calling code for the default region. If
1889
            // so, we remove the country calling code, and do some checks on the validity of the number
1890
            // before and after.
1891
            $defaultCountryCode = $defaultRegionMetadata->getCountryCode();
1892
            $defaultCountryCodeString = (string)$defaultCountryCode;
1893
            $normalizedNumber = (string)$fullNumber;
1894
            if (strpos($normalizedNumber, $defaultCountryCodeString) === 0) {
1895
                $potentialNationalNumber = substr($normalizedNumber, mb_strlen($defaultCountryCodeString));
1896
                $generalDesc = $defaultRegionMetadata->getGeneralDesc();
1897
                $validNumberPattern = $generalDesc->getNationalNumberPattern();
1898
                // Don't need the carrier code.
1899
                $carriercode = null;
1900
                $this->maybeStripNationalPrefixAndCarrierCode(
1901
                    $potentialNationalNumber,
1902
                    $defaultRegionMetadata,
1903
                    $carriercode
1904
                );
1905
                // If the number was not valid before but is valid now, or if it was too long before, we
1906
                // consider the number with the country calling code stripped to be a better result and
1907
                // keep that instead.
1908
                $validNumberPatternFullNumberMatcher = new Matcher($validNumberPattern, $fullNumber);
1909
                $validNumberPatternPotentialNationalNumberMatcher = new Matcher($validNumberPattern, $potentialNationalNumber);
1910
                if ((!$validNumberPatternFullNumberMatcher->matches()
1911
                        && $validNumberPatternPotentialNationalNumberMatcher->matches())
1912
                    || $this->testNumberLength($fullNumber, $defaultRegionMetadata) === ValidationResult::TOO_LONG
1913
                ) {
1914
                    $nationalNumber .= $potentialNationalNumber;
1915
                    if ($keepRawInput) {
1916
                        $phoneNumber->setCountryCodeSource(CountryCodeSource::FROM_NUMBER_WITHOUT_PLUS_SIGN);
1917
                    }
1918
                    $phoneNumber->setCountryCode($defaultCountryCode);
1919
                    return $defaultCountryCode;
1920
                }
1921
            }
1922
        }
1923
        // No country calling code present.
1924
        $phoneNumber->setCountryCode(0);
1925
        return 0;
1926
    }
1927
1928
    /**
1929
     * Strips any international prefix (such as +, 00, 011) present in the number provided, normalizes
1930
     * the resulting number, and indicates if an international prefix was present.
1931
     *
1932
     * @param string $number the non-normalized telephone number that we wish to strip any international
1933
     *     dialing prefix from.
1934
     * @param string $possibleIddPrefix string the international direct dialing prefix from the region we
1935
     *     think this number may be dialed in
1936
     * @return int the corresponding CountryCodeSource if an international dialing prefix could be
1937
     *     removed from the number, otherwise CountryCodeSource.FROM_DEFAULT_COUNTRY if the number did
1938
     *     not seem to be in international format.
1939
     */
1940
    public function maybeStripInternationalPrefixAndNormalize(&$number, $possibleIddPrefix)
1941
    {
1942
        if (mb_strlen($number) == 0) {
1943
            return CountryCodeSource::FROM_DEFAULT_COUNTRY;
1944
        }
1945
        $matches = array();
1946
        // Check to see if the number begins with one or more plus signs.
1947
        $match = preg_match('/^' . static::$PLUS_CHARS_PATTERN . '/' . static::REGEX_FLAGS, $number, $matches, PREG_OFFSET_CAPTURE);
1948
        if ($match > 0) {
1949
            $number = mb_substr($number, $matches[0][1] + mb_strlen($matches[0][0]));
1950
            // Can now normalize the rest of the number since we've consumed the "+" sign at the start.
1951
            $number = static::normalize($number);
1952
            return CountryCodeSource::FROM_NUMBER_WITH_PLUS_SIGN;
1953
        }
1954
        // Attempt to parse the first digits as an international prefix.
1955
        $iddPattern = $possibleIddPrefix;
1956
        $number = static::normalize($number);
1957
        return $this->parsePrefixAsIdd($iddPattern, $number)
1958
            ? CountryCodeSource::FROM_NUMBER_WITH_IDD
1959
            : CountryCodeSource::FROM_DEFAULT_COUNTRY;
1960
    }
1961
1962
    /**
1963
     * Normalizes a string of characters representing a phone number. This performs
1964
     * the following conversions:
1965
     *   Punctuation is stripped.
1966
     *   For ALPHA/VANITY numbers:
1967
     *   Letters are converted to their numeric representation on a telephone
1968
     *       keypad. The keypad used here is the one defined in ITU Recommendation
1969
     *       E.161. This is only done if there are 3 or more letters in the number,
1970
     *       to lessen the risk that such letters are typos.
1971
     *   For other numbers:
1972
     *   Wide-ascii digits are converted to normal ASCII (European) digits.
1973
     *   Arabic-Indic numerals are converted to European numerals.
1974
     *   Spurious alpha characters are stripped.
1975
     *
1976
     * @param string $number a string of characters representing a phone number.
1977
     * @return string the normalized string version of the phone number.
1978
     */
1979
    public static function normalize(&$number)
1980
    {
1981
        if (static::$ALPHA_PHONE_MAPPINGS === null) {
1982
            static::initAlphaPhoneMappings();
1983
        }
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
        } else {
1989
            return static::normalizeDigitsOnly($number);
1990
        }
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 $number string  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($number)
2001
    {
2002
        return static::normalizeDigits($number, false /* strip non-digits */);
2003
    }
2004
2005
    /**
2006
     * @param string $number
2007
     * @param bool $keepNonDigits
2008
     * @return string
2009
     */
2010
    public static function normalizeDigits($number, $keepNonDigits)
2011
    {
2012
        $normalizedDigits = "";
2013
        $numberAsArray = preg_split('/(?<!^)(?!$)/u', $number);
2014
        foreach ($numberAsArray as $character) {
2015
            // Check if we are in the unicode number range
2016
            if (array_key_exists($character, static::$numericCharacters)) {
2017
                $normalizedDigits .= static::$numericCharacters[$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
     * @param string $iddPattern
2031
     * @param string $number
2032
     * @return bool
2033
     */
2034
    protected function parsePrefixAsIdd($iddPattern, &$number)
2035
    {
2036
        $m = new Matcher($iddPattern, $number);
2037
        if ($m->lookingAt()) {
2038
            $matchEnd = $m->end();
2039
            // Only strip this if the first digit after the match is not a 0, since country calling codes
2040
            // cannot begin with 0.
2041
            $digitMatcher = new Matcher(static::$CAPTURING_DIGIT_PATTERN, substr($number, $matchEnd));
2042
            if ($digitMatcher->find()) {
2043
                $normalizedGroup = static::normalizeDigitsOnly($digitMatcher->group(1));
2044
                if ($normalizedGroup == "0") {
2045
                    return false;
2046
                }
2047
            }
2048
            $number = substr($number, $matchEnd);
2049
            return true;
2050
        }
2051
        return false;
2052
    }
2053
2054
    /**
2055
     * Extracts country calling code from fullNumber, returns it and places the remaining number in  nationalNumber.
2056
     * It assumes that the leading plus sign or IDD has already been removed.
2057
     * Returns 0 if fullNumber doesn't start with a valid country calling code, and leaves nationalNumber unmodified.
2058
     * @param string $fullNumber
2059
     * @param string $nationalNumber
2060
     * @return int
2061
     * @internal
2062
     */
2063
    public function extractCountryCode($fullNumber, &$nationalNumber)
2064
    {
2065
        if ((mb_strlen($fullNumber) == 0) || ($fullNumber[0] == '0')) {
2066
            // Country codes do not begin with a '0'.
2067
            return 0;
2068
        }
2069
        $numberLength = mb_strlen($fullNumber);
2070
        for ($i = 1; $i <= static::MAX_LENGTH_COUNTRY_CODE && $i <= $numberLength; $i++) {
2071
            $potentialCountryCode = (int)substr($fullNumber, 0, $i);
2072
            if (isset($this->countryCallingCodeToRegionCodeMap[$potentialCountryCode])) {
2073
                $nationalNumber .= substr($fullNumber, $i);
2074
                return $potentialCountryCode;
2075
            }
2076
        }
2077
        return 0;
2078
    }
2079
2080
    /**
2081
     * Strips any national prefix (such as 0, 1) present in the number provided.
2082
     *
2083
     * @param string $number the normalized telephone number that we wish to strip any national
2084
     *     dialing prefix from
2085
     * @param PhoneMetadata $metadata the metadata for the region that we think this number is from
2086
     * @param string $carrierCode a place to insert the carrier code if one is extracted
2087
     * @return bool true if a national prefix or carrier code (or both) could be extracted.
2088
     */
2089
    public function maybeStripNationalPrefixAndCarrierCode(&$number, PhoneMetadata $metadata, &$carrierCode)
2090
    {
2091
        $numberLength = mb_strlen($number);
2092
        $possibleNationalPrefix = $metadata->getNationalPrefixForParsing();
2093
        if ($numberLength == 0 || $possibleNationalPrefix === null || mb_strlen($possibleNationalPrefix) == 0) {
2094
            // Early return for numbers of zero length.
2095
            return false;
2096
        }
2097
2098
        // Attempt to parse the first digits as a national prefix.
2099
        $prefixMatcher = new Matcher($possibleNationalPrefix, $number);
2100
        if ($prefixMatcher->lookingAt()) {
2101
            $nationalNumberRule = $metadata->getGeneralDesc()->getNationalNumberPattern();
2102
            // Check if the original number is viable.
2103
            $nationalNumberRuleMatcher = new Matcher($nationalNumberRule, $number);
2104
            $isViableOriginalNumber = $nationalNumberRuleMatcher->matches();
2105
            // $prefixMatcher->group($numOfGroups) === null implies nothing was captured by the capturing
2106
            // groups in $possibleNationalPrefix; therefore, no transformation is necessary, and we just
2107
            // remove the national prefix
2108
            $numOfGroups = $prefixMatcher->groupCount();
2109
            $transformRule = $metadata->getNationalPrefixTransformRule();
2110
            if ($transformRule === null
2111
                || mb_strlen($transformRule) == 0
2112
                || $prefixMatcher->group($numOfGroups - 1) === null
2113
            ) {
2114
                // If the original number was viable, and the resultant number is not, we return.
2115
                $matcher = new Matcher($nationalNumberRule, substr($number, $prefixMatcher->end()));
2116
                if ($isViableOriginalNumber && !$matcher->matches()) {
2117
                    return false;
2118
                }
2119
                if ($carrierCode !== null && $numOfGroups > 0 && $prefixMatcher->group($numOfGroups) !== null) {
2120
                    $carrierCode .= $prefixMatcher->group(1);
2121
                }
2122
2123
                $number = substr($number, $prefixMatcher->end());
2124
                return true;
2125
            } else {
2126
                // Check that the resultant number is still viable. If not, return. Check this by copying
2127
                // the string and making the transformation on the copy first.
2128
                $transformedNumber = $number;
2129
                $transformedNumber = substr_replace(
2130
                    $transformedNumber,
2131
                    $prefixMatcher->replaceFirst($transformRule),
2132
                    0,
2133
                    $numberLength
2134
                );
2135
                $matcher = new Matcher($nationalNumberRule, $transformedNumber);
2136
                if ($isViableOriginalNumber && !$matcher->matches()) {
2137
                    return false;
2138
                }
2139
                if ($carrierCode !== null && $numOfGroups > 1) {
2140
                    $carrierCode .= $prefixMatcher->group(1);
2141
                }
2142
                $number = substr_replace($number, $transformedNumber, 0, mb_strlen($number));
2143
                return true;
2144
            }
2145
        }
2146
        return false;
2147
    }
2148
2149
    /**
2150
     * Convenience wrapper around isPossibleNumberForTypeWithReason. Instead of returning the reason
2151
     * reason for failure, this method returns true if the number is either a possible fully-qualified
2152
     * number (containing the area code and country code), or if the number could be a possible local
2153
     * number (with a country code, but missing an area code). Local numbers are considered possible
2154
     * if they could be possibly dialled in this format: if the area code is needed for a call to
2155
     * connect, the number is not considered possible without it.
2156
     *
2157
     * @param PhoneNumber $number The number that needs to be checked
2158
     * @param int $type PhoneNumberType The type we are interested in
2159
     * @return bool true if the number is possible for this particular type
2160
     */
2161
    public function isPossibleNumberForType(PhoneNumber $number, $type)
2162
    {
2163
        $result = $this->isPossibleNumberForTypeWithReason($number, $type);
2164
        return $result === ValidationResult::IS_POSSIBLE
2165
            || $result === ValidationResult::IS_POSSIBLE_LOCAL_ONLY;
2166
    }
2167
2168
    /**
2169
     * Helper method to check a number against possible lengths for this number type, and determine
2170
     * whether it matches, or is too short or too long. Currently, if a number pattern suggests that
2171
     * numbers of length 7 and 10 are possible, and a number in between these possible lengths is
2172
     * entered, such as of length 8, this will return TOO_LONG.
2173
     *
2174
     * @param string $number
2175
     * @param PhoneMetadata $metadata
2176
     * @param int $type PhoneNumberType
2177
     * @return int ValidationResult
2178
     */
2179
    protected function testNumberLength($number, PhoneMetadata $metadata, $type = PhoneNumberType::UNKNOWN)
2180
    {
2181
        $descForType = $this->getNumberDescByType($metadata, $type);
2182
        // There should always be "possibleLengths" set for every element. This is declared in the XML
2183
        // schema which is verified by PhoneNumberMetadataSchemaTest.
2184
        // For size efficiency, where a sub-description (e.g. fixed-line) has the same possibleLengths
2185
        // as the parent, this is missing, so we fall back to the general desc (where no numbers of the
2186
        // type exist at all, there is one possible length (-1) which is guaranteed not to match the
2187
        // length of any real phone number).
2188
        $possibleLengths = (count($descForType->getPossibleLength()) === 0)
2189
            ? $metadata->getGeneralDesc()->getPossibleLength() : $descForType->getPossibleLength();
2190
2191
        $localLengths = $descForType->getPossibleLengthLocalOnly();
2192
2193
        if ($type === PhoneNumberType::FIXED_LINE_OR_MOBILE) {
2194
            if (!static::descHasPossibleNumberData($this->getNumberDescByType($metadata, PhoneNumberType::FIXED_LINE))) {
2195
                // The rate case has been encountered where no fixedLine data is available (true for some
2196
                // non-geographical entities), so we just check mobile.
2197
                return $this->testNumberLength($number, $metadata, PhoneNumberType::MOBILE);
2198
            } else {
2199
                $mobileDesc = $this->getNumberDescByType($metadata, PhoneNumberType::MOBILE);
2200
                if (static::descHasPossibleNumberData($mobileDesc)) {
2201
                    // Note that when adding the possible lengths from mobile, we have to again check they
2202
                    // aren't empty since if they are this indicates they are the same as the general desc and
2203
                    // should be obtained from there.
2204
                    $possibleLengths = array_merge($possibleLengths,
2205
                        (count($mobileDesc->getPossibleLength()) === 0)
2206
                            ? $metadata->getGeneralDesc()->getPossibleLength() : $mobileDesc->getPossibleLength());
2207
2208
                    // The current list is sorted; we need to merge in the new list and re-sort (duplicates
2209
                    // are okay). Sorting isn't so expensive because the lists are very small.
2210
                    sort($possibleLengths);
2211
2212
                    if (count($localLengths) === 0) {
2213
                        $localLengths = $mobileDesc->getPossibleLengthLocalOnly();
2214
                    } else {
2215
                        $localLengths = array_merge($localLengths, $mobileDesc->getPossibleLengthLocalOnly());
2216
                        sort($localLengths);
2217
                    }
2218
                }
2219
            }
2220
        }
2221
2222
2223
        // If the type is not supported at all (indicated by the possible lengths containing -1 at this
2224
        // point) we return invalid length.
2225
2226
        if ($possibleLengths[0] === -1) {
2227
            return ValidationResult::INVALID_LENGTH;
2228
        }
2229
2230
        $actualLength = mb_strlen($number);
2231
2232
        // This is safe because there is never an overlap between the possible lengths and the local-only
2233
        // lengths; this is checked at build time.
2234
2235
        if (in_array($actualLength, $localLengths)) {
2236
            return ValidationResult::IS_POSSIBLE_LOCAL_ONLY;
2237
        }
2238
2239
        $minimumLength = reset($possibleLengths);
2240
        if ($minimumLength == $actualLength) {
2241
            return ValidationResult::IS_POSSIBLE;
2242
        } elseif ($minimumLength > $actualLength) {
2243
            return ValidationResult::TOO_SHORT;
2244
        } elseif (isset($possibleLengths[count($possibleLengths) - 1]) && $possibleLengths[count($possibleLengths) - 1] < $actualLength) {
2245
            return ValidationResult::TOO_LONG;
2246
        }
2247
2248
        // We skip the first element; we've already checked it.
2249
        array_shift($possibleLengths);
2250
        return in_array($actualLength, $possibleLengths) ? ValidationResult::IS_POSSIBLE : ValidationResult::INVALID_LENGTH;
2251
    }
2252
2253
    /**
2254
     * Returns a list with the region codes that match the specific country calling code. For
2255
     * non-geographical country calling codes, the region code 001 is returned. Also, in the case
2256
     * of no region code being found, an empty list is returned.
2257
     * @param int $countryCallingCode
2258
     * @return array
2259
     */
2260
    public function getRegionCodesForCountryCode($countryCallingCode)
2261
    {
2262
        $regionCodes = isset($this->countryCallingCodeToRegionCodeMap[$countryCallingCode]) ? $this->countryCallingCodeToRegionCodeMap[$countryCallingCode] : null;
2263
        return $regionCodes === null ? array() : $regionCodes;
2264
    }
2265
2266
    /**
2267
     * Returns the country calling code for a specific region. For example, this would be 1 for the
2268
     * United States, and 64 for New Zealand. Assumes the region is already valid.
2269
     *
2270
     * @param string $regionCode the region that we want to get the country calling code for
2271
     * @return int the country calling code for the region denoted by regionCode
2272
     */
2273
    public function getCountryCodeForRegion($regionCode)
2274
    {
2275
        if (!$this->isValidRegionCode($regionCode)) {
2276
            return 0;
2277
        }
2278
        return $this->getCountryCodeForValidRegion($regionCode);
2279
    }
2280
2281
    /**
2282
     * Returns the country calling code for a specific region. For example, this would be 1 for the
2283
     * United States, and 64 for New Zealand. Assumes the region is already valid.
2284
     *
2285
     * @param string $regionCode the region that we want to get the country calling code for
2286
     * @return int the country calling code for the region denoted by regionCode
2287
     * @throws \InvalidArgumentException if the region is invalid
2288
     */
2289
    protected function getCountryCodeForValidRegion($regionCode)
2290
    {
2291
        $metadata = $this->getMetadataForRegion($regionCode);
2292
        if ($metadata === null) {
2293
            throw new \InvalidArgumentException("Invalid region code: " . $regionCode);
2294
        }
2295
        return $metadata->getCountryCode();
2296
    }
2297
2298
    /**
2299
     * Returns a number formatted in such a way that it can be dialed from a mobile phone in a
2300
     * specific region. If the number cannot be reached from the region (e.g. some countries block
2301
     * toll-free numbers from being called outside of the country), the method returns an empty
2302
     * string.
2303
     *
2304
     * @param PhoneNumber $number the phone number to be formatted
2305
     * @param string $regionCallingFrom the region where the call is being placed
2306
     * @param boolean $withFormatting whether the number should be returned with formatting symbols, such as
2307
     *     spaces and dashes.
2308
     * @return string the formatted phone number
2309
     */
2310
    public function formatNumberForMobileDialing(PhoneNumber $number, $regionCallingFrom, $withFormatting)
2311
    {
2312
        $countryCallingCode = $number->getCountryCode();
2313
        if (!$this->hasValidCountryCallingCode($countryCallingCode)) {
2314
            return $number->hasRawInput() ? $number->getRawInput() : "";
2315
        }
2316
2317
        $formattedNumber = "";
2318
        // Clear the extension, as that part cannot normally be dialed together with the main number.
2319
        $numberNoExt = new PhoneNumber();
2320
        $numberNoExt->mergeFrom($number)->clearExtension();
2321
        $regionCode = $this->getRegionCodeForCountryCode($countryCallingCode);
2322
        $numberType = $this->getNumberType($numberNoExt);
2323
        $isValidNumber = ($numberType !== PhoneNumberType::UNKNOWN);
2324
        if ($regionCallingFrom == $regionCode) {
2325
            $isFixedLineOrMobile = ($numberType == PhoneNumberType::FIXED_LINE) || ($numberType == PhoneNumberType::MOBILE) || ($numberType == PhoneNumberType::FIXED_LINE_OR_MOBILE);
2326
            // Carrier codes may be needed in some countries. We handle this here.
2327
            if ($regionCode == "CO" && $numberType == PhoneNumberType::FIXED_LINE) {
2328
                $formattedNumber = $this->formatNationalNumberWithCarrierCode(
2329
                    $numberNoExt,
2330
                    static::COLOMBIA_MOBILE_TO_FIXED_LINE_PREFIX
2331
                );
2332
            } elseif ($regionCode == "BR" && $isFixedLineOrMobile) {
2333
                // Historically, we set this to an empty string when parsing with raw input if none was
2334
                // found in the input string. However, this doesn't result in a number we can dial. For this
2335
                // reason, we treat the empty string the same as if it isn't set at all.
2336
                $formattedNumber = mb_strlen($numberNoExt->getPreferredDomesticCarrierCode()) > 0
2337
                    ? $this->formatNationalNumberWithPreferredCarrierCode($numberNoExt, "")
2338
                    // Brazilian fixed line and mobile numbers need to be dialed with a carrier code when
2339
                    // called within Brazil. Without that, most of the carriers won't connect the call.
2340
                    // Because of that, we return an empty string here.
2341
                    : "";
2342
            } elseif ($isValidNumber && $regionCode == "HU") {
2343
                // The national format for HU numbers doesn't contain the national prefix, because that is
2344
                // how numbers are normally written down. However, the national prefix is obligatory when
2345
                // dialing from a mobile phone, except for short numbers. As a result, we add it back here
2346
                // if it is a valid regular length phone number.
2347
                $formattedNumber = $this->getNddPrefixForRegion(
2348
                        $regionCode,
2349
                        true /* strip non-digits */
2350
                    ) . " " . $this->format($numberNoExt, PhoneNumberFormat::NATIONAL);
2351
            } elseif ($countryCallingCode === static::NANPA_COUNTRY_CODE) {
2352
                // For NANPA countries, we output international format for numbers that can be dialed
2353
                // internationally, since that always works, except for numbers which might potentially be
2354
                // short numbers, which are always dialled in national format.
2355
                $regionMetadata = $this->getMetadataForRegion($regionCallingFrom);
2356
                if ($this->canBeInternationallyDialled($numberNoExt)
2357
                    && $this->testNumberLength($this->getNationalSignificantNumber($numberNoExt), $regionMetadata)
0 ignored issues
show
Bug introduced by
It seems like $regionMetadata defined by $this->getMetadataForRegion($regionCallingFrom) on line 2355 can be null; however, libphonenumber\PhoneNumberUtil::testNumberLength() does not accept null, maybe add an additional type check?

Unless you are absolutely sure that the expression can never be null because of other conditions, we strongly recommend to add an additional type check to your code:

/** @return stdClass|null */
function mayReturnNull() { }

function doesNotAcceptNull(stdClass $x) { }

// With potential error.
function withoutCheck() {
    $x = mayReturnNull();
    doesNotAcceptNull($x); // Potential error here.
}

// Safe - Alternative 1
function withCheck1() {
    $x = mayReturnNull();
    if ( ! $x instanceof stdClass) {
        throw new \LogicException('$x must be defined.');
    }
    doesNotAcceptNull($x);
}

// Safe - Alternative 2
function withCheck2() {
    $x = mayReturnNull();
    if ($x instanceof stdClass) {
        doesNotAcceptNull($x);
    }
}
Loading history...
2358
                    !== ValidationResult::TOO_SHORT
2359
                ) {
2360
                    $formattedNumber = $this->format($numberNoExt, PhoneNumberFormat::INTERNATIONAL);
2361
                } else {
2362
                    $formattedNumber = $this->format($numberNoExt, PhoneNumberFormat::NATIONAL);
2363
                }
2364
            } else {
2365
                // For non-geographical countries, Mexican and Chilean fixed line and mobile numbers, we
2366
                // output international format for numbers that can be dialed internationally as that always
2367
                // works.
2368
                if (($regionCode == static::REGION_CODE_FOR_NON_GEO_ENTITY ||
2369
                        // MX fixed line and mobile numbers should always be formatted in international format,
2370
                        // even when dialed within MX. For national format to work, a carrier code needs to be
2371
                        // used, and the correct carrier code depends on if the caller and callee are from the
2372
                        // same local area. It is trickier to get that to work correctly than using
2373
                        // international format, which is tested to work fine on all carriers.
2374
                        // CL fixed line numbers need the national prefix when dialing in the national format,
2375
                        // but don't have it when used for display. The reverse is true for mobile numbers.
2376
                        // As a result, we output them in the international format to make it work.
2377
                        (($regionCode == "MX" || $regionCode == "CL") && $isFixedLineOrMobile)) && $this->canBeInternationallyDialled(
2378
                        $numberNoExt
2379
                    )
2380
                ) {
2381
                    $formattedNumber = $this->format($numberNoExt, PhoneNumberFormat::INTERNATIONAL);
2382
                } else {
2383
                    $formattedNumber = $this->format($numberNoExt, PhoneNumberFormat::NATIONAL);
2384
                }
2385
            }
2386
        } elseif ($isValidNumber && $this->canBeInternationallyDialled($numberNoExt)) {
2387
            // We assume that short numbers are not diallable from outside their region, so if a number
2388
            // is not a valid regular length phone number, we treat it as if it cannot be internationally
2389
            // dialled.
2390
            return $withFormatting ?
2391
                $this->format($numberNoExt, PhoneNumberFormat::INTERNATIONAL) :
2392
                $this->format($numberNoExt, PhoneNumberFormat::E164);
2393
        }
2394
        return $withFormatting ? $formattedNumber : static::normalizeDiallableCharsOnly($formattedNumber);
2395
    }
2396
2397
    /**
2398
     * Formats a phone number in national format for dialing using the carrier as specified in the
2399
     * {@code carrierCode}. The {@code carrierCode} will always be used regardless of whether the
2400
     * phone number already has a preferred domestic carrier code stored. If {@code carrierCode}
2401
     * contains an empty string, returns the number in national format without any carrier code.
2402
     *
2403
     * @param PhoneNumber $number the phone number to be formatted
2404
     * @param string $carrierCode the carrier selection code to be used
2405
     * @return string the formatted phone number in national format for dialing using the carrier as
2406
     * specified in the {@code carrierCode}
2407
     */
2408
    public function formatNationalNumberWithCarrierCode(PhoneNumber $number, $carrierCode)
2409
    {
2410
        $countryCallingCode = $number->getCountryCode();
2411
        $nationalSignificantNumber = $this->getNationalSignificantNumber($number);
2412
        if (!$this->hasValidCountryCallingCode($countryCallingCode)) {
2413
            return $nationalSignificantNumber;
2414
        }
2415
2416
        // Note getRegionCodeForCountryCode() is used because formatting information for regions which
2417
        // share a country calling code is contained by only one region for performance reasons. For
2418
        // example, for NANPA regions it will be contained in the metadata for US.
2419
        $regionCode = $this->getRegionCodeForCountryCode($countryCallingCode);
2420
        // Metadata cannot be null because the country calling code is valid.
2421
        $metadata = $this->getMetadataForRegionOrCallingCode($countryCallingCode, $regionCode);
2422
2423
        $formattedNumber = $this->formatNsn(
2424
            $nationalSignificantNumber,
2425
            $metadata,
0 ignored issues
show
Bug introduced by
It seems like $metadata defined by $this->getMetadataForReg...llingCode, $regionCode) on line 2421 can be null; however, libphonenumber\PhoneNumberUtil::formatNsn() does not accept null, maybe add an additional type check?

Unless you are absolutely sure that the expression can never be null because of other conditions, we strongly recommend to add an additional type check to your code:

/** @return stdClass|null */
function mayReturnNull() { }

function doesNotAcceptNull(stdClass $x) { }

// With potential error.
function withoutCheck() {
    $x = mayReturnNull();
    doesNotAcceptNull($x); // Potential error here.
}

// Safe - Alternative 1
function withCheck1() {
    $x = mayReturnNull();
    if ( ! $x instanceof stdClass) {
        throw new \LogicException('$x must be defined.');
    }
    doesNotAcceptNull($x);
}

// Safe - Alternative 2
function withCheck2() {
    $x = mayReturnNull();
    if ($x instanceof stdClass) {
        doesNotAcceptNull($x);
    }
}
Loading history...
2426
            PhoneNumberFormat::NATIONAL,
2427
            $carrierCode
2428
        );
2429
        $this->maybeAppendFormattedExtension($number, $metadata, PhoneNumberFormat::NATIONAL, $formattedNumber);
2430
        $this->prefixNumberWithCountryCallingCode(
2431
            $countryCallingCode,
2432
            PhoneNumberFormat::NATIONAL,
2433
            $formattedNumber
2434
        );
2435
        return $formattedNumber;
2436
    }
2437
2438
    /**
2439
     * Formats a phone number in national format for dialing using the carrier as specified in the
2440
     * preferredDomesticCarrierCode field of the PhoneNumber object passed in. If that is missing,
2441
     * use the {@code fallbackCarrierCode} passed in instead. If there is no
2442
     * {@code preferredDomesticCarrierCode}, and the {@code fallbackCarrierCode} contains an empty
2443
     * string, return the number in national format without any carrier code.
2444
     *
2445
     * <p>Use {@link #formatNationalNumberWithCarrierCode} instead if the carrier code passed in
2446
     * should take precedence over the number's {@code preferredDomesticCarrierCode} when formatting.
2447
     *
2448
     * @param PhoneNumber $number the phone number to be formatted
2449
     * @param string $fallbackCarrierCode the carrier selection code to be used, if none is found in the
2450
     *     phone number itself
2451
     * @return string the formatted phone number in national format for dialing using the number's
2452
     *     {@code preferredDomesticCarrierCode}, or the {@code fallbackCarrierCode} passed in if
2453
     *     none is found
2454
     */
2455
    public function formatNationalNumberWithPreferredCarrierCode(PhoneNumber $number, $fallbackCarrierCode)
2456
    {
2457
        return $this->formatNationalNumberWithCarrierCode(
2458
            $number,
2459
            // Historically, we set this to an empty string when parsing with raw input if none was
2460
            // found in the input string. However, this doesn't result in a number we can dial. For this
2461
            // reason, we treat the empty string the same as if it isn't set at all.
2462
            mb_strlen($number->getPreferredDomesticCarrierCode()) > 0
2463
                ? $number->getPreferredDomesticCarrierCode()
2464
                : $fallbackCarrierCode
2465
        );
2466
    }
2467
2468
    /**
2469
     * Returns true if the number can be dialled from outside the region, or unknown. If the number
2470
     * can only be dialled from within the region, returns false. Does not check the number is a valid
2471
     * number.
2472
     * TODO: Make this method public when we have enough metadata to make it worthwhile.
2473
     *
2474
     * @param PhoneNumber $number the phone-number for which we want to know whether it is diallable from outside the region
2475
     * @return bool
2476
     */
2477
    public function canBeInternationallyDialled(PhoneNumber $number)
2478
    {
2479
        $metadata = $this->getMetadataForRegion($this->getRegionCodeForNumber($number));
2480
        if ($metadata === null) {
2481
            // Note numbers belonging to non-geographical entities (e.g. +800 numbers) are always
2482
            // internationally diallable, and will be caught here.
2483
            return true;
2484
        }
2485
        $nationalSignificantNumber = $this->getNationalSignificantNumber($number);
2486
        return !$this->isNumberMatchingDesc($nationalSignificantNumber, $metadata->getNoInternationalDialling());
2487
    }
2488
2489
    /**
2490
     * Normalizes a string of characters representing a phone number. This strips all characters which
2491
     * are not diallable on a mobile phone keypad (including all non-ASCII digits).
2492
     *
2493
     * @param string $number a string of characters representing a phone number
2494
     * @return string the normalized string version of the phone number
2495
     */
2496
    public static function normalizeDiallableCharsOnly($number)
2497
    {
2498
        if (count(static::$DIALLABLE_CHAR_MAPPINGS) === 0) {
2499
            static::initDiallableCharMappings();
2500
        }
2501
2502
        return static::normalizeHelper($number, static::$DIALLABLE_CHAR_MAPPINGS, true /* remove non matches */);
2503
    }
2504
2505
    /**
2506
     * Formats a phone number for out-of-country dialing purposes.
2507
     *
2508
     * Note that in this version, if the number was entered originally using alpha characters and
2509
     * this version of the number is stored in raw_input, this representation of the number will be
2510
     * used rather than the digit representation. Grouping information, as specified by characters
2511
     * such as "-" and " ", will be retained.
2512
     *
2513
     * <p><b>Caveats:</b></p>
2514
     * <ul>
2515
     *  <li> This will not produce good results if the country calling code is both present in the raw
2516
     *       input _and_ is the start of the national number. This is not a problem in the regions
2517
     *       which typically use alpha numbers.
2518
     *  <li> This will also not produce good results if the raw input has any grouping information
2519
     *       within the first three digits of the national number, and if the function needs to strip
2520
     *       preceding digits/words in the raw input before these digits. Normally people group the
2521
     *       first three digits together so this is not a huge problem - and will be fixed if it
2522
     *       proves to be so.
2523
     * </ul>
2524
     *
2525
     * @param PhoneNumber $number the phone number that needs to be formatted
2526
     * @param String $regionCallingFrom the region where the call is being placed
2527
     * @return String the formatted phone number
2528
     */
2529
    public function formatOutOfCountryKeepingAlphaChars(PhoneNumber $number, $regionCallingFrom)
2530
    {
2531
        $rawInput = $number->getRawInput();
2532
        // If there is no raw input, then we can't keep alpha characters because there aren't any.
2533
        // In this case, we return formatOutOfCountryCallingNumber.
2534
        if (mb_strlen($rawInput) == 0) {
2535
            return $this->formatOutOfCountryCallingNumber($number, $regionCallingFrom);
2536
        }
2537
        $countryCode = $number->getCountryCode();
2538
        if (!$this->hasValidCountryCallingCode($countryCode)) {
2539
            return $rawInput;
2540
        }
2541
        // Strip any prefix such as country calling code, IDD, that was present. We do this by comparing
2542
        // the number in raw_input with the parsed number.
2543
        // To do this, first we normalize punctuation. We retain number grouping symbols such as " "
2544
        // only.
2545
        $rawInput = $this->normalizeHelper($rawInput, static::$ALL_PLUS_NUMBER_GROUPING_SYMBOLS, true);
2546
        // Now we trim everything before the first three digits in the parsed number. We choose three
2547
        // because all valid alpha numbers have 3 digits at the start - if it does not, then we don't
2548
        // trim anything at all. Similarly, if the national number was less than three digits, we don't
2549
        // trim anything at all.
2550
        $nationalNumber = $this->getNationalSignificantNumber($number);
2551
        if (mb_strlen($nationalNumber) > 3) {
2552
            $firstNationalNumberDigit = strpos($rawInput, substr($nationalNumber, 0, 3));
2553
            if ($firstNationalNumberDigit !== false) {
2554
                $rawInput = substr($rawInput, $firstNationalNumberDigit);
2555
            }
2556
        }
2557
        $metadataForRegionCallingFrom = $this->getMetadataForRegion($regionCallingFrom);
2558
        if ($countryCode == static::NANPA_COUNTRY_CODE) {
2559
            if ($this->isNANPACountry($regionCallingFrom)) {
2560
                return $countryCode . " " . $rawInput;
2561
            }
2562
        } elseif ($metadataForRegionCallingFrom !== null &&
2563
            $countryCode == $this->getCountryCodeForValidRegion($regionCallingFrom)
2564
        ) {
2565
            $formattingPattern =
2566
                $this->chooseFormattingPatternForNumber(
2567
                    $metadataForRegionCallingFrom->numberFormats(),
2568
                    $nationalNumber
2569
                );
2570
            if ($formattingPattern === null) {
2571
                // If no pattern above is matched, we format the original input.
2572
                return $rawInput;
2573
            }
2574
            $newFormat = new NumberFormat();
2575
            $newFormat->mergeFrom($formattingPattern);
2576
            // The first group is the first group of digits that the user wrote together.
2577
            $newFormat->setPattern("(\\d+)(.*)");
2578
            // Here we just concatenate them back together after the national prefix has been fixed.
2579
            $newFormat->setFormat("$1$2");
2580
            // Now we format using this pattern instead of the default pattern, but with the national
2581
            // prefix prefixed if necessary.
2582
            // This will not work in the cases where the pattern (and not the leading digits) decide
2583
            // whether a national prefix needs to be used, since we have overridden the pattern to match
2584
            // anything, but that is not the case in the metadata to date.
2585
            return $this->formatNsnUsingPattern($rawInput, $newFormat, PhoneNumberFormat::NATIONAL);
2586
        }
2587
        $internationalPrefixForFormatting = "";
2588
        // If an unsupported region-calling-from is entered, or a country with multiple international
2589
        // prefixes, the international format of the number is returned, unless there is a preferred
2590
        // international prefix.
2591
        if ($metadataForRegionCallingFrom !== null) {
2592
            $internationalPrefix = $metadataForRegionCallingFrom->getInternationalPrefix();
2593
            $uniqueInternationalPrefixMatcher = new Matcher(static::UNIQUE_INTERNATIONAL_PREFIX, $internationalPrefix);
2594
            $internationalPrefixForFormatting =
2595
                $uniqueInternationalPrefixMatcher->matches()
2596
                    ? $internationalPrefix
2597
                    : $metadataForRegionCallingFrom->getPreferredInternationalPrefix();
2598
        }
2599
        $formattedNumber = $rawInput;
2600
        $regionCode = $this->getRegionCodeForCountryCode($countryCode);
2601
        // Metadata cannot be null because the country calling code is valid.
2602
        $metadataForRegion = $this->getMetadataForRegionOrCallingCode($countryCode, $regionCode);
2603
        $this->maybeAppendFormattedExtension(
2604
            $number,
2605
            $metadataForRegion,
2606
            PhoneNumberFormat::INTERNATIONAL,
2607
            $formattedNumber
2608
        );
2609
        if (mb_strlen($internationalPrefixForFormatting) > 0) {
2610
            $formattedNumber = $internationalPrefixForFormatting . " " . $countryCode . " " . $formattedNumber;
2611
        } else {
2612
            // Invalid region entered as country-calling-from (so no metadata was found for it) or the
2613
            // region chosen has multiple international dialling prefixes.
2614
            $this->prefixNumberWithCountryCallingCode(
2615
                $countryCode,
2616
                PhoneNumberFormat::INTERNATIONAL,
2617
                $formattedNumber
2618
            );
2619
        }
2620
        return $formattedNumber;
2621
    }
2622
2623
    /**
2624
     * Formats a phone number for out-of-country dialing purposes. If no regionCallingFrom is
2625
     * supplied, we format the number in its INTERNATIONAL format. If the country calling code is the
2626
     * same as that of the region where the number is from, then NATIONAL formatting will be applied.
2627
     *
2628
     * <p>If the number itself has a country calling code of zero or an otherwise invalid country
2629
     * calling code, then we return the number with no formatting applied.
2630
     *
2631
     * <p>Note this function takes care of the case for calling inside of NANPA and between Russia and
2632
     * Kazakhstan (who share the same country calling code). In those cases, no international prefix
2633
     * is used. For regions which have multiple international prefixes, the number in its
2634
     * INTERNATIONAL format will be returned instead.
2635
     *
2636
     * @param PhoneNumber $number the phone number to be formatted
2637
     * @param string $regionCallingFrom the region where the call is being placed
2638
     * @return string  the formatted phone number
2639
     */
2640
    public function formatOutOfCountryCallingNumber(PhoneNumber $number, $regionCallingFrom)
2641
    {
2642
        if (!$this->isValidRegionCode($regionCallingFrom)) {
2643
            return $this->format($number, PhoneNumberFormat::INTERNATIONAL);
2644
        }
2645
        $countryCallingCode = $number->getCountryCode();
2646
        $nationalSignificantNumber = $this->getNationalSignificantNumber($number);
2647
        if (!$this->hasValidCountryCallingCode($countryCallingCode)) {
2648
            return $nationalSignificantNumber;
2649
        }
2650
        if ($countryCallingCode == static::NANPA_COUNTRY_CODE) {
2651
            if ($this->isNANPACountry($regionCallingFrom)) {
2652
                // For NANPA regions, return the national format for these regions but prefix it with the
2653
                // country calling code.
2654
                return $countryCallingCode . " " . $this->format($number, PhoneNumberFormat::NATIONAL);
2655
            }
2656
        } elseif ($countryCallingCode == $this->getCountryCodeForValidRegion($regionCallingFrom)) {
2657
            // If regions share a country calling code, the country calling code need not be dialled.
2658
            // This also applies when dialling within a region, so this if clause covers both these cases.
2659
            // Technically this is the case for dialling from La Reunion to other overseas departments of
2660
            // France (French Guiana, Martinique, Guadeloupe), but not vice versa - so we don't cover this
2661
            // edge case for now and for those cases return the version including country calling code.
2662
            // Details here: http://www.petitfute.com/voyage/225-info-pratiques-reunion
2663
            return $this->format($number, PhoneNumberFormat::NATIONAL);
2664
        }
2665
        // Metadata cannot be null because we checked 'isValidRegionCode()' above.
2666
        $metadataForRegionCallingFrom = $this->getMetadataForRegion($regionCallingFrom);
2667
2668
        $internationalPrefix = $metadataForRegionCallingFrom->getInternationalPrefix();
2669
2670
        // For regions that have multiple international prefixes, the international format of the
2671
        // number is returned, unless there is a preferred international prefix.
2672
        $internationalPrefixForFormatting = "";
2673
        $uniqueInternationalPrefixMatcher = new Matcher(static::UNIQUE_INTERNATIONAL_PREFIX, $internationalPrefix);
2674
2675
        if ($uniqueInternationalPrefixMatcher->matches()) {
2676
            $internationalPrefixForFormatting = $internationalPrefix;
2677
        } elseif ($metadataForRegionCallingFrom->hasPreferredInternationalPrefix()) {
2678
            $internationalPrefixForFormatting = $metadataForRegionCallingFrom->getPreferredInternationalPrefix();
2679
        }
2680
2681
        $regionCode = $this->getRegionCodeForCountryCode($countryCallingCode);
2682
        // Metadata cannot be null because the country calling code is valid.
2683
        $metadataForRegion = $this->getMetadataForRegionOrCallingCode($countryCallingCode, $regionCode);
2684
        $formattedNationalNumber = $this->formatNsn(
2685
            $nationalSignificantNumber,
2686
            $metadataForRegion,
0 ignored issues
show
Bug introduced by
It seems like $metadataForRegion defined by $this->getMetadataForReg...llingCode, $regionCode) on line 2683 can be null; however, libphonenumber\PhoneNumberUtil::formatNsn() does not accept null, maybe add an additional type check?

Unless you are absolutely sure that the expression can never be null because of other conditions, we strongly recommend to add an additional type check to your code:

/** @return stdClass|null */
function mayReturnNull() { }

function doesNotAcceptNull(stdClass $x) { }

// With potential error.
function withoutCheck() {
    $x = mayReturnNull();
    doesNotAcceptNull($x); // Potential error here.
}

// Safe - Alternative 1
function withCheck1() {
    $x = mayReturnNull();
    if ( ! $x instanceof stdClass) {
        throw new \LogicException('$x must be defined.');
    }
    doesNotAcceptNull($x);
}

// Safe - Alternative 2
function withCheck2() {
    $x = mayReturnNull();
    if ($x instanceof stdClass) {
        doesNotAcceptNull($x);
    }
}
Loading history...
2687
            PhoneNumberFormat::INTERNATIONAL
2688
        );
2689
        $formattedNumber = $formattedNationalNumber;
2690
        $this->maybeAppendFormattedExtension(
2691
            $number,
2692
            $metadataForRegion,
2693
            PhoneNumberFormat::INTERNATIONAL,
2694
            $formattedNumber
2695
        );
2696
        if (mb_strlen($internationalPrefixForFormatting) > 0) {
2697
            $formattedNumber = $internationalPrefixForFormatting . " " . $countryCallingCode . " " . $formattedNumber;
2698
        } else {
2699
            $this->prefixNumberWithCountryCallingCode(
2700
                $countryCallingCode,
2701
                PhoneNumberFormat::INTERNATIONAL,
2702
                $formattedNumber
2703
            );
2704
        }
2705
        return $formattedNumber;
2706
    }
2707
2708
    /**
2709
     * Checks if this is a region under the North American Numbering Plan Administration (NANPA).
2710
     * @param string $regionCode
2711
     * @return boolean true if regionCode is one of the regions under NANPA
2712
     */
2713
    public function isNANPACountry($regionCode)
2714
    {
2715
        return in_array($regionCode, $this->nanpaRegions);
2716
    }
2717
2718
    /**
2719
     * Formats a phone number using the original phone number format that the number is parsed from.
2720
     * The original format is embedded in the country_code_source field of the PhoneNumber object
2721
     * passed in. If such information is missing, the number will be formatted into the NATIONAL
2722
     * format by default. When the number contains a leading zero and this is unexpected for this
2723
     * country, or we don't have a formatting pattern for the number, the method returns the raw input
2724
     * when it is available.
2725
     *
2726
     * Note this method guarantees no digit will be inserted, removed or modified as a result of
2727
     * formatting.
2728
     *
2729
     * @param PhoneNumber $number the phone number that needs to be formatted in its original number format
2730
     * @param string $regionCallingFrom the region whose IDD needs to be prefixed if the original number
2731
     *     has one
2732
     * @return string the formatted phone number in its original number format
2733
     */
2734
    public function formatInOriginalFormat(PhoneNumber $number, $regionCallingFrom)
2735
    {
2736
        if ($number->hasRawInput() &&
2737
            ($this->hasUnexpectedItalianLeadingZero($number) || !$this->hasFormattingPatternForNumber($number))
2738
        ) {
2739
            // We check if we have the formatting pattern because without that, we might format the number
2740
            // as a group without national prefix.
2741
            return $number->getRawInput();
2742
        }
2743
        if (!$number->hasCountryCodeSource()) {
2744
            return $this->format($number, PhoneNumberFormat::NATIONAL);
2745
        }
2746
        switch ($number->getCountryCodeSource()) {
2747
            case CountryCodeSource::FROM_NUMBER_WITH_PLUS_SIGN:
2748
                $formattedNumber = $this->format($number, PhoneNumberFormat::INTERNATIONAL);
2749
                break;
2750
            case CountryCodeSource::FROM_NUMBER_WITH_IDD:
2751
                $formattedNumber = $this->formatOutOfCountryCallingNumber($number, $regionCallingFrom);
2752
                break;
2753
            case CountryCodeSource::FROM_NUMBER_WITHOUT_PLUS_SIGN:
2754
                $formattedNumber = substr($this->format($number, PhoneNumberFormat::INTERNATIONAL), 1);
2755
                break;
2756
            case CountryCodeSource::FROM_DEFAULT_COUNTRY:
2757
                // Fall-through to default case.
2758
            default:
0 ignored issues
show
Coding Style introduced by
The default body in a switch statement must start on the line following the statement.

According to the PSR-2, the body of a default statement must start on the line immediately following the statement.

switch ($expr) {
    default:
        doSomething(); //right
        break;
}


switch ($expr) {
    default:

        doSomething(); //wrong
        break;
}

To learn more about the PSR-2 coding standard, please refer to the PHP-Fig.

Loading history...
2759
2760
                $regionCode = $this->getRegionCodeForCountryCode($number->getCountryCode());
2761
                // We strip non-digits from the NDD here, and from the raw input later, so that we can
2762
                // compare them easily.
2763
                $nationalPrefix = $this->getNddPrefixForRegion($regionCode, true /* strip non-digits */);
2764
                $nationalFormat = $this->format($number, PhoneNumberFormat::NATIONAL);
2765
                if ($nationalPrefix === null || mb_strlen($nationalPrefix) == 0) {
2766
                    // If the region doesn't have a national prefix at all, we can safely return the national
2767
                    // format without worrying about a national prefix being added.
2768
                    $formattedNumber = $nationalFormat;
2769
                    break;
2770
                }
2771
                // Otherwise, we check if the original number was entered with a national prefix.
2772
                if ($this->rawInputContainsNationalPrefix(
2773
                    $number->getRawInput(),
2774
                    $nationalPrefix,
2775
                    $regionCode
2776
                )
2777
                ) {
2778
                    // If so, we can safely return the national format.
2779
                    $formattedNumber = $nationalFormat;
2780
                    break;
2781
                }
2782
                // Metadata cannot be null here because getNddPrefixForRegion() (above) returns null if
2783
                // there is no metadata for the region.
2784
                $metadata = $this->getMetadataForRegion($regionCode);
2785
                $nationalNumber = $this->getNationalSignificantNumber($number);
2786
                $formatRule = $this->chooseFormattingPatternForNumber($metadata->numberFormats(), $nationalNumber);
2787
                // The format rule could still be null here if the national number was 0 and there was no
2788
                // raw input (this should not be possible for numbers generated by the phonenumber library
2789
                // as they would also not have a country calling code and we would have exited earlier).
2790
                if ($formatRule === null) {
2791
                    $formattedNumber = $nationalFormat;
2792
                    break;
2793
                }
2794
                // When the format we apply to this number doesn't contain national prefix, we can just
2795
                // return the national format.
2796
                // TODO: Refactor the code below with the code in isNationalPrefixPresentIfRequired.
2797
                $candidateNationalPrefixRule = $formatRule->getNationalPrefixFormattingRule();
2798
                // We assume that the first-group symbol will never be _before_ the national prefix.
2799
                $indexOfFirstGroup = strpos($candidateNationalPrefixRule, '$1');
2800
                if ($indexOfFirstGroup <= 0) {
2801
                    $formattedNumber = $nationalFormat;
2802
                    break;
2803
                }
2804
                $candidateNationalPrefixRule = substr($candidateNationalPrefixRule, 0, $indexOfFirstGroup);
2805
                $candidateNationalPrefixRule = static::normalizeDigitsOnly($candidateNationalPrefixRule);
2806
                if (mb_strlen($candidateNationalPrefixRule) == 0) {
2807
                    // National prefix not used when formatting this number.
2808
                    $formattedNumber = $nationalFormat;
2809
                    break;
2810
                }
2811
                // Otherwise, we need to remove the national prefix from our output.
2812
                $numFormatCopy = new NumberFormat();
2813
                $numFormatCopy->mergeFrom($formatRule);
2814
                $numFormatCopy->clearNationalPrefixFormattingRule();
2815
                $numberFormats = array();
2816
                $numberFormats[] = $numFormatCopy;
2817
                $formattedNumber = $this->formatByPattern($number, PhoneNumberFormat::NATIONAL, $numberFormats);
2818
                break;
2819
        }
2820
        $rawInput = $number->getRawInput();
2821
        // If no digit is inserted/removed/modified as a result of our formatting, we return the
2822
        // formatted phone number; otherwise we return the raw input the user entered.
2823
        if ($formattedNumber !== null && mb_strlen($rawInput) > 0) {
2824
            $normalizedFormattedNumber = static::normalizeDiallableCharsOnly($formattedNumber);
2825
            $normalizedRawInput = static::normalizeDiallableCharsOnly($rawInput);
2826
            if ($normalizedFormattedNumber != $normalizedRawInput) {
2827
                $formattedNumber = $rawInput;
2828
            }
2829
        }
2830
        return $formattedNumber;
2831
    }
2832
2833
    /**
2834
     * Returns true if a number is from a region whose national significant number couldn't contain a
2835
     * leading zero, but has the italian_leading_zero field set to true.
2836
     * @param PhoneNumber $number
2837
     * @return bool
2838
     */
2839
    protected function hasUnexpectedItalianLeadingZero(PhoneNumber $number)
2840
    {
2841
        return $number->isItalianLeadingZero() && !$this->isLeadingZeroPossible($number->getCountryCode());
2842
    }
2843
2844
    /**
2845
     * Checks whether the country calling code is from a region whose national significant number
2846
     * could contain a leading zero. An example of such a region is Italy. Returns false if no
2847
     * metadata for the country is found.
2848
     * @param int $countryCallingCode
2849
     * @return bool
2850
     */
2851
    public function isLeadingZeroPossible($countryCallingCode)
2852
    {
2853
        $mainMetadataForCallingCode = $this->getMetadataForRegionOrCallingCode(
2854
            $countryCallingCode,
2855
            $this->getRegionCodeForCountryCode($countryCallingCode)
2856
        );
2857
        if ($mainMetadataForCallingCode === null) {
2858
            return false;
2859
        }
2860
        return (bool)$mainMetadataForCallingCode->isLeadingZeroPossible();
2861
    }
2862
2863
    /**
2864
     * @param PhoneNumber $number
2865
     * @return bool
2866
     */
2867
    protected function hasFormattingPatternForNumber(PhoneNumber $number)
2868
    {
2869
        $countryCallingCode = $number->getCountryCode();
2870
        $phoneNumberRegion = $this->getRegionCodeForCountryCode($countryCallingCode);
2871
        $metadata = $this->getMetadataForRegionOrCallingCode($countryCallingCode, $phoneNumberRegion);
2872
        if ($metadata === null) {
2873
            return false;
2874
        }
2875
        $nationalNumber = $this->getNationalSignificantNumber($number);
2876
        $formatRule = $this->chooseFormattingPatternForNumber($metadata->numberFormats(), $nationalNumber);
2877
        return $formatRule !== null;
2878
    }
2879
2880
    /**
2881
     * Returns the national dialling prefix for a specific region. For example, this would be 1 for
2882
     * the United States, and 0 for New Zealand. Set stripNonDigits to true to strip symbols like "~"
2883
     * (which indicates a wait for a dialling tone) from the prefix returned. If no national prefix is
2884
     * present, we return null.
2885
     *
2886
     * <p>Warning: Do not use this method for do-your-own formatting - for some regions, the
2887
     * national dialling prefix is used only for certain types of numbers. Use the library's
2888
     * formatting functions to prefix the national prefix when required.
2889
     *
2890
     * @param string $regionCode the region that we want to get the dialling prefix for
2891
     * @param boolean $stripNonDigits true to strip non-digits from the national dialling prefix
2892
     * @return string the dialling prefix for the region denoted by regionCode
2893
     */
2894
    public function getNddPrefixForRegion($regionCode, $stripNonDigits)
2895
    {
2896
        $metadata = $this->getMetadataForRegion($regionCode);
2897
        if ($metadata === null) {
2898
            return null;
2899
        }
2900
        $nationalPrefix = $metadata->getNationalPrefix();
2901
        // If no national prefix was found, we return null.
2902
        if (mb_strlen($nationalPrefix) == 0) {
2903
            return null;
2904
        }
2905
        if ($stripNonDigits) {
2906
            // Note: if any other non-numeric symbols are ever used in national prefixes, these would have
2907
            // to be removed here as well.
2908
            $nationalPrefix = str_replace("~", "", $nationalPrefix);
2909
        }
2910
        return $nationalPrefix;
2911
    }
2912
2913
    /**
2914
     * Check if rawInput, which is assumed to be in the national format, has a national prefix. The
2915
     * national prefix is assumed to be in digits-only form.
2916
     * @param string $rawInput
2917
     * @param string $nationalPrefix
2918
     * @param string $regionCode
2919
     * @return bool
2920
     */
2921
    protected function rawInputContainsNationalPrefix($rawInput, $nationalPrefix, $regionCode)
2922
    {
2923
        $normalizedNationalNumber = static::normalizeDigitsOnly($rawInput);
2924
        if (strpos($normalizedNationalNumber, $nationalPrefix) === 0) {
2925
            try {
2926
                // Some Japanese numbers (e.g. 00777123) might be mistaken to contain the national prefix
2927
                // when written without it (e.g. 0777123) if we just do prefix matching. To tackle that, we
2928
                // check the validity of the number if the assumed national prefix is removed (777123 won't
2929
                // be valid in Japan).
2930
                return $this->isValidNumber(
2931
                    $this->parse(substr($normalizedNationalNumber, mb_strlen($nationalPrefix)), $regionCode)
2932
                );
2933
            } catch (NumberParseException $e) {
2934
                return false;
2935
            }
2936
        }
2937
        return false;
2938
    }
2939
2940
    /**
2941
     * Tests whether a phone number matches a valid pattern. Note this doesn't verify the number
2942
     * is actually in use, which is impossible to tell by just looking at a number itself. It only
2943
     * verifies whether the parsed, canonicalised number is valid: not whether a particular series of
2944
     * digits entered by the user is diallable from the region provided when parsing. For example, the
2945
     * number +41 (0) 78 927 2696 can be parsed into a number with country code "41" and national
2946
     * significant number "789272696". This is valid, while the original string is not diallable.
2947
     *
2948
     * @param PhoneNumber $number the phone number that we want to validate
2949
     * @return boolean that indicates whether the number is of a valid pattern
2950
     */
2951
    public function isValidNumber(PhoneNumber $number)
2952
    {
2953
        $regionCode = $this->getRegionCodeForNumber($number);
2954
        return $this->isValidNumberForRegion($number, $regionCode);
2955
    }
2956
2957
    /**
2958
     * Tests whether a phone number is valid for a certain region. Note this doesn't verify the number
2959
     * is actually in use, which is impossible to tell by just looking at a number itself. If the
2960
     * country calling code is not the same as the country calling code for the region, this
2961
     * immediately exits with false. After this, the specific number pattern rules for the region are
2962
     * examined. This is useful for determining for example whether a particular number is valid for
2963
     * Canada, rather than just a valid NANPA number.
2964
     * Warning: In most cases, you want to use {@link #isValidNumber} instead. For example, this
2965
     * method will mark numbers from British Crown dependencies such as the Isle of Man as invalid for
2966
     * the region "GB" (United Kingdom), since it has its own region code, "IM", which may be
2967
     * undesirable.
2968
     *
2969
     * @param PhoneNumber $number the phone number that we want to validate
2970
     * @param string $regionCode the region that we want to validate the phone number for
2971
     * @return boolean that indicates whether the number is of a valid pattern
2972
     */
2973
    public function isValidNumberForRegion(PhoneNumber $number, $regionCode)
2974
    {
2975
        $countryCode = $number->getCountryCode();
2976
        $metadata = $this->getMetadataForRegionOrCallingCode($countryCode, $regionCode);
2977
        if (($metadata === null) ||
2978
            (static::REGION_CODE_FOR_NON_GEO_ENTITY !== $regionCode &&
2979
                $countryCode !== $this->getCountryCodeForValidRegion($regionCode))
2980
        ) {
2981
            // Either the region code was invalid, or the country calling code for this number does not
2982
            // match that of the region code.
2983
            return false;
2984
        }
2985
        $nationalSignificantNumber = $this->getNationalSignificantNumber($number);
2986
2987
        return $this->getNumberTypeHelper($nationalSignificantNumber, $metadata) != PhoneNumberType::UNKNOWN;
2988
    }
2989
2990
    /**
2991
     * Parses a string and returns it as a phone number in proto buffer format. The method is quite
2992
     * lenient and looks for a number in the input text (raw input) and does not check whether the
2993
     * string is definitely only a phone number. To do this, it ignores punctuation and white-space,
2994
     * as well as any text before the number (e.g. a leading “Tel: ”) and trims the non-number bits.
2995
     * It will accept a number in any format (E164, national, international etc), assuming it can
2996
     * interpreted with the defaultRegion supplied. It also attempts to convert any alpha characters
2997
     * into digits if it thinks this is a vanity number of the type "1800 MICROSOFT".
2998
     *
2999
     * <p> This method will throw a {@link NumberParseException} if the number is not considered to
3000
     * be a possible number. Note that validation of whether the number is actually a valid number
3001
     * for a particular region is not performed. This can be done separately with {@link #isValidnumber}.
3002
     *
3003
     * @param string $numberToParse number that we are attempting to parse. This can contain formatting
3004
     *                          such as +, ( and -, as well as a phone number extension.
3005
     * @param string $defaultRegion region that we are expecting the number to be from. This is only used
3006
     *                          if the number being parsed is not written in international format.
3007
     *                          The country_code for the number in this case would be stored as that
3008
     *                          of the default region supplied. If the number is guaranteed to
3009
     *                          start with a '+' followed by the country calling code, then
3010
     *                          "ZZ" or null can be supplied.
3011
     * @param PhoneNumber|null $phoneNumber
3012
     * @param bool $keepRawInput
3013
     * @return PhoneNumber a phone number proto buffer filled with the parsed number
3014
     * @throws NumberParseException  if the string is not considered to be a viable phone number (e.g.
3015
     *                               too few or too many digits) or if no default region was supplied
3016
     *                               and the number is not in international format (does not start
3017
     *                               with +)
3018
     */
3019
    public function parse($numberToParse, $defaultRegion, PhoneNumber $phoneNumber = null, $keepRawInput = false)
3020
    {
3021
        if ($phoneNumber === null) {
3022
            $phoneNumber = new PhoneNumber();
3023
        }
3024
        $this->parseHelper($numberToParse, $defaultRegion, $keepRawInput, true, $phoneNumber);
3025
        return $phoneNumber;
3026
    }
3027
3028
    /**
3029
     * Formats a phone number in the specified format using client-defined formatting rules. Note that
3030
     * if the phone number has a country calling code of zero or an otherwise invalid country calling
3031
     * code, we cannot work out things like whether there should be a national prefix applied, or how
3032
     * to format extensions, so we return the national significant number with no formatting applied.
3033
     *
3034
     * @param PhoneNumber $number the phone number to be formatted
3035
     * @param int $numberFormat the format the phone number should be formatted into
3036
     * @param array $userDefinedFormats formatting rules specified by clients
3037
     * @return String the formatted phone number
3038
     */
3039
    public function formatByPattern(PhoneNumber $number, $numberFormat, array $userDefinedFormats)
3040
    {
3041
        $countryCallingCode = $number->getCountryCode();
3042
        $nationalSignificantNumber = $this->getNationalSignificantNumber($number);
3043
        if (!$this->hasValidCountryCallingCode($countryCallingCode)) {
3044
            return $nationalSignificantNumber;
3045
        }
3046
        // Note getRegionCodeForCountryCode() is used because formatting information for regions which
3047
        // share a country calling code is contained by only one region for performance reasons. For
3048
        // example, for NANPA regions it will be contained in the metadata for US.
3049
        $regionCode = $this->getRegionCodeForCountryCode($countryCallingCode);
3050
        // Metadata cannot be null because the country calling code is valid
3051
        $metadata = $this->getMetadataForRegionOrCallingCode($countryCallingCode, $regionCode);
3052
3053
        $formattedNumber = "";
3054
3055
        $formattingPattern = $this->chooseFormattingPatternForNumber($userDefinedFormats, $nationalSignificantNumber);
3056
        if ($formattingPattern === null) {
3057
            // If no pattern above is matched, we format the number as a whole.
3058
            $formattedNumber .= $nationalSignificantNumber;
3059
        } else {
3060
            $numFormatCopy = new NumberFormat();
3061
            // Before we do a replacement of the national prefix pattern $NP with the national prefix, we
3062
            // need to copy the rule so that subsequent replacements for different numbers have the
3063
            // appropriate national prefix.
3064
            $numFormatCopy->mergeFrom($formattingPattern);
3065
            $nationalPrefixFormattingRule = $formattingPattern->getNationalPrefixFormattingRule();
3066
            if (mb_strlen($nationalPrefixFormattingRule) > 0) {
3067
                $nationalPrefix = $metadata->getNationalPrefix();
3068
                if (mb_strlen($nationalPrefix) > 0) {
3069
                    // Replace $NP with national prefix and $FG with the first group ($1).
3070
                    $npPatternMatcher = new Matcher(static::NP_PATTERN, $nationalPrefixFormattingRule);
3071
                    $nationalPrefixFormattingRule = $npPatternMatcher->replaceFirst($nationalPrefix);
3072
                    $fgPatternMatcher = new Matcher(static::FG_PATTERN, $nationalPrefixFormattingRule);
3073
                    $nationalPrefixFormattingRule = $fgPatternMatcher->replaceFirst("\\$1");
3074
                    $numFormatCopy->setNationalPrefixFormattingRule($nationalPrefixFormattingRule);
3075
                } else {
3076
                    // We don't want to have a rule for how to format the national prefix if there isn't one.
3077
                    $numFormatCopy->clearNationalPrefixFormattingRule();
3078
                }
3079
            }
3080
            $formattedNumber .= $this->formatNsnUsingPattern($nationalSignificantNumber, $numFormatCopy, $numberFormat);
3081
        }
3082
        $this->maybeAppendFormattedExtension($number, $metadata, $numberFormat, $formattedNumber);
3083
        $this->prefixNumberWithCountryCallingCode($countryCallingCode, $numberFormat, $formattedNumber);
3084
        return $formattedNumber;
3085
    }
3086
3087
    /**
3088
     * Gets a valid number for the specified region.
3089
     *
3090
     * @param string regionCode  the region for which an example number is needed
3091
     * @return PhoneNumber a valid fixed-line number for the specified region. Returns null when the metadata
3092
     *    does not contain such information, or the region 001 is passed in. For 001 (representing
3093
     *    non-geographical numbers), call {@link #getExampleNumberForNonGeoEntity} instead.
3094
     */
3095
    public function getExampleNumber($regionCode)
3096
    {
3097
        return $this->getExampleNumberForType($regionCode, PhoneNumberType::FIXED_LINE);
3098
    }
3099
3100
    /**
3101
     * Gets an invalid number for the specified region. This is useful for unit-testing purposes,
3102
     * where you want to test what will happen with an invalid number. Note that the number that is
3103
     * returned will always be able to be parsed and will have the correct country code. It may also
3104
     * be a valid *short* number/code for this region. Validity checking such numbers is handled with
3105
     * {@link ShortNumberInfo}.
3106
     *
3107
     * @param string $regionCode The region for which an example number is needed
3108
     * @return PhoneNumber|null An invalid number for the specified region. Returns null when an unsupported region
3109
     * or the region 001 (Earth) is passed in.
3110
     */
3111
    public function getInvalidExampleNumber($regionCode)
3112
    {
3113
        if (!$this->isValidRegionCode($regionCode)) {
3114
            return null;
3115
        }
3116
3117
        // We start off with a valid fixed-line number since every country supports this. Alternatively
3118
        // we could start with a different number type, since fixed-line numbers typically have a wide
3119
        // breadth of valid number lengths and we may have to make it very short before we get an
3120
        // invalid number.
3121
3122
        $desc = $this->getNumberDescByType($this->getMetadataForRegion($regionCode), PhoneNumberType::FIXED_LINE);
0 ignored issues
show
Bug introduced by
It seems like $this->getMetadataForRegion($regionCode) can be null; however, getNumberDescByType() does not accept null, maybe add an additional type check?

Unless you are absolutely sure that the expression can never be null because of other conditions, we strongly recommend to add an additional type check to your code:

/** @return stdClass|null */
function mayReturnNull() { }

function doesNotAcceptNull(stdClass $x) { }

// With potential error.
function withoutCheck() {
    $x = mayReturnNull();
    doesNotAcceptNull($x); // Potential error here.
}

// Safe - Alternative 1
function withCheck1() {
    $x = mayReturnNull();
    if ( ! $x instanceof stdClass) {
        throw new \LogicException('$x must be defined.');
    }
    doesNotAcceptNull($x);
}

// Safe - Alternative 2
function withCheck2() {
    $x = mayReturnNull();
    if ($x instanceof stdClass) {
        doesNotAcceptNull($x);
    }
}
Loading history...
3123
3124
        if ($desc->getExampleNumber() == '') {
3125
            // This shouldn't happen; we have a test for this.
3126
            return null;
3127
        }
3128
3129
        $exampleNumber = $desc->getExampleNumber();
3130
3131
        // Try and make the number invalid. We do this by changing the length. We try reducing the
3132
        // length of the number, since currently no region has a number that is the same length as
3133
        // MIN_LENGTH_FOR_NSN. This is probably quicker than making the number longer, which is another
3134
        // alternative. We could also use the possible number pattern to extract the possible lengths of
3135
        // the number to make this faster, but this method is only for unit-testing so simplicity is
3136
        // preferred to performance.  We don't want to return a number that can't be parsed, so we check
3137
        // the number is long enough. We try all possible lengths because phone number plans often have
3138
        // overlapping prefixes so the number 123456 might be valid as a fixed-line number, and 12345 as
3139
        // a mobile number. It would be faster to loop in a different order, but we prefer numbers that
3140
        // look closer to real numbers (and it gives us a variety of different lengths for the resulting
3141
        // phone numbers - otherwise they would all be MIN_LENGTH_FOR_NSN digits long.)
3142
        for ($phoneNumberLength = mb_strlen($exampleNumber) - 1; $phoneNumberLength >= static::MIN_LENGTH_FOR_NSN; $phoneNumberLength--) {
3143
            $numberToTry = mb_substr($exampleNumber, 0, $phoneNumberLength);
3144
            try {
3145
                $possiblyValidNumber = $this->parse($numberToTry, $regionCode);
3146
                if (!$this->isValidNumber($possiblyValidNumber)) {
3147
                    return $possiblyValidNumber;
3148
                }
3149
            } catch (NumberParseException $e) {
3150
                // Shouldn't happen: we have already checked the length, we know example numbers have
3151
                // only valid digits, and we know the region code is fine.
3152
            }
3153
        }
3154
        // We have a test to check that this doesn't happen for any of our supported regions.
3155
        return null;
3156
    }
3157
3158
    /**
3159
     * Gets a valid number for the specified region and number type.
3160
     *
3161
     * @param string|int $regionCodeOrType the region for which an example number is needed
3162
     * @param int $type the PhoneNumberType of number that is needed
3163
     * @return PhoneNumber a valid number for the specified region and type. Returns null when the metadata
3164
     *     does not contain such information or if an invalid region or region 001 was entered.
3165
     *     For 001 (representing non-geographical numbers), call
3166
     *     {@link #getExampleNumberForNonGeoEntity} instead.
3167
     *
3168
     * If $regionCodeOrType is the only parameter supplied, then a valid number for the specified number type
3169
     * will be returned that may belong to any country.
3170
     */
3171
    public function getExampleNumberForType($regionCodeOrType, $type = null)
3172
    {
3173
        if ($regionCodeOrType !== null && $type === null) {
3174
            /*
3175
             * Gets a valid number for the specified number type (it may belong to any country).
3176
             */
3177
            foreach ($this->getSupportedRegions() as $regionCode) {
3178
                $exampleNumber = $this->getExampleNumberForType($regionCode, $regionCodeOrType);
3179
                if ($exampleNumber !== null) {
3180
                    return $exampleNumber;
3181
                }
3182
            }
3183
3184
            // If there wasn't an example number for a region, try the non-geographical entities
3185
            foreach ($this->getSupportedGlobalNetworkCallingCodes() as $countryCallingCode) {
3186
                $desc = $this->getNumberDescByType($this->getMetadataForNonGeographicalRegion($countryCallingCode), $regionCodeOrType);
0 ignored issues
show
Bug introduced by
It seems like $this->getMetadataForNon...on($countryCallingCode) can be null; however, getNumberDescByType() does not accept null, maybe add an additional type check?

Unless you are absolutely sure that the expression can never be null because of other conditions, we strongly recommend to add an additional type check to your code:

/** @return stdClass|null */
function mayReturnNull() { }

function doesNotAcceptNull(stdClass $x) { }

// With potential error.
function withoutCheck() {
    $x = mayReturnNull();
    doesNotAcceptNull($x); // Potential error here.
}

// Safe - Alternative 1
function withCheck1() {
    $x = mayReturnNull();
    if ( ! $x instanceof stdClass) {
        throw new \LogicException('$x must be defined.');
    }
    doesNotAcceptNull($x);
}

// Safe - Alternative 2
function withCheck2() {
    $x = mayReturnNull();
    if ($x instanceof stdClass) {
        doesNotAcceptNull($x);
    }
}
Loading history...
3187
                try {
3188
                    if ($desc->getExampleNumber() != '') {
3189
                        return $this->parse("+" . $countryCallingCode . $desc->getExampleNumber(), static::UNKNOWN_REGION);
3190
                    }
3191
                } catch (NumberParseException $e) {
3192
                    // noop
3193
                }
3194
            }
3195
            // There are no example numbers of this type for any country in the library.
3196
            return null;
3197
        }
3198
3199
        // Check the region code is valid.
3200
        if (!$this->isValidRegionCode($regionCodeOrType)) {
3201
            return null;
3202
        }
3203
        $desc = $this->getNumberDescByType($this->getMetadataForRegion($regionCodeOrType), $type);
0 ignored issues
show
Bug introduced by
It seems like $this->getMetadataForRegion($regionCodeOrType) can be null; however, getNumberDescByType() does not accept null, maybe add an additional type check?

Unless you are absolutely sure that the expression can never be null because of other conditions, we strongly recommend to add an additional type check to your code:

/** @return stdClass|null */
function mayReturnNull() { }

function doesNotAcceptNull(stdClass $x) { }

// With potential error.
function withoutCheck() {
    $x = mayReturnNull();
    doesNotAcceptNull($x); // Potential error here.
}

// Safe - Alternative 1
function withCheck1() {
    $x = mayReturnNull();
    if ( ! $x instanceof stdClass) {
        throw new \LogicException('$x must be defined.');
    }
    doesNotAcceptNull($x);
}

// Safe - Alternative 2
function withCheck2() {
    $x = mayReturnNull();
    if ($x instanceof stdClass) {
        doesNotAcceptNull($x);
    }
}
Loading history...
3204
        try {
3205
            if ($desc->hasExampleNumber()) {
3206
                return $this->parse($desc->getExampleNumber(), $regionCodeOrType);
3207
            }
3208
        } catch (NumberParseException $e) {
3209
            // noop
3210
        }
3211
        return null;
3212
    }
3213
3214
    /**
3215
     * @param PhoneMetadata $metadata
3216
     * @param int $type PhoneNumberType
3217
     * @return PhoneNumberDesc
3218
     */
3219
    protected function getNumberDescByType(PhoneMetadata $metadata, $type)
3220
    {
3221
        switch ($type) {
3222
            case PhoneNumberType::PREMIUM_RATE:
3223
                return $metadata->getPremiumRate();
3224
            case PhoneNumberType::TOLL_FREE:
3225
                return $metadata->getTollFree();
3226
            case PhoneNumberType::MOBILE:
3227
                return $metadata->getMobile();
3228
            case PhoneNumberType::FIXED_LINE:
3229
            case PhoneNumberType::FIXED_LINE_OR_MOBILE:
3230
                return $metadata->getFixedLine();
3231
            case PhoneNumberType::SHARED_COST:
3232
                return $metadata->getSharedCost();
3233
            case PhoneNumberType::VOIP:
3234
                return $metadata->getVoip();
3235
            case PhoneNumberType::PERSONAL_NUMBER:
3236
                return $metadata->getPersonalNumber();
3237
            case PhoneNumberType::PAGER:
3238
                return $metadata->getPager();
3239
            case PhoneNumberType::UAN:
3240
                return $metadata->getUan();
3241
            case PhoneNumberType::VOICEMAIL:
3242
                return $metadata->getVoicemail();
3243
            default:
3244
                return $metadata->getGeneralDesc();
3245
        }
3246
    }
3247
3248
    /**
3249
     * Gets a valid number for the specified country calling code for a non-geographical entity.
3250
     *
3251
     * @param int $countryCallingCode the country calling code for a non-geographical entity
3252
     * @return PhoneNumber a valid number for the non-geographical entity. Returns null when the metadata
3253
     *    does not contain such information, or the country calling code passed in does not belong
3254
     *    to a non-geographical entity.
3255
     */
3256
    public function getExampleNumberForNonGeoEntity($countryCallingCode)
3257
    {
3258
        $metadata = $this->getMetadataForNonGeographicalRegion($countryCallingCode);
3259
        if ($metadata !== null) {
3260
            // For geographical entities, fixed-line data is always present. However, for non-geographical
3261
            // entities, this is not the case, so we have to go through different types to find the
3262
            // example number. We don't check fixed-line or personal number since they aren't used by
3263
            // non-geographical entities (if this changes, a unit-test will catch this.)
3264
            /** @var PhoneNumberDesc[] $list */
3265
            $list = array(
3266
                $metadata->getMobile(),
3267
                $metadata->getTollFree(),
3268
                $metadata->getSharedCost(),
3269
                $metadata->getVoip(),
3270
                $metadata->getVoicemail(),
3271
                $metadata->getUan(),
3272
                $metadata->getPremiumRate(),
3273
            );
3274
            foreach ($list as $desc) {
3275
                try {
3276
                    if ($desc !== null && $desc->hasExampleNumber()) {
3277
                        return $this->parse('+' . $countryCallingCode . $desc->getExampleNumber(), self::UNKNOWN_REGION);
3278
                    }
3279
                } catch (NumberParseException $e) {
3280
                    // noop
3281
                }
3282
            }
3283
        }
3284
        return null;
3285
    }
3286
3287
3288
    /**
3289
     * Takes two phone numbers and compares them for equality.
3290
     *
3291
     * <p>Returns EXACT_MATCH if the country_code, NSN, presence of a leading zero
3292
     * for Italian numbers and any extension present are the same. Returns NSN_MATCH
3293
     * if either or both has no region specified, and the NSNs and extensions are
3294
     * the same. Returns SHORT_NSN_MATCH if either or both has no region specified,
3295
     * or the region specified is the same, and one NSN could be a shorter version
3296
     * of the other number. This includes the case where one has an extension
3297
     * specified, and the other does not. Returns NO_MATCH otherwise. For example,
3298
     * the numbers +1 345 657 1234 and 657 1234 are a SHORT_NSN_MATCH. The numbers
3299
     * +1 345 657 1234 and 345 657 are a NO_MATCH.
3300
     *
3301
     * @param $firstNumberIn PhoneNumber|string First number to compare. If it is a
3302
     * string it can contain formatting, and can have country calling code specified
3303
     * with + at the start.
3304
     * @param $secondNumberIn PhoneNumber|string Second number to compare. If it is a
3305
     * string it can contain formatting, and can have country calling code specified
3306
     * with + at the start.
3307
     * @throws \InvalidArgumentException
3308
     * @return int {MatchType} NOT_A_NUMBER, NO_MATCH,
3309
     */
3310
    public function isNumberMatch($firstNumberIn, $secondNumberIn)
3311
    {
3312
        if (is_string($firstNumberIn) && is_string($secondNumberIn)) {
3313
            try {
3314
                $firstNumberAsProto = $this->parse($firstNumberIn, static::UNKNOWN_REGION);
3315
                return $this->isNumberMatch($firstNumberAsProto, $secondNumberIn);
3316
            } catch (NumberParseException $e) {
3317
                if ($e->getErrorType() === NumberParseException::INVALID_COUNTRY_CODE) {
3318
                    try {
3319
                        $secondNumberAsProto = $this->parse($secondNumberIn, static::UNKNOWN_REGION);
3320
                        return $this->isNumberMatch($secondNumberAsProto, $firstNumberIn);
3321
                    } catch (NumberParseException $e2) {
3322
                        if ($e2->getErrorType() === NumberParseException::INVALID_COUNTRY_CODE) {
3323
                            try {
3324
                                $firstNumberProto = new PhoneNumber();
3325
                                $secondNumberProto = new PhoneNumber();
3326
                                $this->parseHelper($firstNumberIn, null, false, false, $firstNumberProto);
3327
                                $this->parseHelper($secondNumberIn, null, false, false, $secondNumberProto);
3328
                                return $this->isNumberMatch($firstNumberProto, $secondNumberProto);
3329
                            } catch (NumberParseException $e3) {
3330
                                // Fall through and return MatchType::NOT_A_NUMBER
3331
                            }
3332
                        }
3333
                    }
3334
                }
3335
            }
3336
            return MatchType::NOT_A_NUMBER;
3337
        }
3338
        if ($firstNumberIn instanceof PhoneNumber && is_string($secondNumberIn)) {
3339
            // First see if the second number has an implicit country calling code, by attempting to parse
3340
            // it.
3341
            try {
3342
                $secondNumberAsProto = $this->parse($secondNumberIn, static::UNKNOWN_REGION);
3343
                return $this->isNumberMatch($firstNumberIn, $secondNumberAsProto);
3344
            } catch (NumberParseException $e) {
3345
                if ($e->getErrorType() === NumberParseException::INVALID_COUNTRY_CODE) {
3346
                    // The second number has no country calling code. EXACT_MATCH is no longer possible.
3347
                    // We parse it as if the region was the same as that for the first number, and if
3348
                    // EXACT_MATCH is returned, we replace this with NSN_MATCH.
3349
                    $firstNumberRegion = $this->getRegionCodeForCountryCode($firstNumberIn->getCountryCode());
3350
                    try {
3351
                        if ($firstNumberRegion != static::UNKNOWN_REGION) {
3352
                            $secondNumberWithFirstNumberRegion = $this->parse($secondNumberIn, $firstNumberRegion);
3353
                            $match = $this->isNumberMatch($firstNumberIn, $secondNumberWithFirstNumberRegion);
3354
                            if ($match === MatchType::EXACT_MATCH) {
3355
                                return MatchType::NSN_MATCH;
3356
                            }
3357
                            return $match;
3358
                        } else {
3359
                            // If the first number didn't have a valid country calling code, then we parse the
3360
                            // second number without one as well.
3361
                            $secondNumberProto = new PhoneNumber();
3362
                            $this->parseHelper($secondNumberIn, null, false, false, $secondNumberProto);
3363
                            return $this->isNumberMatch($firstNumberIn, $secondNumberProto);
3364
                        }
3365
                    } catch (NumberParseException $e2) {
3366
                        // Fall-through to return NOT_A_NUMBER.
3367
                    }
3368
                }
3369
            }
3370
        }
3371
        if ($firstNumberIn instanceof PhoneNumber && $secondNumberIn instanceof PhoneNumber) {
3372
            // We only care about the fields that uniquely define a number, so we copy these across
3373
            // explicitly.
3374
            $firstNumber = self::copyCoreFieldsOnly($firstNumberIn);
3375
            $secondNumber = self::copyCoreFieldsOnly($secondNumberIn);
3376
3377
            // Early exit if both had extensions and these are different.
3378
            if ($firstNumber->hasExtension() && $secondNumber->hasExtension() &&
3379
                $firstNumber->getExtension() != $secondNumber->getExtension()
3380
            ) {
3381
                return MatchType::NO_MATCH;
3382
            }
3383
3384
            $firstNumberCountryCode = $firstNumber->getCountryCode();
3385
            $secondNumberCountryCode = $secondNumber->getCountryCode();
3386
            // Both had country_code specified.
3387
            if ($firstNumberCountryCode != 0 && $secondNumberCountryCode != 0) {
0 ignored issues
show
Bug introduced by
It seems like you are loosely comparing $firstNumberCountryCode of type integer|null to 0; this is ambiguous as not only 0 == 0 is true, but null == 0 is true, too. Consider using a strict comparison ===.
Loading history...
Bug introduced by
It seems like you are loosely comparing $secondNumberCountryCode of type integer|null to 0; this is ambiguous as not only 0 == 0 is true, but null == 0 is true, too. Consider using a strict comparison ===.
Loading history...
3388
                if ($firstNumber->equals($secondNumber)) {
3389
                    return MatchType::EXACT_MATCH;
3390
                } elseif ($firstNumberCountryCode == $secondNumberCountryCode &&
3391
                    $this->isNationalNumberSuffixOfTheOther($firstNumber, $secondNumber)
3392
                ) {
3393
                    // A SHORT_NSN_MATCH occurs if there is a difference because of the presence or absence of
3394
                    // an 'Italian leading zero', the presence or absence of an extension, or one NSN being a
3395
                    // shorter variant of the other.
3396
                    return MatchType::SHORT_NSN_MATCH;
3397
                }
3398
                // This is not a match.
3399
                return MatchType::NO_MATCH;
3400
            }
3401
            // Checks cases where one or both country_code fields were not specified. To make equality
3402
            // checks easier, we first set the country_code fields to be equal.
3403
            $firstNumber->setCountryCode($secondNumberCountryCode);
3404
            // If all else was the same, then this is an NSN_MATCH.
3405
            if ($firstNumber->equals($secondNumber)) {
3406
                return MatchType::NSN_MATCH;
3407
            }
3408
            if ($this->isNationalNumberSuffixOfTheOther($firstNumber, $secondNumber)) {
3409
                return MatchType::SHORT_NSN_MATCH;
3410
            }
3411
            return MatchType::NO_MATCH;
3412
        }
3413
        return MatchType::NOT_A_NUMBER;
3414
    }
3415
3416
    /**
3417
     * Returns true when one national number is the suffix of the other or both are the same.
3418
     * @param PhoneNumber $firstNumber
3419
     * @param PhoneNumber $secondNumber
3420
     * @return bool
3421
     */
3422
    protected function isNationalNumberSuffixOfTheOther(PhoneNumber $firstNumber, PhoneNumber $secondNumber)
3423
    {
3424
        $firstNumberNationalNumber = trim((string)$firstNumber->getNationalNumber());
3425
        $secondNumberNationalNumber = trim((string)$secondNumber->getNationalNumber());
3426
        return $this->stringEndsWithString($firstNumberNationalNumber, $secondNumberNationalNumber) ||
3427
        $this->stringEndsWithString($secondNumberNationalNumber, $firstNumberNationalNumber);
3428
    }
3429
3430
    protected function stringEndsWithString($hayStack, $needle)
3431
    {
3432
        $revNeedle = strrev($needle);
3433
        $revHayStack = strrev($hayStack);
3434
        return strpos($revHayStack, $revNeedle) === 0;
3435
    }
3436
3437
    /**
3438
     * Returns true if the supplied region supports mobile number portability. Returns false for
3439
     * invalid, unknown or regions that don't support mobile number portability.
3440
     *
3441
     * @param string $regionCode the region for which we want to know whether it supports mobile number
3442
     *                    portability or not.
3443
     * @return bool
3444
     */
3445
    public function isMobileNumberPortableRegion($regionCode)
3446
    {
3447
        $metadata = $this->getMetadataForRegion($regionCode);
3448
        if ($metadata === null) {
3449
            return false;
3450
        }
3451
3452
        return $metadata->isMobileNumberPortableRegion();
3453
    }
3454
3455
    /**
3456
     * Check whether a phone number is a possible number given a number in the form of a string, and
3457
     * the region where the number could be dialed from. It provides a more lenient check than
3458
     * {@link #isValidNumber}. See {@link #isPossibleNumber(PhoneNumber)} for details.
3459
     *
3460
     * Convenience wrapper around {@link #isPossibleNumberWithReason}. Instead of returning the reason
3461
     * for failure, this method returns a boolean value.
3462
     * for failure, this method returns true if the number is either a possible fully-qualified number
3463
     * (containing the area code and country code), or if the number could be a possible local number
3464
     * (with a country code, but missing an area code). Local numbers are considered possible if they
3465
     * could be possibly dialled in this format: if the area code is needed for a call to connect, the
3466
     * number is not considered possible without it.
3467
     *
3468
     * Note: There are two ways to call this method.
3469
     *
3470
     * isPossibleNumber(PhoneNumber $numberObject)
3471
     * isPossibleNumber(string '+441174960126', string 'GB')
3472
     *
3473
     * @param PhoneNumber|string $number the number that needs to be checked, in the form of a string
3474
     * @param string|null $regionDialingFrom the region that we are expecting the number to be dialed from.
3475
     *     Note this is different from the region where the number belongs.  For example, the number
3476
     *     +1 650 253 0000 is a number that belongs to US. When written in this form, it can be
3477
     *     dialed from any region. When it is written as 00 1 650 253 0000, it can be dialed from any
3478
     *     region which uses an international dialling prefix of 00. When it is written as
3479
     *     650 253 0000, it can only be dialed from within the US, and when written as 253 0000, it
3480
     *     can only be dialed from within a smaller area in the US (Mountain View, CA, to be more
3481
     *     specific).
3482
     * @return boolean true if the number is possible
3483
     */
3484
    public function isPossibleNumber($number, $regionDialingFrom = null)
3485
    {
3486
        if ($regionDialingFrom !== null && is_string($number)) {
3487
            try {
3488
                return $this->isPossibleNumber($this->parse($number, $regionDialingFrom));
3489
            } catch (NumberParseException $e) {
3490
                return false;
3491
            }
3492
        } else {
3493
            $result = $this->isPossibleNumberWithReason($number);
0 ignored issues
show
Bug introduced by
It seems like $number defined by parameter $number on line 3484 can also be of type string; however, libphonenumber\PhoneNumb...sibleNumberWithReason() does only seem to accept object<libphonenumber\PhoneNumber>, maybe add an additional type check?

This check looks at variables that have been passed in as parameters and are passed out again to other methods.

If the outgoing method call has stricter type requirements than the method itself, an issue is raised.

An additional type check may prevent trouble.

Loading history...
3494
            return $result === ValidationResult::IS_POSSIBLE
3495
                || $result === ValidationResult::IS_POSSIBLE_LOCAL_ONLY;
3496
        }
3497
    }
3498
3499
3500
    /**
3501
     * Check whether a phone number is a possible number. It provides a more lenient check than
3502
     * {@link #isValidNumber} in the following sense:
3503
     * <ol>
3504
     *   <li> It only checks the length of phone numbers. In particular, it doesn't check starting
3505
     *        digits of the number.
3506
     *   <li> It doesn't attempt to figure out the type of the number, but uses general rules which
3507
     *        applies to all types of phone numbers in a region. Therefore, it is much faster than
3508
     *        isValidNumber.
3509
     *   <li> For some numbers (particularly fixed-line), many regions have the concept of area code,
3510
     *        which together with subscriber number constitute the national significant number. It is
3511
     *        sometimes okay to dial only the subscriber number when dialing in the same area. This
3512
     *        function will return IS_POSSIBLE_LOCAL_ONLY if the subscriber-number-only version is
3513
     *        passed in. On the other hand, because isValidNumber validates using information on both
3514
     *        starting digits (for fixed line numbers, that would most likely be area codes) and
3515
     *        length (obviously includes the length of area codes for fixed line numbers), it will
3516
     *        return false for the subscriber-number-only version.
3517
     * </ol>
3518
     * @param PhoneNumber $number the number that needs to be checked
3519
     * @return int a ValidationResult object which indicates whether the number is possible
3520
     */
3521
    public function isPossibleNumberWithReason(PhoneNumber $number)
3522
    {
3523
        return $this->isPossibleNumberForTypeWithReason($number, PhoneNumberType::UNKNOWN);
3524
    }
3525
3526
   /**
3527
    * Check whether a phone number is a possible number of a particular type. For types that don't
3528
    * exist in a particular region, this will return a result that isn't so useful; it is recommended
3529
    * that you use {@link #getSupportedTypesForRegion} or {@link #getSupportedTypesForNonGeoEntity}
3530
    * respectively before calling this method to determine whether you should call it for this number
3531
    * at all.
3532
    *
3533
    * This provides a more lenient check than {@link #isValidNumber} in the following sense:
3534
    *
3535
    * <ol>
3536
    *   <li> It only checks the length of phone numbers. In particular, it doesn't check starting
3537
    *        digits of the number.
3538
    *   <li> For some numbers (particularly fixed-line), many regions have the concept of area code,
3539
    *        which together with subscriber number constitute the national significant number. It is
3540
    *        sometimes okay to dial only the subscriber number when dialing in the same area. This
3541
    *        function will return IS_POSSIBLE_LOCAL_ONLY if the subscriber-number-only version is
3542
    *        passed in. On the other hand, because isValidNumber validates using information on both
3543
    *        starting digits (for fixed line numbers, that would most likely be area codes) and
3544
    *        length (obviously includes the length of area codes for fixed line numbers), it will
3545
    *        return false for the subscriber-number-only version.
3546
    * </ol>
3547
    *
3548
    * @param PhoneNumber $number the number that needs to be checked
3549
    * @param int $type the PhoneNumberType we are interested in
3550
    * @return int a ValidationResult object which indicates whether the number is possible
3551
    */
3552
    public function isPossibleNumberForTypeWithReason(PhoneNumber $number, $type)
3553
    {
3554
        $nationalNumber = $this->getNationalSignificantNumber($number);
3555
        $countryCode = $number->getCountryCode();
3556
3557
        // Note: For regions that share a country calling code, like NANPA numbers, we just use the
3558
        // rules from the default region (US in this case) since the getRegionCodeForNumber will not
3559
        // work if the number is possible but not valid. There is in fact one country calling code (290)
3560
        // where the possible number pattern differs between various regions (Saint Helena and Tristan
3561
        // da Cuñha), but this is handled by putting all possible lengths for any country with this
3562
        // country calling code in the metadata for the default region in this case.
3563
        if (!$this->hasValidCountryCallingCode($countryCode)) {
3564
            return ValidationResult::INVALID_COUNTRY_CODE;
3565
        }
3566
3567
        $regionCode = $this->getRegionCodeForCountryCode($countryCode);
3568
        // Metadata cannot be null because the country calling code is valid.
3569
        $metadata = $this->getMetadataForRegionOrCallingCode($countryCode, $regionCode);
3570
        return $this->testNumberLength($nationalNumber, $metadata, $type);
0 ignored issues
show
Bug introduced by
It seems like $metadata defined by $this->getMetadataForReg...untryCode, $regionCode) on line 3569 can be null; however, libphonenumber\PhoneNumberUtil::testNumberLength() does not accept null, maybe add an additional type check?

Unless you are absolutely sure that the expression can never be null because of other conditions, we strongly recommend to add an additional type check to your code:

/** @return stdClass|null */
function mayReturnNull() { }

function doesNotAcceptNull(stdClass $x) { }

// With potential error.
function withoutCheck() {
    $x = mayReturnNull();
    doesNotAcceptNull($x); // Potential error here.
}

// Safe - Alternative 1
function withCheck1() {
    $x = mayReturnNull();
    if ( ! $x instanceof stdClass) {
        throw new \LogicException('$x must be defined.');
    }
    doesNotAcceptNull($x);
}

// Safe - Alternative 2
function withCheck2() {
    $x = mayReturnNull();
    if ($x instanceof stdClass) {
        doesNotAcceptNull($x);
    }
}
Loading history...
3571
    }
3572
3573
    /**
3574
     * Attempts to extract a valid number from a phone number that is too long to be valid, and resets
3575
     * the PhoneNumber object passed in to that valid version. If no valid number could be extracted,
3576
     * the PhoneNumber object passed in will not be modified.
3577
     * @param PhoneNumber $number a PhoneNumber object which contains a number that is too long to be valid.
3578
     * @return boolean true if a valid phone number can be successfully extracted.
3579
     */
3580
    public function truncateTooLongNumber(PhoneNumber $number)
3581
    {
3582
        if ($this->isValidNumber($number)) {
3583
            return true;
3584
        }
3585
        $numberCopy = new PhoneNumber();
3586
        $numberCopy->mergeFrom($number);
3587
        $nationalNumber = $number->getNationalNumber();
3588
        do {
3589
            $nationalNumber = floor($nationalNumber / 10);
3590
            $numberCopy->setNationalNumber($nationalNumber);
3591
            if ($this->isPossibleNumberWithReason($numberCopy) == ValidationResult::TOO_SHORT || $nationalNumber == 0) {
3592
                return false;
3593
            }
3594
        } while (!$this->isValidNumber($numberCopy));
3595
        $number->setNationalNumber($nationalNumber);
3596
        return true;
3597
    }
3598
}
3599