Completed
Push — master ( 939550...54c69f )
by Joshua
16s
created

PhoneNumberUtil::getSupportedCallingCodes()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 4
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 1
CRAP Score 1

Importance

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