Completed
Pull Request — master (#188)
by Joshua
20:06 queued 05:22
created

PhoneNumberUtil::normalizeDigits()   B

Complexity

Conditions 5
Paths 5

Size

Total Lines 16
Code Lines 11

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 11
CRAP Score 5

Importance

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