Passed
Pull Request — master (#395)
by Joshua
32:55 queued 23:47
created

PhoneNumberUtil::testNumberLength()   C

Complexity

Conditions 14
Paths 58

Size

Total Lines 76
Code Lines 33

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 31
CRAP Score 14.0436

Importance

Changes 0
Metric Value
cc 14
eloc 33
nc 58
nop 3
dl 0
loc 76
ccs 31
cts 33
cp 0.9394
crap 14.0436
rs 6.2666
c 0
b 0
f 0

How to fix   Long Method    Complexity   

Long Method

Small methods make your code easier to understand, in particular if combined with a good name. Besides, if your method is small, finding a good name is usually much easier.

For example, if you find yourself adding comments to a method's body, this is usually a good sign to extract the commented part to a new method, and use the comment as a starting point when coming up with a good name for this new method.

Commonly applied refactorings include:

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/google/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;
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;
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;
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;
227
    protected static $VALID_PHONE_NUMBER_PATTERN;
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
    protected $matcherAPI;
329
330
    /**
331
     * This class implements a singleton, so the only constructor is protected.
332
     * @param MetadataSourceInterface $metadataSource
333
     * @param $countryCallingCodeToRegionCodeMap
334
     */
335 668
    protected function __construct(MetadataSourceInterface $metadataSource, $countryCallingCodeToRegionCodeMap)
336
    {
337 668
        $this->metadataSource = $metadataSource;
338 668
        $this->countryCallingCodeToRegionCodeMap = $countryCallingCodeToRegionCodeMap;
339 668
        $this->init();
340 668
        $this->matcherAPI = RegexBasedMatcher::create();
341 668
        static::initCapturingExtnDigits();
342 668
        static::initExtnPatterns();
343 668
        static::initExtnPattern();
344 668
        static::$PLUS_CHARS_PATTERN = '[' . static::PLUS_CHARS . ']+';
345 668
        static::$SEPARATOR_PATTERN = '[' . static::VALID_PUNCTUATION . ']+';
346 668
        static::$CAPTURING_DIGIT_PATTERN = '(' . static::DIGITS . ')';
347 668
        static::initValidStartCharPattern();
348 668
        static::initAlphaPhoneMappings();
349 668
        static::initDiallableCharMappings();
350
351 668
        static::$ALL_PLUS_NUMBER_GROUPING_SYMBOLS = array();
352
        // Put (lower letter -> upper letter) and (upper letter -> upper letter) mappings.
353 668
        foreach (static::$ALPHA_MAPPINGS as $c => $value) {
354 668
            static::$ALL_PLUS_NUMBER_GROUPING_SYMBOLS[strtolower($c)] = $c;
355 668
            static::$ALL_PLUS_NUMBER_GROUPING_SYMBOLS[$c] = $c;
356
        }
357 668
        static::$ALL_PLUS_NUMBER_GROUPING_SYMBOLS += static::$asciiDigitMappings;
358 668
        static::$ALL_PLUS_NUMBER_GROUPING_SYMBOLS['-'] = '-';
359 668
        static::$ALL_PLUS_NUMBER_GROUPING_SYMBOLS["\xEF\xBC\x8D"] = '-';
360 668
        static::$ALL_PLUS_NUMBER_GROUPING_SYMBOLS["\xE2\x80\x90"] = '-';
361 668
        static::$ALL_PLUS_NUMBER_GROUPING_SYMBOLS["\xE2\x80\x91"] = '-';
362 668
        static::$ALL_PLUS_NUMBER_GROUPING_SYMBOLS["\xE2\x80\x92"] = '-';
363 668
        static::$ALL_PLUS_NUMBER_GROUPING_SYMBOLS["\xE2\x80\x93"] = '-';
364 668
        static::$ALL_PLUS_NUMBER_GROUPING_SYMBOLS["\xE2\x80\x94"] = '-';
365 668
        static::$ALL_PLUS_NUMBER_GROUPING_SYMBOLS["\xE2\x80\x95"] = '-';
366 668
        static::$ALL_PLUS_NUMBER_GROUPING_SYMBOLS["\xE2\x88\x92"] = '-';
367 668
        static::$ALL_PLUS_NUMBER_GROUPING_SYMBOLS['/'] = '/';
368 668
        static::$ALL_PLUS_NUMBER_GROUPING_SYMBOLS["\xEF\xBC\x8F"] = '/';
369 668
        static::$ALL_PLUS_NUMBER_GROUPING_SYMBOLS[' '] = ' ';
370 668
        static::$ALL_PLUS_NUMBER_GROUPING_SYMBOLS["\xE3\x80\x80"] = ' ';
371 668
        static::$ALL_PLUS_NUMBER_GROUPING_SYMBOLS["\xE2\x81\xA0"] = ' ';
372 668
        static::$ALL_PLUS_NUMBER_GROUPING_SYMBOLS['.'] = '.';
373 668
        static::$ALL_PLUS_NUMBER_GROUPING_SYMBOLS["\xEF\xBC\x8E"] = '.';
374
375
376 668
        static::initValidPhoneNumberPatterns();
377
378 668
        static::$UNWANTED_END_CHAR_PATTERN = '[^' . static::DIGITS . static::VALID_ALPHA . '#]+$';
379
380 668
        static::initMobileTokenMappings();
381
382 668
        static::$GEO_MOBILE_COUNTRIES_WITHOUT_MOBILE_AREA_CODES = array();
383 668
        static::$GEO_MOBILE_COUNTRIES_WITHOUT_MOBILE_AREA_CODES[] = 86; // China
384
385 668
        static::$GEO_MOBILE_COUNTRIES = array();
386 668
        static::$GEO_MOBILE_COUNTRIES[] = 52; // Mexico
387 668
        static::$GEO_MOBILE_COUNTRIES[] = 54; // Argentina
388 668
        static::$GEO_MOBILE_COUNTRIES[] = 55; // Brazil
389 668
        static::$GEO_MOBILE_COUNTRIES[] = 62; // Indonesia: some prefixes only (fixed CMDA wireless)
390
391 668
        static::$GEO_MOBILE_COUNTRIES = array_merge(static::$GEO_MOBILE_COUNTRIES, static::$GEO_MOBILE_COUNTRIES_WITHOUT_MOBILE_AREA_CODES);
392 668
    }
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
     * multiple times will only result in one instance being created.
401
     *
402
     * @param string $baseFileLocation
403
     * @param array|null $countryCallingCodeToRegionCodeMap
404
     * @param MetadataLoaderInterface|null $metadataLoader
405
     * @param MetadataSourceInterface|null $metadataSource
406
     * @return PhoneNumberUtil instance
407
     */
408 6321
    public static function getInstance($baseFileLocation = self::META_DATA_FILE_PREFIX, array $countryCallingCodeToRegionCodeMap = null, MetadataLoaderInterface $metadataLoader = null, MetadataSourceInterface $metadataSource = null)
409
    {
410 6321
        if (static::$instance === null) {
411 668
            if ($countryCallingCodeToRegionCodeMap === null) {
412 270
                $countryCallingCodeToRegionCodeMap = CountryCodeToRegionCodeMap::$countryCodeToRegionCodeMap;
413
            }
414
415 668
            if ($metadataLoader === null) {
416 668
                $metadataLoader = new DefaultMetadataLoader();
417
            }
418
419 668
            if ($metadataSource === null) {
420 668
                $metadataSource = new MultiFileMetadataSourceImpl($metadataLoader, __DIR__ . '/data/' . $baseFileLocation);
421
            }
422
423 668
            static::$instance = new static($metadataSource, $countryCallingCodeToRegionCodeMap);
424
        }
425 6321
        return static::$instance;
426
    }
427
428 668
    protected function init()
429
    {
430 668
        $supportedRegions = array(array());
431
432 668
        foreach ($this->countryCallingCodeToRegionCodeMap as $countryCode => $regionCodes) {
433
            // We can assume that if the country calling code maps to the non-geo entity region code then
434
            // that's the only region code it maps to.
435 668
            if (count($regionCodes) === 1 && static::REGION_CODE_FOR_NON_GEO_ENTITY === $regionCodes[0]) {
436
                // This is the subset of all country codes that map to the non-geo entity region code.
437 668
                $this->countryCodesForNonGeographicalRegion[] = $countryCode;
438
            } else {
439
                // The supported regions set does not include the "001" non-geo entity region code.
440 668
                $supportedRegions[] = $regionCodes;
441
            }
442
        }
443
444 668
        $this->supportedRegions = call_user_func_array('array_merge', $supportedRegions);
445
446
447
        // If the non-geo entity still got added to the set of supported regions it must be because
448
        // there are entries that list the non-geo entity alongside normal regions (which is wrong).
449
        // If we discover this, remove the non-geo entity from the set of supported regions and log.
450 668
        $idx_region_code_non_geo_entity = array_search(static::REGION_CODE_FOR_NON_GEO_ENTITY, $this->supportedRegions);
451 668
        if ($idx_region_code_non_geo_entity !== false) {
452
            unset($this->supportedRegions[$idx_region_code_non_geo_entity]);
453
        }
454 668
        $this->nanpaRegions = $this->countryCallingCodeToRegionCodeMap[static::NANPA_COUNTRY_CODE];
455 668
    }
456
457
    /**
458
     * @internal
459
     */
460 670
    public static function initCapturingExtnDigits()
461
    {
462 670
        static::$CAPTURING_EXTN_DIGITS = '(' . static::DIGITS . '{1,7})';
463 670
    }
464
465
    /**
466
     * @internal
467
     */
468 670
    public static function initExtnPatterns()
469
    {
470
        // One-character symbols that can be used to indicate an extension.
471 670
        $singleExtnSymbolsForMatching = "x\xEF\xBD\x98#\xEF\xBC\x83~\xEF\xBD\x9E";
472
        // For parsing, we are slightly more lenient in our interpretation than for matching. Here we
473
        // allow "comma" and "semicolon" as possible extension indicators. When matching, these are
474
        // hardly ever used to indicate this.
475 670
        $singleExtnSymbolsForParsing = ',;' . $singleExtnSymbolsForMatching;
476
477 670
        static::$EXTN_PATTERNS_FOR_PARSING = static::createExtnPattern($singleExtnSymbolsForParsing);
478 670
        static::$EXTN_PATTERNS_FOR_MATCHING = static::createExtnPattern($singleExtnSymbolsForMatching);
479 670
    }
480
481
    /**
482
     * Helper initialiser method to create the regular-expression pattern to match extensions,
483
     * allowing the one-char extension symbols provided by {@code singleExtnSymbols}.
484
     * @param string $singleExtnSymbols
485
     * @return string
486
     */
487 670
    protected static function createExtnPattern($singleExtnSymbols)
488
    {
489
        // There are three regular expressions here. The first covers RFC 3966 format, where the
490
        // extension is added using ";ext=". The second more generic one starts with optional white
491
        // space and ends with an optional full stop (.), followed by zero or more spaces/tabs/commas
492
        // and then the numbers themselves. The other one covers the special case of American numbers
493
        // where the extension is written with a hash at the end, such as "- 503#"
494
        // Note that the only capturing groups should be around the digits that you want to capture as
495
        // part of the extension, or else parsing will fail!
496
        // Canonical-equivalence doesn't seem to be an option with Android java, so we allow two options
497
        // for representing the accented o - the character itself, and one in the unicode decomposed
498
        // form with the combining acute accent.
499 670
        return (static::RFC3966_EXTN_PREFIX . static::$CAPTURING_EXTN_DIGITS . '|' . "[ \xC2\xA0\\t,]*" .
500 670
            "(?:e?xt(?:ensi(?:o\xCC\x81?|\xC3\xB3))?n?|(?:\xEF\xBD\x85)?\xEF\xBD\x98\xEF\xBD\x94(?:\xEF\xBD\x8E)?|" .
501 670
            'доб|' . '[' . $singleExtnSymbols . "]|int|\xEF\xBD\x89\xEF\xBD\x8E\xEF\xBD\x94|anexo)" .
502 670
            "[:\\.\xEF\xBC\x8E]?[ \xC2\xA0\\t,-]*" . static::$CAPTURING_EXTN_DIGITS . "\\#?|" .
503 670
            '[- ]+(' . static::DIGITS . "{1,5})\\#");
504
    }
505
506 668
    protected static function initExtnPattern()
507
    {
508 668
        static::$EXTN_PATTERN = '/(?:' . static::$EXTN_PATTERNS_FOR_PARSING . ')$/' . static::REGEX_FLAGS;
509 668
    }
510
511 670
    protected static function initValidPhoneNumberPatterns()
512
    {
513 670
        static::initCapturingExtnDigits();
514 670
        static::initExtnPatterns();
515 670
        static::$MIN_LENGTH_PHONE_NUMBER_PATTERN = '[' . static::DIGITS . ']{' . static::MIN_LENGTH_FOR_NSN . '}';
516 670
        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 . ']*';
517 670
        static::$VALID_PHONE_NUMBER_PATTERN = '%^' . static::$MIN_LENGTH_PHONE_NUMBER_PATTERN . '$|^' . static::$VALID_PHONE_NUMBER . '(?:' . static::$EXTN_PATTERNS_FOR_PARSING . ')?$%' . static::REGEX_FLAGS;
518 670
    }
519
520 670
    protected static function initAlphaPhoneMappings()
521
    {
522 670
        static::$ALPHA_PHONE_MAPPINGS = static::$ALPHA_MAPPINGS + static::$asciiDigitMappings;
523 670
    }
524
525 669
    protected static function initValidStartCharPattern()
526
    {
527 669
        static::$VALID_START_CHAR_PATTERN = '[' . static::PLUS_CHARS . static::DIGITS . ']';
528 669
    }
529
530 669
    protected static function initMobileTokenMappings()
531
    {
532 669
        static::$MOBILE_TOKEN_MAPPINGS = array();
533 669
        static::$MOBILE_TOKEN_MAPPINGS['54'] = '9';
534 669
    }
535
536 669
    protected static function initDiallableCharMappings()
537
    {
538 669
        static::$DIALLABLE_CHAR_MAPPINGS = static::$asciiDigitMappings;
539 669
        static::$DIALLABLE_CHAR_MAPPINGS[static::PLUS_SIGN] = static::PLUS_SIGN;
540 669
        static::$DIALLABLE_CHAR_MAPPINGS['*'] = '*';
541 669
        static::$DIALLABLE_CHAR_MAPPINGS['#'] = '#';
542 669
    }
543
544
    /**
545
     * Used for testing purposes only to reset the PhoneNumberUtil singleton to null.
546
     */
547 674
    public static function resetInstance()
548
    {
549 674
        static::$instance = null;
550 674
    }
551
552
    /**
553
     * Converts all alpha characters in a number to their respective digits on a keypad, but retains
554
     * existing formatting.
555
     * @param string $number
556
     * @return string
557
     */
558 2
    public static function convertAlphaCharactersInNumber($number)
559
    {
560 2
        if (static::$ALPHA_PHONE_MAPPINGS === null) {
0 ignored issues
show
introduced by
The condition static::ALPHA_PHONE_MAPPINGS === null is always false.
Loading history...
561 1
            static::initAlphaPhoneMappings();
562
        }
563
564 2
        return static::normalizeHelper($number, static::$ALPHA_PHONE_MAPPINGS, false);
565
    }
566
567
    /**
568
     * Normalizes a string of characters representing a phone number by replacing all characters found
569
     * in the accompanying map with the values therein, and stripping all other characters if
570
     * removeNonMatches is true.
571
     *
572
     * @param string $number a string of characters representing a phone number
573
     * @param array $normalizationReplacements a mapping of characters to what they should be replaced by in
574
     * the normalized version of the phone number
575
     * @param bool $removeNonMatches indicates whether characters that are not able to be replaced
576
     * should be stripped from the number. If this is false, they will be left unchanged in the number.
577
     * @return string the normalized string version of the phone number
578
     */
579 40
    protected static function normalizeHelper($number, array $normalizationReplacements, $removeNonMatches)
580
    {
581 40
        $normalizedNumber = '';
582 40
        $strLength = mb_strlen($number, 'UTF-8');
583 40
        for ($i = 0; $i < $strLength; $i++) {
584 40
            $character = mb_substr($number, $i, 1, 'UTF-8');
585 40
            if (isset($normalizationReplacements[mb_strtoupper($character, 'UTF-8')])) {
586 40
                $normalizedNumber .= $normalizationReplacements[mb_strtoupper($character, 'UTF-8')];
587 40
            } elseif (!$removeNonMatches) {
588 2
                $normalizedNumber .= $character;
589
            }
590
            // If neither of the above are true, we remove this character.
591
        }
592 40
        return $normalizedNumber;
593
    }
594
595
    /**
596
     * Helper function to check if the national prefix formatting rule has the first group only, i.e.,
597
     * does not start with the national prefix.
598
     * @param string $nationalPrefixFormattingRule
599
     * @return bool
600
     */
601 61
    public static function formattingRuleHasFirstGroupOnly($nationalPrefixFormattingRule)
602
    {
603 61
        $firstGroupOnlyPrefixPatternMatcher = new Matcher(
604 61
            static::FIRST_GROUP_ONLY_PREFIX_PATTERN,
605
            $nationalPrefixFormattingRule
606
        );
607
608 61
        return mb_strlen($nationalPrefixFormattingRule) === 0
609 61
            || $firstGroupOnlyPrefixPatternMatcher->matches();
610
    }
611
612
    /**
613
     * Returns all regions the library has metadata for.
614
     *
615
     * @return array An unordered array of the two-letter region codes for every geographical region the
616
     *  library supports
617
     */
618 246
    public function getSupportedRegions()
619
    {
620 246
        return $this->supportedRegions;
621
    }
622
623
    /**
624
     * Returns all global network calling codes the library has metadata for.
625
     *
626
     * @return array An unordered array of the country calling codes for every non-geographical entity
627
     *  the library supports
628
     */
629 2
    public function getSupportedGlobalNetworkCallingCodes()
630
    {
631 2
        return $this->countryCodesForNonGeographicalRegion;
632
    }
633
634
    /**
635
     * Returns all country calling codes the library has metadata for, covering both non-geographical
636
     * entities (global network calling codes) and those used for geographical entities. The could be
637
     * used to populate a drop-down box of country calling codes for a phone-number widget, for
638
     * instance.
639
     *
640
     * @return array An unordered array of the country calling codes for every geographical and
641
     *      non-geographical entity the library supports
642
     */
643 1
    public function getSupportedCallingCodes()
644
    {
645 1
        return array_keys($this->countryCallingCodeToRegionCodeMap);
646
    }
647
648
    /**
649
     * Returns true if there is any possible number data set for a particular PhoneNumberDesc.
650
     *
651
     * @param PhoneNumberDesc $desc
652
     * @return bool
653
     */
654 5
    protected static function descHasPossibleNumberData(PhoneNumberDesc $desc)
655
    {
656
        // If this is empty, it means numbers of this type inherit from the "general desc" -> the value
657
        // '-1' means that no numbers exist for this type.
658 5
        $possibleLength = $desc->getPossibleLength();
659 5
        return count($possibleLength) != 1 || $possibleLength[0] != -1;
660
    }
661
662
    /**
663
     * Returns true if there is any data set for a particular PhoneNumberDesc.
664
     *
665
     * @param PhoneNumberDesc $desc
666
     * @return bool
667
     */
668 2
    protected static function descHasData(PhoneNumberDesc $desc)
669
    {
670
        // Checking most properties since we don't know what's present, since a custom build may have
671
        // stripped just one of them (e.g. liteBuild strips exampleNumber). We don't bother checking the
672
        // possibleLengthsLocalOnly, since if this is the only thing that's present we don't really
673
        // support the type at all: no type-specific methods will work with only this data.
674 2
        return $desc->hasExampleNumber()
675 2
            || static::descHasPossibleNumberData($desc)
676 2
            || $desc->hasNationalNumberPattern();
677
    }
678
679
    /**
680
     * Returns the types we have metadata for based on the PhoneMetadata object passed in
681
     *
682
     * @param PhoneMetadata $metadata
683
     * @return array
684
     */
685 2
    private function getSupportedTypesForMetadata(PhoneMetadata $metadata)
686
    {
687 2
        $types = array();
688 2
        foreach (array_keys(PhoneNumberType::values()) as $type) {
689 2
            if ($type === PhoneNumberType::FIXED_LINE_OR_MOBILE || $type === PhoneNumberType::UNKNOWN) {
690
                // Never return FIXED_LINE_OR_MOBILE (it is a convenience type, and represents that a
691
                // particular number type can't be determined) or UNKNOWN (the non-type).
692 2
                continue;
693
            }
694
695 2
            if (self::descHasData($this->getNumberDescByType($metadata, $type))) {
696 2
                $types[] = $type;
697
            }
698
        }
699
700 2
        return $types;
701
    }
702
703
    /**
704
     * Returns the types for a given region which the library has metadata for. Will not include
705
     * FIXED_LINE_OR_MOBILE (if the numbers in this region could be classified as FIXED_LINE_OR_MOBILE,
706
     * both FIXED_LINE and MOBILE would be present) and UNKNOWN.
707
     *
708
     * No types will be returned for invalid or unknown region codes.
709
     *
710
     * @param string $regionCode
711
     * @return array
712
     */
713 1
    public function getSupportedTypesForRegion($regionCode)
714
    {
715 1
        if (!$this->isValidRegionCode($regionCode)) {
716 1
            return array();
717
        }
718 1
        $metadata = $this->getMetadataForRegion($regionCode);
719 1
        return $this->getSupportedTypesForMetadata($metadata);
0 ignored issues
show
Bug introduced by
It seems like $metadata can also be of type null; however, parameter $metadata of libphonenumber\PhoneNumb...ortedTypesForMetadata() does only seem to accept libphonenumber\PhoneMetadata, maybe add an additional type check? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

719
        return $this->getSupportedTypesForMetadata(/** @scrutinizer ignore-type */ $metadata);
Loading history...
720
    }
721
722
    /**
723
     * Returns the types for a country-code belonging to a non-geographical entity which the library
724
     * has metadata for. Will not include FIXED_LINE_OR_MOBILE (if numbers for this non-geographical
725
     * entity could be classified as FIXED_LINE_OR_MOBILE, both FIXED_LINE and MOBILE would be
726
     * present) and UNKNOWN.
727
     *
728
     * @param int $countryCallingCode
729
     * @return array
730
     */
731 1
    public function getSupportedTypesForNonGeoEntity($countryCallingCode)
732
    {
733 1
        $metadata = $this->getMetadataForNonGeographicalRegion($countryCallingCode);
734 1
        if ($metadata === null) {
735 1
            return array();
736
        }
737
738 1
        return $this->getSupportedTypesForMetadata($metadata);
739
    }
740
741
    /**
742
     * Gets the length of the geographical area code from the {@code nationalNumber} field of the
743
     * PhoneNumber object passed in, so that clients could use it to split a national significant
744
     * number into geographical area code and subscriber number. It works in such a way that the
745
     * resultant subscriber number should be diallable, at least on some devices. An example of how
746
     * this could be used:
747
     *
748
     * <code>
749
     * $phoneUtil = PhoneNumberUtil::getInstance();
750
     * $number = $phoneUtil->parse("16502530000", "US");
751
     * $nationalSignificantNumber = $phoneUtil->getNationalSignificantNumber($number);
752
     *
753
     * $areaCodeLength = $phoneUtil->getLengthOfGeographicalAreaCode($number);
754
     * if ($areaCodeLength > 0)
755
     * {
756
     *     $areaCode = substr($nationalSignificantNumber, 0,$areaCodeLength);
757
     *     $subscriberNumber = substr($nationalSignificantNumber, $areaCodeLength);
758
     * } else {
759
     *     $areaCode = "";
760
     *     $subscriberNumber = $nationalSignificantNumber;
761
     * }
762
     * </code>
763
     *
764
     * N.B.: area code is a very ambiguous concept, so the I18N team generally recommends against
765
     * using it for most purposes, but recommends using the more general {@code nationalNumber}
766
     * instead. Read the following carefully before deciding to use this method:
767
     * <ul>
768
     *  <li> geographical area codes change over time, and this method honors those changes;
769
     *    therefore, it doesn't guarantee the stability of the result it produces.
770
     *  <li> subscriber numbers may not be diallable from all devices (notably mobile devices, which
771
     *    typically requires the full national_number to be dialled in most regions).
772
     *  <li> most non-geographical numbers have no area codes, including numbers from non-geographical
773
     *    entities
774
     *  <li> some geographical numbers have no area codes.
775
     * </ul>
776
     * @param PhoneNumber $number PhoneNumber object for which clients want to know the length of the area code.
777
     * @return int the length of area code of the PhoneNumber object passed in.
778
     */
779 1
    public function getLengthOfGeographicalAreaCode(PhoneNumber $number)
780
    {
781 1
        $metadata = $this->getMetadataForRegion($this->getRegionCodeForNumber($number));
782 1
        if ($metadata === null) {
783 1
            return 0;
784
        }
785
        // If a country doesn't use a national prefix, and this number doesn't have an Italian leading
786
        // zero, we assume it is a closed dialling plan with no area codes.
787 1
        if (!$metadata->hasNationalPrefix() && !$number->isItalianLeadingZero()) {
0 ignored issues
show
Bug Best Practice introduced by
The expression $number->isItalianLeadingZero() of type boolean|null is loosely compared to false; this is ambiguous if the boolean can be false. You might want to explicitly use !== null instead.

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

$a = canBeFalseAndNull();

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

// Better use one of the explicit versions:
if ($a !== null) { }
if ($a !== false) { }
if ($a !== null && $a !== false) { }
Loading history...
788 1
            return 0;
789
        }
790
791 1
        $type = $this->getNumberType($number);
792 1
        $countryCallingCode = $number->getCountryCode();
793
794 1
        if ($type === PhoneNumberType::MOBILE
795
            // Note this is a rough heuristic; it doesn't cover Indonesia well, for example, where area
796
            // codes are present for some mobile phones but not for others. We have no better way of
797
            // representing this in the metadata at this point.
798 1
            && in_array($countryCallingCode, self::$GEO_MOBILE_COUNTRIES_WITHOUT_MOBILE_AREA_CODES)
799
        ) {
800 1
            return 0;
801
        }
802
803 1
        if (!$this->isNumberGeographical($type, $countryCallingCode)) {
804 1
            return 0;
805
        }
806
807 1
        return $this->getLengthOfNationalDestinationCode($number);
808
    }
809
810
    /**
811
     * Returns the metadata for the given region code or {@code null} if the region code is invalid
812
     * or unknown.
813
     * @param string $regionCode
814
     * @return null|PhoneMetadata
815
     */
816 5224
    public function getMetadataForRegion($regionCode)
817
    {
818 5224
        if (!$this->isValidRegionCode($regionCode)) {
819 349
            return null;
820
        }
821
822 5211
        return $this->metadataSource->getMetadataForRegion($regionCode);
823
    }
824
825
    /**
826
     * Helper function to check region code is not unknown or null.
827
     * @param string $regionCode
828
     * @return bool
829
     */
830 5225
    protected function isValidRegionCode($regionCode)
831
    {
832 5225
        return $regionCode !== null && in_array($regionCode, $this->supportedRegions);
833
    }
834
835
    /**
836
     * Returns the region where a phone number is from. This could be used for geocoding at the region
837
     * level. Only guarantees correct results for valid, full numbers (not short-codes, or invalid
838
     * numbers).
839
     *
840
     * @param PhoneNumber $number the phone number whose origin we want to know
841
     * @return null|string  the region where the phone number is from, or null if no region matches this calling
842
     * code
843
     */
844 2291
    public function getRegionCodeForNumber(PhoneNumber $number)
845
    {
846 2291
        $countryCode = $number->getCountryCode();
847 2291
        if (!isset($this->countryCallingCodeToRegionCodeMap[$countryCode])) {
848 4
            return null;
849
        }
850 2290
        $regions = $this->countryCallingCodeToRegionCodeMap[$countryCode];
851 2290
        if (count($regions) == 1) {
852 1722
            return $regions[0];
853
        }
854
855 592
        return $this->getRegionCodeForNumberFromRegionList($number, $regions);
856
    }
857
858
    /**
859
     * @param PhoneNumber $number
860
     * @param array $regionCodes
861
     * @return null|string
862
     */
863 592
    protected function getRegionCodeForNumberFromRegionList(PhoneNumber $number, array $regionCodes)
864
    {
865 592
        $nationalNumber = $this->getNationalSignificantNumber($number);
866 592
        foreach ($regionCodes as $regionCode) {
867
            // If leadingDigits is present, use this. Otherwise, do full validation.
868
            // Metadata cannot be null because the region codes come from the country calling code map.
869 592
            $metadata = $this->getMetadataForRegion($regionCode);
870 592
            if ($metadata->hasLeadingDigits()) {
871 286
                $nbMatches = preg_match(
872 286
                    '/' . $metadata->getLeadingDigits() . '/',
873
                    $nationalNumber,
874
                    $matches,
875 286
                    PREG_OFFSET_CAPTURE
876
                );
877 286
                if ($nbMatches > 0 && $matches[0][1] === 0) {
878 286
                    return $regionCode;
879
                }
880 490
            } elseif ($this->getNumberTypeHelper($nationalNumber, $metadata) != PhoneNumberType::UNKNOWN) {
0 ignored issues
show
Bug introduced by
It seems like $metadata can also be of type null; however, parameter $metadata of libphonenumber\PhoneNumb...::getNumberTypeHelper() does only seem to accept libphonenumber\PhoneMetadata, maybe add an additional type check? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

880
            } elseif ($this->getNumberTypeHelper($nationalNumber, /** @scrutinizer ignore-type */ $metadata) != PhoneNumberType::UNKNOWN) {
Loading history...
881 275
                return $regionCode;
882
            }
883
        }
884 70
        return null;
885
    }
886
887
    /**
888
     * Gets the national significant number of the a phone number. Note a national significant number
889
     * doesn't contain a national prefix or any formatting.
890
     *
891
     * @param PhoneNumber $number the phone number for which the national significant number is needed
892
     * @return string the national significant number of the PhoneNumber object passed in
893
     */
894 2191
    public function getNationalSignificantNumber(PhoneNumber $number)
895
    {
896
        // If leading zero(s) have been set, we prefix this now. Note this is not a national prefix.
897 2191
        $nationalNumber = '';
898 2191
        if ($number->isItalianLeadingZero() && $number->getNumberOfLeadingZeros() > 0) {
899 82
            $zeros = str_repeat('0', $number->getNumberOfLeadingZeros());
900 82
            $nationalNumber .= $zeros;
901
        }
902 2191
        $nationalNumber .= $number->getNationalNumber();
903 2191
        return $nationalNumber;
904
    }
905
906
    /**
907
     * @param string $nationalNumber
908
     * @param PhoneMetadata $metadata
909
     * @return int PhoneNumberType constant
910
     */
911 2092
    protected function getNumberTypeHelper($nationalNumber, PhoneMetadata $metadata)
912
    {
913 2092
        if (!$this->isNumberMatchingDesc($nationalNumber, $metadata->getGeneralDesc())) {
914 319
            return PhoneNumberType::UNKNOWN;
915
        }
916 1831
        if ($this->isNumberMatchingDesc($nationalNumber, $metadata->getPremiumRate())) {
917 163
            return PhoneNumberType::PREMIUM_RATE;
918
        }
919 1669
        if ($this->isNumberMatchingDesc($nationalNumber, $metadata->getTollFree())) {
920 195
            return PhoneNumberType::TOLL_FREE;
921
        }
922
923
924 1486
        if ($this->isNumberMatchingDesc($nationalNumber, $metadata->getSharedCost())) {
925 56
            return PhoneNumberType::SHARED_COST;
926
        }
927 1430
        if ($this->isNumberMatchingDesc($nationalNumber, $metadata->getVoip())) {
928 92
            return PhoneNumberType::VOIP;
929
        }
930 1342
        if ($this->isNumberMatchingDesc($nationalNumber, $metadata->getPersonalNumber())) {
931 61
            return PhoneNumberType::PERSONAL_NUMBER;
932
        }
933 1281
        if ($this->isNumberMatchingDesc($nationalNumber, $metadata->getPager())) {
934 25
            return PhoneNumberType::PAGER;
935
        }
936 1259
        if ($this->isNumberMatchingDesc($nationalNumber, $metadata->getUan())) {
937 66
            return PhoneNumberType::UAN;
938
        }
939 1196
        if ($this->isNumberMatchingDesc($nationalNumber, $metadata->getVoicemail())) {
940 15
            return PhoneNumberType::VOICEMAIL;
941
        }
942 1182
        $isFixedLine = $this->isNumberMatchingDesc($nationalNumber, $metadata->getFixedLine());
943 1182
        if ($isFixedLine) {
944 885
            if ($metadata->getSameMobileAndFixedLinePattern()) {
945
                return PhoneNumberType::FIXED_LINE_OR_MOBILE;
946
            }
947
948 885
            if ($this->isNumberMatchingDesc($nationalNumber, $metadata->getMobile())) {
949 112
                return PhoneNumberType::FIXED_LINE_OR_MOBILE;
950
            }
951 782
            return PhoneNumberType::FIXED_LINE;
952
        }
953
        // Otherwise, test to see if the number is mobile. Only do this if certain that the patterns for
954
        // mobile and fixed line aren't the same.
955 425
        if (!$metadata->getSameMobileAndFixedLinePattern() &&
956 425
            $this->isNumberMatchingDesc($nationalNumber, $metadata->getMobile())
957
        ) {
958 260
            return PhoneNumberType::MOBILE;
959
        }
960 190
        return PhoneNumberType::UNKNOWN;
961
    }
962
963
    /**
964
     * @param string $nationalNumber
965
     * @param PhoneNumberDesc $numberDesc
966
     * @return bool
967
     */
968 2092
    public function isNumberMatchingDesc($nationalNumber, PhoneNumberDesc $numberDesc)
969
    {
970
        // Check if any possible number lengths are present; if so, we use them to avoid checking the
971
        // validation pattern if they don't match. If they are absent, this means they match the general
972
        // description, which we have already checked before checking a specific number type.
973 2092
        $actualLength = mb_strlen($nationalNumber);
974 2092
        $possibleLengths = $numberDesc->getPossibleLength();
975 2092
        if (count($possibleLengths) > 0 && !in_array($actualLength, $possibleLengths)) {
976 1690
            return false;
977
        }
978
979 1869
        return $this->matcherAPI->matchNationalNumber($nationalNumber, $numberDesc, false);
980
    }
981
982
    /**
983
     * isNumberGeographical(PhoneNumber)
984
     *
985
     * Tests whether a phone number has a geographical association. It checks if the number is
986
     * associated with a certain region in the country to which it belongs. Note that this doesn't
987
     * verify if the number is actually in use.
988
     *
989
     * isNumberGeographical(PhoneNumberType, $countryCallingCode)
990
     *
991
     * Tests whether a phone number has a geographical association, as represented by its type and the
992
     * country it belongs to.
993
     *
994
     * This version exists since calculating the phone number type is expensive; if we have already
995
     * done this, we don't want to do it again.
996
     *
997
     * @param PhoneNumber|int $phoneNumberObjOrType A PhoneNumber object, or a PhoneNumberType integer
998
     * @param int|null $countryCallingCode Used when passing a PhoneNumberType
999
     * @return bool
1000
     */
1001 21
    public function isNumberGeographical($phoneNumberObjOrType, $countryCallingCode = null)
1002
    {
1003 21
        if ($phoneNumberObjOrType instanceof PhoneNumber) {
1004 1
            return $this->isNumberGeographical($this->getNumberType($phoneNumberObjOrType), $phoneNumberObjOrType->getCountryCode());
1005
        }
1006
1007 21
        return $phoneNumberObjOrType == PhoneNumberType::FIXED_LINE
1008 17
        || $phoneNumberObjOrType == PhoneNumberType::FIXED_LINE_OR_MOBILE
1009 12
        || (in_array($countryCallingCode, static::$GEO_MOBILE_COUNTRIES)
1010 21
            && $phoneNumberObjOrType == PhoneNumberType::MOBILE);
1011
    }
1012
1013
    /**
1014
     * Gets the type of a valid phone number.
1015
     * @param PhoneNumber $number the number the phone number that we want to know the type
1016
     * @return int PhoneNumberType the type of the phone number, or UNKNOWN if it is invalid
1017
     */
1018 1400
    public function getNumberType(PhoneNumber $number)
1019
    {
1020 1400
        $regionCode = $this->getRegionCodeForNumber($number);
1021 1400
        $metadata = $this->getMetadataForRegionOrCallingCode($number->getCountryCode(), $regionCode);
1022 1400
        if ($metadata === null) {
1023 8
            return PhoneNumberType::UNKNOWN;
1024
        }
1025 1399
        $nationalSignificantNumber = $this->getNationalSignificantNumber($number);
1026 1399
        return $this->getNumberTypeHelper($nationalSignificantNumber, $metadata);
1027
    }
1028
1029
    /**
1030
     * @param int $countryCallingCode
1031
     * @param string $regionCode
1032
     * @return null|PhoneMetadata
1033
     */
1034 2144
    protected function getMetadataForRegionOrCallingCode($countryCallingCode, $regionCode)
1035
    {
1036 2144
        return static::REGION_CODE_FOR_NON_GEO_ENTITY === $regionCode ?
1037 2144
            $this->getMetadataForNonGeographicalRegion($countryCallingCode) : $this->getMetadataForRegion($regionCode);
1038
    }
1039
1040
    /**
1041
     * @param int $countryCallingCode
1042
     * @return null|PhoneMetadata
1043
     */
1044 34
    public function getMetadataForNonGeographicalRegion($countryCallingCode)
1045
    {
1046 34
        if (!isset($this->countryCallingCodeToRegionCodeMap[$countryCallingCode])) {
1047 2
            return null;
1048
        }
1049 34
        return $this->metadataSource->getMetadataForNonGeographicalRegion($countryCallingCode);
1050
    }
1051
1052
    /**
1053
     * Gets the length of the national destination code (NDC) from the PhoneNumber object passed in,
1054
     * so that clients could use it to split a national significant number into NDC and subscriber
1055
     * number. The NDC of a phone number is normally the first group of digit(s) right after the
1056
     * country calling code when the number is formatted in the international format, if there is a
1057
     * subscriber number part that follows.
1058
     *
1059
     * follows.
1060
     *
1061
     * N.B.: similar to an area code, not all numbers have an NDC!
1062
     *
1063
     * An example of how this could be used:
1064
     *
1065
     * <code>
1066
     * $phoneUtil = PhoneNumberUtil::getInstance();
1067
     * $number = $phoneUtil->parse("18002530000", "US");
1068
     * $nationalSignificantNumber = $phoneUtil->getNationalSignificantNumber($number);
1069
     *
1070
     * $nationalDestinationCodeLength = $phoneUtil->getLengthOfNationalDestinationCode($number);
1071
     * if ($nationalDestinationCodeLength > 0) {
1072
     *     $nationalDestinationCode = substr($nationalSignificantNumber, 0, $nationalDestinationCodeLength);
1073
     *     $subscriberNumber = substr($nationalSignificantNumber, $nationalDestinationCodeLength);
1074
     * } else {
1075
     *     $nationalDestinationCode = "";
1076
     *     $subscriberNumber = $nationalSignificantNumber;
1077
     * }
1078
     * </code>
1079
     *
1080
     * Refer to the unit tests to see the difference between this function and
1081
     * {@link #getLengthOfGeographicalAreaCode}.
1082
     *
1083
     * @param PhoneNumber $number the PhoneNumber object for which clients want to know the length of the NDC.
1084
     * @return int the length of NDC of the PhoneNumber object passed in, which could be zero
1085
     */
1086 2
    public function getLengthOfNationalDestinationCode(PhoneNumber $number)
1087
    {
1088 2
        if ($number->hasExtension()) {
1089
            // We don't want to alter the proto given to us, but we don't want to include the extension
1090
            // when we format it, so we copy it and clear the extension here.
1091
            $copiedProto = new PhoneNumber();
1092
            $copiedProto->mergeFrom($number);
1093
            $copiedProto->clearExtension();
1094
        } else {
1095 2
            $copiedProto = clone $number;
1096
        }
1097
1098 2
        $nationalSignificantNumber = $this->format($copiedProto, PhoneNumberFormat::INTERNATIONAL);
1099
1100 2
        $numberGroups = preg_split('/' . static::NON_DIGITS_PATTERN . '/', $nationalSignificantNumber);
1101
1102
        // The pattern will start with "+COUNTRY_CODE " so the first group will always be the empty
1103
        // string (before the + symbol) and the second group will be the country calling code. The third
1104
        // group will be area code if it is not the last group.
1105 2
        if (count($numberGroups) <= 3) {
0 ignored issues
show
Bug introduced by
It seems like $numberGroups can also be of type false; however, parameter $var of count() does only seem to accept Countable|array, maybe add an additional type check? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

1105
        if (count(/** @scrutinizer ignore-type */ $numberGroups) <= 3) {
Loading history...
1106 1
            return 0;
1107
        }
1108
1109 2
        if ($this->getNumberType($number) == PhoneNumberType::MOBILE) {
1110
            // For example Argentinian mobile numbers, when formatted in the international format, are in
1111
            // the form of +54 9 NDC XXXX.... As a result, we take the length of the third group (NDC) and
1112
            // add the length of the second group (which is the mobile token), which also forms part of
1113
            // the national significant number. This assumes that the mobile token is always formatted
1114
            // separately from the rest of the phone number.
1115
1116 2
            $mobileToken = static::getCountryMobileToken($number->getCountryCode());
1117 2
            if ($mobileToken !== '') {
1118 2
                return mb_strlen($numberGroups[2]) + mb_strlen($numberGroups[3]);
1119
            }
1120
        }
1121 2
        return mb_strlen($numberGroups[2]);
1122
    }
1123
1124
    /**
1125
     * Formats a phone number in the specified format using default rules. Note that this does not
1126
     * promise to produce a phone number that the user can dial from where they are - although we do
1127
     * format in either 'national' or 'international' format depending on what the client asks for, we
1128
     * do not currently support a more abbreviated format, such as for users in the same "area" who
1129
     * could potentially dial the number without area code. Note that if the phone number has a
1130
     * country calling code of 0 or an otherwise invalid country calling code, we cannot work out
1131
     * which formatting rules to apply so we return the national significant number with no formatting
1132
     * applied.
1133
     *
1134
     * @param PhoneNumber $number the phone number to be formatted
1135
     * @param int $numberFormat the PhoneNumberFormat the phone number should be formatted into
1136
     * @return string the formatted phone number
1137
     */
1138 344
    public function format(PhoneNumber $number, $numberFormat)
1139
    {
1140 344
        if ($number->getNationalNumber() == 0 && $number->hasRawInput()) {
0 ignored issues
show
Bug Best Practice introduced by
It seems like you are loosely comparing $number->getNationalNumber() of type null|string 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...
1141
            // Unparseable numbers that kept their raw input just use that.
1142
            // This is the only case where a number can be formatted as E164 without a
1143
            // leading '+' symbol (but the original number wasn't parseable anyway).
1144
            // TODO: Consider removing the 'if' above so that unparseable
1145
            // strings without raw input format to the empty string instead of "+00"
1146 1
            $rawInput = $number->getRawInput();
1147 1
            if (mb_strlen($rawInput) > 0) {
1148 1
                return $rawInput;
1149
            }
1150
        }
1151
1152 344
        $formattedNumber = '';
1153 344
        $countryCallingCode = $number->getCountryCode();
1154 344
        $nationalSignificantNumber = $this->getNationalSignificantNumber($number);
1155
1156 344
        if ($numberFormat == PhoneNumberFormat::E164) {
1157
            // Early exit for E164 case (even if the country calling code is invalid) since no formatting
1158
            // of the national number needs to be applied. Extensions are not formatted.
1159 266
            $formattedNumber .= $nationalSignificantNumber;
1160 266
            $this->prefixNumberWithCountryCallingCode($countryCallingCode, PhoneNumberFormat::E164, $formattedNumber);
1161 266
            return $formattedNumber;
1162
        }
1163
1164 95
        if (!$this->hasValidCountryCallingCode($countryCallingCode)) {
1165 1
            $formattedNumber .= $nationalSignificantNumber;
1166 1
            return $formattedNumber;
1167
        }
1168
1169
        // Note getRegionCodeForCountryCode() is used because formatting information for regions which
1170
        // share a country calling code is contained by only one region for performance reasons. For
1171
        // example, for NANPA regions it will be contained in the metadata for US.
1172 95
        $regionCode = $this->getRegionCodeForCountryCode($countryCallingCode);
1173
        // Metadata cannot be null because the country calling code is valid (which means that the
1174
        // region code cannot be ZZ and must be one of our supported region codes).
1175 95
        $metadata = $this->getMetadataForRegionOrCallingCode($countryCallingCode, $regionCode);
1176 95
        $formattedNumber .= $this->formatNsn($nationalSignificantNumber, $metadata, $numberFormat);
1177 95
        $this->maybeAppendFormattedExtension($number, $metadata, $numberFormat, $formattedNumber);
1178 95
        $this->prefixNumberWithCountryCallingCode($countryCallingCode, $numberFormat, $formattedNumber);
1179 95
        return $formattedNumber;
1180
    }
1181
1182
    /**
1183
     * A helper function that is used by format and formatByPattern.
1184
     * @param int $countryCallingCode
1185
     * @param int $numberFormat PhoneNumberFormat
1186
     * @param string $formattedNumber
1187
     */
1188 345
    protected function prefixNumberWithCountryCallingCode($countryCallingCode, $numberFormat, &$formattedNumber)
1189
    {
1190
        switch ($numberFormat) {
1191 345
            case PhoneNumberFormat::E164:
1192 266
                $formattedNumber = static::PLUS_SIGN . $countryCallingCode . $formattedNumber;
1193 266
                return;
1194 96
            case PhoneNumberFormat::INTERNATIONAL:
1195 20
                $formattedNumber = static::PLUS_SIGN . $countryCallingCode . ' ' . $formattedNumber;
1196 20
                return;
1197 93
            case PhoneNumberFormat::RFC3966:
1198 59
                $formattedNumber = static::RFC3966_PREFIX . static::PLUS_SIGN . $countryCallingCode . '-' . $formattedNumber;
1199 59
                return;
1200 39
            case PhoneNumberFormat::NATIONAL:
1201
            default:
1202 39
                return;
1203
        }
1204
    }
1205
1206
    /**
1207
     * Helper function to check the country calling code is valid.
1208
     * @param int $countryCallingCode
1209
     * @return bool
1210
     */
1211 166
    protected function hasValidCountryCallingCode($countryCallingCode)
1212
    {
1213 166
        return isset($this->countryCallingCodeToRegionCodeMap[$countryCallingCode]);
1214
    }
1215
1216
    /**
1217
     * Returns the region code that matches the specific country calling code. In the case of no
1218
     * region code being found, ZZ will be returned. In the case of multiple regions, the one
1219
     * designated in the metadata as the "main" region for this calling code will be returned. If the
1220
     * countryCallingCode entered is valid but doesn't match a specific region (such as in the case of
1221
     * non-geographical calling codes like 800) the value "001" will be returned (corresponding to
1222
     * the value for World in the UN M.49 schema).
1223
     *
1224
     * @param int $countryCallingCode
1225
     * @return string
1226
     */
1227 522
    public function getRegionCodeForCountryCode($countryCallingCode)
1228
    {
1229 522
        $regionCodes = isset($this->countryCallingCodeToRegionCodeMap[$countryCallingCode]) ? $this->countryCallingCodeToRegionCodeMap[$countryCallingCode] : null;
1230 522
        return $regionCodes === null ? static::UNKNOWN_REGION : $regionCodes[0];
1231
    }
1232
1233
    /**
1234
     * Note in some regions, the national number can be written in two completely different ways
1235
     * depending on whether it forms part of the NATIONAL format or INTERNATIONAL format. The
1236
     * numberFormat parameter here is used to specify which format to use for those cases. If a
1237
     * carrierCode is specified, this will be inserted into the formatted string to replace $CC.
1238
     * @param string $number
1239
     * @param PhoneMetadata $metadata
1240
     * @param int $numberFormat PhoneNumberFormat
1241
     * @param null|string $carrierCode
1242
     * @return string
1243
     */
1244 96
    protected function formatNsn($number, PhoneMetadata $metadata, $numberFormat, $carrierCode = null)
1245
    {
1246 96
        $intlNumberFormats = $metadata->intlNumberFormats();
1247
        // When the intlNumberFormats exists, we use that to format national number for the
1248
        // INTERNATIONAL format instead of using the numberDesc.numberFormats.
1249 96
        $availableFormats = (count($intlNumberFormats) == 0 || $numberFormat == PhoneNumberFormat::NATIONAL)
1250 76
            ? $metadata->numberFormats()
1251 96
            : $metadata->intlNumberFormats();
1252 96
        $formattingPattern = $this->chooseFormattingPatternForNumber($availableFormats, $number);
1253 96
        return ($formattingPattern === null)
1254 8
            ? $number
1255 96
            : $this->formatNsnUsingPattern($number, $formattingPattern, $numberFormat, $carrierCode);
1256
    }
1257
1258
    /**
1259
     * @param NumberFormat[] $availableFormats
1260
     * @param string $nationalNumber
1261
     * @return NumberFormat|null
1262
     */
1263 129
    public function chooseFormattingPatternForNumber(array $availableFormats, $nationalNumber)
1264
    {
1265 129
        foreach ($availableFormats as $numFormat) {
1266 129
            $leadingDigitsPatternMatcher = null;
1267 129
            $size = $numFormat->leadingDigitsPatternSize();
1268
            // We always use the last leading_digits_pattern, as it is the most detailed.
1269 129
            if ($size > 0) {
1270 98
                $leadingDigitsPatternMatcher = new Matcher(
1271 98
                    $numFormat->getLeadingDigitsPattern($size - 1),
1272
                    $nationalNumber
1273
                );
1274
            }
1275 129
            if ($size == 0 || $leadingDigitsPatternMatcher->lookingAt()) {
1276 128
                $m = new Matcher($numFormat->getPattern(), $nationalNumber);
1277 128
                if ($m->matches() > 0) {
1278 128
                    return $numFormat;
1279
                }
1280
            }
1281
        }
1282 9
        return null;
1283
    }
1284
1285
    /**
1286
     * Note that carrierCode is optional - if null or an empty string, no carrier code replacement
1287
     * will take place.
1288
     * @param string $nationalNumber
1289
     * @param NumberFormat $formattingPattern
1290
     * @param int $numberFormat PhoneNumberFormat
1291
     * @param null|string $carrierCode
1292
     * @return string
1293
     */
1294 96
    public function formatNsnUsingPattern(
1295
        $nationalNumber,
1296
        NumberFormat $formattingPattern,
1297
        $numberFormat,
1298
        $carrierCode = null
1299
    ) {
1300 96
        $numberFormatRule = $formattingPattern->getFormat();
1301 96
        $m = new Matcher($formattingPattern->getPattern(), $nationalNumber);
1302 96
        if ($numberFormat === PhoneNumberFormat::NATIONAL &&
1303 96
            $carrierCode !== null && mb_strlen($carrierCode) > 0 &&
1304 96
            mb_strlen($formattingPattern->getDomesticCarrierCodeFormattingRule()) > 0
1305
        ) {
1306
            // Replace the $CC in the formatting rule with the desired carrier code.
1307 2
            $carrierCodeFormattingRule = $formattingPattern->getDomesticCarrierCodeFormattingRule();
1308 2
            $carrierCodeFormattingRule = str_replace(static::CC_STRING, $carrierCode, $carrierCodeFormattingRule);
1309
            // Now replace the $FG in the formatting rule with the first group and the carrier code
1310
            // combined in the appropriate way.
1311 2
            $firstGroupMatcher = new Matcher(static::FIRST_GROUP_PATTERN, $numberFormatRule);
1312 2
            $numberFormatRule = $firstGroupMatcher->replaceFirst($carrierCodeFormattingRule);
1313 2
            $formattedNationalNumber = $m->replaceAll($numberFormatRule);
1314
        } else {
1315
            // Use the national prefix formatting rule instead.
1316 96
            $nationalPrefixFormattingRule = $formattingPattern->getNationalPrefixFormattingRule();
1317 96
            if ($numberFormat == PhoneNumberFormat::NATIONAL &&
1318 96
                $nationalPrefixFormattingRule !== null &&
1319 96
                mb_strlen($nationalPrefixFormattingRule) > 0
1320
            ) {
1321 22
                $firstGroupMatcher = new Matcher(static::FIRST_GROUP_PATTERN, $numberFormatRule);
1322 22
                $formattedNationalNumber = $m->replaceAll(
1323 22
                    $firstGroupMatcher->replaceFirst($nationalPrefixFormattingRule)
1324
                );
1325
            } else {
1326 89
                $formattedNationalNumber = $m->replaceAll($numberFormatRule);
1327
            }
1328
        }
1329 96
        if ($numberFormat == PhoneNumberFormat::RFC3966) {
1330
            // Strip any leading punctuation.
1331 59
            $matcher = new Matcher(static::$SEPARATOR_PATTERN, $formattedNationalNumber);
1332 59
            if ($matcher->lookingAt()) {
1333 1
                $formattedNationalNumber = $matcher->replaceFirst('');
1334
            }
1335
            // Replace the rest with a dash between each number group.
1336 59
            $formattedNationalNumber = $matcher->reset($formattedNationalNumber)->replaceAll('-');
1337
        }
1338 96
        return $formattedNationalNumber;
1339
    }
1340
1341
    /**
1342
     * Appends the formatted extension of a phone number to formattedNumber, if the phone number had
1343
     * an extension specified.
1344
     *
1345
     * @param PhoneNumber $number
1346
     * @param PhoneMetadata|null $metadata
1347
     * @param int $numberFormat PhoneNumberFormat
1348
     * @param string $formattedNumber
1349
     */
1350 97
    protected function maybeAppendFormattedExtension(PhoneNumber $number, $metadata, $numberFormat, &$formattedNumber)
1351
    {
1352 97
        if ($number->hasExtension() && mb_strlen($number->getExtension()) > 0) {
1353 13
            if ($numberFormat === PhoneNumberFormat::RFC3966) {
1354 12
                $formattedNumber .= static::RFC3966_EXTN_PREFIX . $number->getExtension();
1355 3
            } elseif (!empty($metadata) && $metadata->hasPreferredExtnPrefix()) {
1356 2
                $formattedNumber .= $metadata->getPreferredExtnPrefix() . $number->getExtension();
1357
            } else {
1358 2
                $formattedNumber .= static::DEFAULT_EXTN_PREFIX . $number->getExtension();
1359
            }
1360
        }
1361 97
    }
1362
1363
    /**
1364
     * Returns the mobile token for the provided country calling code if it has one, otherwise
1365
     * returns an empty string. A mobile token is a number inserted before the area code when dialing
1366
     * a mobile number from that country from abroad.
1367
     *
1368
     * @param int $countryCallingCode the country calling code for which we want the mobile token
1369
     * @return string the mobile token, as a string, for the given country calling code
1370
     */
1371 16
    public static function getCountryMobileToken($countryCallingCode)
1372
    {
1373 16
        if (count(static::$MOBILE_TOKEN_MAPPINGS) === 0) {
1374 1
            static::initMobileTokenMappings();
1375
        }
1376
1377 16
        if (array_key_exists($countryCallingCode, static::$MOBILE_TOKEN_MAPPINGS)) {
1378 5
            return static::$MOBILE_TOKEN_MAPPINGS[$countryCallingCode];
1379
        }
1380 14
        return '';
1381
    }
1382
1383
    /**
1384
     * Checks if the number is a valid vanity (alpha) number such as 800 MICROSOFT. A valid vanity
1385
     * number will start with at least 3 digits and will have three or more alpha characters. This
1386
     * does not do region-specific checks - to work out if this number is actually valid for a region,
1387
     * it should be parsed and methods such as {@link #isPossibleNumberWithReason} and
1388
     * {@link #isValidNumber} should be used.
1389
     *
1390
     * @param string $number the number that needs to be checked
1391
     * @return bool true if the number is a valid vanity number
1392
     */
1393 1
    public function isAlphaNumber($number)
1394
    {
1395 1
        if (!static::isViablePhoneNumber($number)) {
1396
            // Number is too short, or doesn't match the basic phone number pattern.
1397 1
            return false;
1398
        }
1399 1
        $this->maybeStripExtension($number);
1400 1
        return (bool)preg_match('/' . static::VALID_ALPHA_PHONE_PATTERN . '/' . static::REGEX_FLAGS, $number);
1401
    }
1402
1403
    /**
1404
     * Checks to see if the string of characters could possibly be a phone number at all. At the
1405
     * moment, checks to see that the string begins with at least 2 digits, ignoring any punctuation
1406
     * commonly found in phone numbers.
1407
     * This method does not require the number to be normalized in advance - but does assume that
1408
     * leading non-number symbols have been removed, such as by the method extractPossibleNumber.
1409
     *
1410
     * @param string $number to be checked for viability as a phone number
1411
     * @return boolean true if the number could be a phone number of some sort, otherwise false
1412
     */
1413 3283
    public static function isViablePhoneNumber($number)
1414
    {
1415 3283
        if (static::$VALID_PHONE_NUMBER_PATTERN === null) {
1416 2
            static::initValidPhoneNumberPatterns();
1417
        }
1418
1419 3283
        if (mb_strlen($number) < static::MIN_LENGTH_FOR_NSN) {
1420 25
            return false;
1421
        }
1422
1423 3282
        $validPhoneNumberPattern = static::getValidPhoneNumberPattern();
1424
1425 3282
        $m = preg_match($validPhoneNumberPattern, $number);
1426 3282
        return $m > 0;
1427
    }
1428
1429
    /**
1430
     * We append optionally the extension pattern to the end here, as a valid phone number may
1431
     * have an extension prefix appended, followed by 1 or more digits.
1432
     * @return string
1433
     */
1434 3282
    protected static function getValidPhoneNumberPattern()
1435
    {
1436 3282
        return static::$VALID_PHONE_NUMBER_PATTERN;
1437
    }
1438
1439
    /**
1440
     * Strips any extension (as in, the part of the number dialled after the call is connected,
1441
     * usually indicated with extn, ext, x or similar) from the end of the number, and returns it.
1442
     *
1443
     * @param string $number the non-normalized telephone number that we wish to strip the extension from
1444
     * @return string the phone extension
1445
     */
1446 3277
    protected function maybeStripExtension(&$number)
1447
    {
1448 3277
        $matches = array();
1449 3277
        $find = preg_match(static::$EXTN_PATTERN, $number, $matches, PREG_OFFSET_CAPTURE);
1450
        // If we find a potential extension, and the number preceding this is a viable number, we assume
1451
        // it is an extension.
1452 3277
        if ($find > 0 && static::isViablePhoneNumber(substr($number, 0, $matches[0][1]))) {
1453
            // The numbers are captured into groups in the regular expression.
1454
1455 29
            for ($i = 1, $length = count($matches); $i <= $length; $i++) {
1456 29
                if ($matches[$i][0] != '') {
1457
                    // We go through the capturing groups until we find one that captured some digits. If none
1458
                    // did, then we will return the empty string.
1459 29
                    $extension = $matches[$i][0];
1460 29
                    $number = substr($number, 0, $matches[0][1]);
1461 29
                    return $extension;
1462
                }
1463
            }
1464
        }
1465 3255
        return '';
1466
    }
1467
1468
    /**
1469
     * Parses a string and returns it in proto buffer format. This method differs from {@link #parse}
1470
     * in that it always populates the raw_input field of the protocol buffer with numberToParse as
1471
     * well as the country_code_source field.
1472
     *
1473
     * @param string $numberToParse number that we are attempting to parse. This can contain formatting
1474
     *                                  such as +, ( and -, as well as a phone number extension. It can also
1475
     *                                  be provided in RFC3966 format.
1476
     * @param string $defaultRegion region that we are expecting the number to be from. This is only used
1477
     *                                  if the number being parsed is not written in international format.
1478
     *                                  The country calling code for the number in this case would be stored
1479
     *                                  as that of the default region supplied.
1480
     * @param PhoneNumber $phoneNumber
1481
     * @return PhoneNumber              a phone number proto buffer filled with the parsed number
1482
     */
1483 182
    public function parseAndKeepRawInput($numberToParse, $defaultRegion, PhoneNumber $phoneNumber = null)
1484
    {
1485 182
        if ($phoneNumber === null) {
1486 182
            $phoneNumber = new PhoneNumber();
1487
        }
1488 182
        $this->parseHelper($numberToParse, $defaultRegion, true, true, $phoneNumber);
1489 181
        return $phoneNumber;
1490
    }
1491
1492
    /**
1493
     * Returns an iterable over all PhoneNumberMatches in $text
1494
     *
1495
     * @param string $text
1496
     * @param string $defaultRegion
1497
     * @param AbstractLeniency $leniency Defaults to Leniency::VALID()
1498
     * @param int $maxTries Defaults to PHP_INT_MAX
1499
     * @return PhoneNumberMatcher
1500
     */
1501 207
    public function findNumbers($text, $defaultRegion, AbstractLeniency $leniency = null, $maxTries = PHP_INT_MAX)
1502
    {
1503 207
        if ($leniency === null) {
1504 18
            $leniency = Leniency::VALID();
1505
        }
1506
1507 207
        return new PhoneNumberMatcher($this, $text, $defaultRegion, $leniency, $maxTries);
1508
    }
1509
1510
    /**
1511
     * Gets an AsYouTypeFormatter for the specific region.
1512
     *
1513
     * @param string $regionCode The region where the phone number is being entered.
1514
     * @return AsYouTypeFormatter
1515
     */
1516 33
    public function getAsYouTypeFormatter($regionCode)
1517
    {
1518 33
        return new AsYouTypeFormatter($regionCode);
1519
    }
1520
1521
    /**
1522
     * A helper function to set the values related to leading zeros in a PhoneNumber.
1523
     * @param string $nationalNumber
1524
     * @param PhoneNumber $phoneNumber
1525
     */
1526 3274
    public static function setItalianLeadingZerosForPhoneNumber($nationalNumber, PhoneNumber $phoneNumber)
1527
    {
1528 3274
        if (strlen($nationalNumber) > 1 && substr($nationalNumber, 0, 1) == '0') {
1529 125
            $phoneNumber->setItalianLeadingZero(true);
1530 125
            $numberOfLeadingZeros = 1;
1531
            // Note that if the national number is all "0"s, the last "0" is not counted as a leading
1532
            // zero.
1533 125
            while ($numberOfLeadingZeros < (strlen($nationalNumber) - 1) &&
1534 125
                substr($nationalNumber, $numberOfLeadingZeros, 1) == '0') {
1535 20
                $numberOfLeadingZeros++;
1536
            }
1537
1538 125
            if ($numberOfLeadingZeros != 1) {
1539 20
                $phoneNumber->setNumberOfLeadingZeros($numberOfLeadingZeros);
1540
            }
1541
        }
1542 3274
    }
1543
1544
    /**
1545
     * Parses a string and fills up the phoneNumber. This method is the same as the public
1546
     * parse() method, with the exception that it allows the default region to be null, for use by
1547
     * isNumberMatch(). checkRegion should be set to false if it is permitted for the default region
1548
     * to be null or unknown ("ZZ").
1549
     * @param string $numberToParse
1550
     * @param string $defaultRegion
1551
     * @param bool $keepRawInput
1552
     * @param bool $checkRegion
1553
     * @param PhoneNumber $phoneNumber
1554
     * @throws NumberParseException
1555
     */
1556 3280
    protected function parseHelper($numberToParse, $defaultRegion, $keepRawInput, $checkRegion, PhoneNumber $phoneNumber)
1557
    {
1558 3280
        if ($numberToParse === null) {
0 ignored issues
show
introduced by
The condition $numberToParse === null is always false.
Loading history...
1559 2
            throw new NumberParseException(NumberParseException::NOT_A_NUMBER, 'The phone number supplied was null.');
1560
        }
1561
1562 3279
        $numberToParse = trim($numberToParse);
1563
1564 3279
        if (mb_strlen($numberToParse) > static::MAX_INPUT_STRING_LENGTH) {
1565 1
            throw new NumberParseException(
1566 1
                NumberParseException::TOO_LONG,
1567 1
                'The string supplied was too long to parse.'
1568
            );
1569
        }
1570
1571 3278
        $nationalNumber = '';
1572 3278
        $this->buildNationalNumberForParsing($numberToParse, $nationalNumber);
1573
1574 3278
        if (!static::isViablePhoneNumber($nationalNumber)) {
1575 26
            throw new NumberParseException(
1576 26
                NumberParseException::NOT_A_NUMBER,
1577 26
                'The string supplied did not seem to be a phone number.'
1578
            );
1579
        }
1580
1581
        // Check the region supplied is valid, or that the extracted number starts with some sort of +
1582
        // sign so the number's region can be determined.
1583 3277
        if ($checkRegion && !$this->checkRegionForParsing($nationalNumber, $defaultRegion)) {
1584 7
            throw new NumberParseException(
1585 7
                NumberParseException::INVALID_COUNTRY_CODE,
1586 7
                'Missing or invalid default region.'
1587
            );
1588
        }
1589
1590 3276
        if ($keepRawInput) {
1591 181
            $phoneNumber->setRawInput($numberToParse);
1592
        }
1593
        // Attempt to parse extension first, since it doesn't require region-specific data and we want
1594
        // to have the non-normalised number here.
1595 3276
        $extension = $this->maybeStripExtension($nationalNumber);
1596 3276
        if (mb_strlen($extension) > 0) {
1597 28
            $phoneNumber->setExtension($extension);
1598
        }
1599
1600 3276
        $regionMetadata = $this->getMetadataForRegion($defaultRegion);
1601
        // Check to see if the number is given in international format so we know whether this number is
1602
        // from the default region or not.
1603 3276
        $normalizedNationalNumber = '';
1604
        try {
1605
            // TODO: This method should really just take in the string buffer that has already
1606
            // been created, and just remove the prefix, rather than taking in a string and then
1607
            // outputting a string buffer.
1608 3276
            $countryCode = $this->maybeExtractCountryCode(
1609 3276
                $nationalNumber,
1610
                $regionMetadata,
1611
                $normalizedNationalNumber,
1612
                $keepRawInput,
1613
                $phoneNumber
1614
            );
1615 15
        } catch (NumberParseException $e) {
1616 15
            $matcher = new Matcher(static::$PLUS_CHARS_PATTERN, $nationalNumber);
1617 15
            if ($e->getErrorType() == NumberParseException::INVALID_COUNTRY_CODE && $matcher->lookingAt()) {
1618
                // Strip the plus-char, and try again.
1619 6
                $countryCode = $this->maybeExtractCountryCode(
1620 6
                    substr($nationalNumber, $matcher->end()),
1621
                    $regionMetadata,
1622
                    $normalizedNationalNumber,
1623
                    $keepRawInput,
1624
                    $phoneNumber
1625
                );
1626 6
                if ($countryCode == 0) {
1627 5
                    throw new NumberParseException(
1628 5
                        NumberParseException::INVALID_COUNTRY_CODE,
1629 6
                        'Could not interpret numbers after plus-sign.'
1630
                    );
1631
                }
1632
            } else {
1633 10
                throw new NumberParseException($e->getErrorType(), $e->getMessage(), $e);
1634
            }
1635
        }
1636 3276
        if ($countryCode !== 0) {
1637 347
            $phoneNumberRegion = $this->getRegionCodeForCountryCode($countryCode);
1638 347
            if ($phoneNumberRegion != $defaultRegion) {
1639
                // Metadata cannot be null because the country calling code is valid.
1640 347
                $regionMetadata = $this->getMetadataForRegionOrCallingCode($countryCode, $phoneNumberRegion);
1641
            }
1642
        } else {
1643
            // If no extracted country calling code, use the region supplied instead. The national number
1644
            // is just the normalized version of the number we were given to parse.
1645
1646 3206
            $normalizedNationalNumber .= static::normalize($nationalNumber);
1647 3206
            if ($defaultRegion !== null) {
0 ignored issues
show
introduced by
The condition $defaultRegion !== null is always true.
Loading history...
1648 3206
                $countryCode = $regionMetadata->getCountryCode();
1649 3206
                $phoneNumber->setCountryCode($countryCode);
1650 3
            } elseif ($keepRawInput) {
1651
                $phoneNumber->clearCountryCodeSource();
1652
            }
1653
        }
1654 3276
        if (mb_strlen($normalizedNationalNumber) < static::MIN_LENGTH_FOR_NSN) {
1655 2
            throw new NumberParseException(
1656 2
                NumberParseException::TOO_SHORT_NSN,
1657 2
                'The string supplied is too short to be a phone number.'
1658
            );
1659
        }
1660 3275
        if ($regionMetadata !== null) {
1661 3275
            $carrierCode = '';
1662 3275
            $potentialNationalNumber = $normalizedNationalNumber;
1663 3275
            $this->maybeStripNationalPrefixAndCarrierCode($potentialNationalNumber, $regionMetadata, $carrierCode);
1664
            // We require that the NSN remaining after stripping the national prefix and carrier code be
1665
            // long enough to be a possible length for the region. Otherwise, we don't do the stripping,
1666
            // since the original number could be a valid short number.
1667 3275
            $validationResult = $this->testNumberLength($potentialNationalNumber, $regionMetadata);
1668 3275
            if ($validationResult !== ValidationResult::TOO_SHORT
1669 3275
                && $validationResult !== ValidationResult::IS_POSSIBLE_LOCAL_ONLY
1670 3275
                && $validationResult !== ValidationResult::INVALID_LENGTH) {
1671 2110
                $normalizedNationalNumber = $potentialNationalNumber;
1672 2110
                if ($keepRawInput && mb_strlen($carrierCode) > 0) {
1673 1
                    $phoneNumber->setPreferredDomesticCarrierCode($carrierCode);
1674
                }
1675
            }
1676
        }
1677 3275
        $lengthOfNationalNumber = mb_strlen($normalizedNationalNumber);
1678 3275
        if ($lengthOfNationalNumber < static::MIN_LENGTH_FOR_NSN) {
1679
            throw new NumberParseException(
1680
                NumberParseException::TOO_SHORT_NSN,
1681
                'The string supplied is too short to be a phone number.'
1682
            );
1683
        }
1684 3275
        if ($lengthOfNationalNumber > static::MAX_LENGTH_FOR_NSN) {
1685 3
            throw new NumberParseException(
1686 3
                NumberParseException::TOO_LONG,
1687 3
                'The string supplied is too long to be a phone number.'
1688
            );
1689
        }
1690 3274
        static::setItalianLeadingZerosForPhoneNumber($normalizedNationalNumber, $phoneNumber);
1691
1692
        /*
1693
         * We have to store the National Number as a string instead of a "long" as Google do
1694
         *
1695
         * Since PHP doesn't always support 64 bit INTs, this was a float, but that had issues
1696
         * with long numbers.
1697
         *
1698
         * We have to remove the leading zeroes ourself though
1699
         */
1700 3274
        if ((int)$normalizedNationalNumber == 0) {
1701 29
            $normalizedNationalNumber = '0';
1702
        } else {
1703 3250
            $normalizedNationalNumber = ltrim($normalizedNationalNumber, '0');
1704
        }
1705
1706 3274
        $phoneNumber->setNationalNumber($normalizedNationalNumber);
1707 3274
    }
1708
1709
    /**
1710
     * Returns a new phone number containing only the fields needed to uniquely identify a phone
1711
     * number, rather than any fields that capture the context in which  the phone number was created.
1712
     * These fields correspond to those set in parse() rather than parseAndKeepRawInput()
1713
     *
1714
     * @param PhoneNumber $phoneNumberIn
1715
     * @return PhoneNumber
1716
     */
1717 8
    protected static function copyCoreFieldsOnly(PhoneNumber $phoneNumberIn)
1718
    {
1719 8
        $phoneNumber = new PhoneNumber();
1720 8
        $phoneNumber->setCountryCode($phoneNumberIn->getCountryCode());
1721 8
        $phoneNumber->setNationalNumber($phoneNumberIn->getNationalNumber());
1722 8
        if (mb_strlen($phoneNumberIn->getExtension()) > 0) {
1723 3
            $phoneNumber->setExtension($phoneNumberIn->getExtension());
1724
        }
1725 8
        if ($phoneNumberIn->isItalianLeadingZero()) {
1726 4
            $phoneNumber->setItalianLeadingZero(true);
1727
            // This field is only relevant if there are leading zeros at all.
1728 4
            $phoneNumber->setNumberOfLeadingZeros($phoneNumberIn->getNumberOfLeadingZeros());
1729
        }
1730 8
        return $phoneNumber;
1731
    }
1732
1733
    /**
1734
     * Converts numberToParse to a form that we can parse and write it to nationalNumber if it is
1735
     * written in RFC3966; otherwise extract a possible number out of it and write to nationalNumber.
1736
     * @param string $numberToParse
1737
     * @param string $nationalNumber
1738
     */
1739 3278
    protected function buildNationalNumberForParsing($numberToParse, &$nationalNumber)
1740
    {
1741 3278
        $indexOfPhoneContext = strpos($numberToParse, static::RFC3966_PHONE_CONTEXT);
1742 3278
        if ($indexOfPhoneContext !== false) {
1743 6
            $phoneContextStart = $indexOfPhoneContext + mb_strlen(static::RFC3966_PHONE_CONTEXT);
1744
            // If the phone context contains a phone number prefix, we need to capture it, whereas domains
1745
            // will be ignored.
1746 6
            if ($phoneContextStart < (strlen($numberToParse) - 1)
1747 6
                && substr($numberToParse, $phoneContextStart, 1) == static::PLUS_SIGN) {
1748
                // Additional parameters might follow the phone context. If so, we will remove them here
1749
                // because the parameters after phone context are not important for parsing the
1750
                // phone number.
1751 3
                $phoneContextEnd = strpos($numberToParse, ';', $phoneContextStart);
1752 3
                if ($phoneContextEnd > 0) {
1753 1
                    $nationalNumber .= substr($numberToParse, $phoneContextStart, $phoneContextEnd - $phoneContextStart);
1754
                } else {
1755 3
                    $nationalNumber .= substr($numberToParse, $phoneContextStart);
1756
                }
1757
            }
1758
1759
            // Now append everything between the "tel:" prefix and the phone-context. This should include
1760
            // the national number, an optional extension or isdn-subaddress component. Note we also
1761
            // handle the case when "tel:" is missing, as we have seen in some of the phone number inputs.
1762
            // In that case, we append everything from the beginning.
1763
1764 6
            $indexOfRfc3966Prefix = strpos($numberToParse, static::RFC3966_PREFIX);
1765 6
            $indexOfNationalNumber = ($indexOfRfc3966Prefix !== false) ? $indexOfRfc3966Prefix + strlen(static::RFC3966_PREFIX) : 0;
1766 6
            $nationalNumber .= substr(
1767 6
                $numberToParse,
1768
                $indexOfNationalNumber,
1769 6
                $indexOfPhoneContext - $indexOfNationalNumber
1770
            );
1771
        } else {
1772
            // Extract a possible number from the string passed in (this strips leading characters that
1773
            // could not be the start of a phone number.)
1774 3278
            $nationalNumber .= static::extractPossibleNumber($numberToParse);
0 ignored issues
show
Bug introduced by
$numberToParse of type string is incompatible with the type integer expected by parameter $number of libphonenumber\PhoneNumb...extractPossibleNumber(). ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

1774
            $nationalNumber .= static::extractPossibleNumber(/** @scrutinizer ignore-type */ $numberToParse);
Loading history...
1775
        }
1776
1777
        // Delete the isdn-subaddress and everything after it if it is present. Note extension won't
1778
        // appear at the same time with isdn-subaddress according to paragraph 5.3 of the RFC3966 spec,
1779 3278
        $indexOfIsdn = strpos($nationalNumber, static::RFC3966_ISDN_SUBADDRESS);
1780 3278
        if ($indexOfIsdn > 0) {
1781 5
            $nationalNumber = substr($nationalNumber, 0, $indexOfIsdn);
1782
        }
1783
        // If both phone context and isdn-subaddress are absent but other parameters are present, the
1784
        // parameters are left in nationalNumber. This is because we are concerned about deleting
1785
        // content from a potential number string when there is no strong evidence that the number is
1786
        // actually written in RFC3966.
1787 3278
    }
1788
1789
    /**
1790
     * Attempts to extract a possible number from the string passed in. This currently strips all
1791
     * leading characters that cannot be used to start a phone number. Characters that can be used to
1792
     * start a phone number are defined in the VALID_START_CHAR_PATTERN. If none of these characters
1793
     * are found in the number passed in, an empty string is returned. This function also attempts to
1794
     * strip off any alternative extensions or endings if two or more are present, such as in the case
1795
     * of: (530) 583-6985 x302/x2303. The second extension here makes this actually two phone numbers,
1796
     * (530) 583-6985 x302 and (530) 583-6985 x2303. We remove the second extension so that the first
1797
     * number is parsed correctly.
1798
     *
1799
     * @param int $number the string that might contain a phone number
1800
     * @return string the number, stripped of any non-phone-number prefix (such as "Tel:") or an empty
1801
     *                string if no character used to start phone numbers (such as + or any digit) is
1802
     *                found in the number
1803
     */
1804 3301
    public static function extractPossibleNumber($number)
1805
    {
1806 3301
        if (static::$VALID_START_CHAR_PATTERN === null) {
1807 1
            static::initValidStartCharPattern();
1808
        }
1809
1810 3301
        $matches = array();
1811 3301
        $match = preg_match('/' . static::$VALID_START_CHAR_PATTERN . '/ui', $number, $matches, PREG_OFFSET_CAPTURE);
1812 3301
        if ($match > 0) {
1813 3301
            $number = substr($number, $matches[0][1]);
1814
            // Remove trailing non-alpha non-numerical characters.
1815 3301
            $trailingCharsMatcher = new Matcher(static::$UNWANTED_END_CHAR_PATTERN, $number);
1816 3301
            if ($trailingCharsMatcher->find() && $trailingCharsMatcher->start() > 0) {
1817 2
                $number = substr($number, 0, $trailingCharsMatcher->start());
1818
            }
1819
1820
            // Check for extra numbers at the end.
1821 3301
            $match = preg_match('%' . static::$SECOND_NUMBER_START_PATTERN . '%', $number, $matches, PREG_OFFSET_CAPTURE);
1822 3301
            if ($match > 0) {
1823 1
                $number = substr($number, 0, $matches[0][1]);
1824
            }
1825
1826 3301
            return $number;
1827
        }
1828
1829 6
        return '';
1830
    }
1831
1832
    /**
1833
     * Checks to see that the region code used is valid, or if it is not valid, that the number to
1834
     * parse starts with a + symbol so that we can attempt to infer the region from the number.
1835
     * Returns false if it cannot use the region provided and the region cannot be inferred.
1836
     * @param string $numberToParse
1837
     * @param string $defaultRegion
1838
     * @return bool
1839
     */
1840 3277
    protected function checkRegionForParsing($numberToParse, $defaultRegion)
1841
    {
1842 3277
        if (!$this->isValidRegionCode($defaultRegion)) {
1843
            // If the number is null or empty, we can't infer the region.
1844 274
            $plusCharsPatternMatcher = new Matcher(static::$PLUS_CHARS_PATTERN, $numberToParse);
1845 274
            if ($numberToParse === null || mb_strlen($numberToParse) == 0 || !$plusCharsPatternMatcher->lookingAt()) {
1846 7
                return false;
1847
            }
1848
        }
1849 3276
        return true;
1850
    }
1851
1852
    /**
1853
     * Tries to extract a country calling code from a number. This method will return zero if no
1854
     * country calling code is considered to be present. Country calling codes are extracted in the
1855
     * following ways:
1856
     * <ul>
1857
     *  <li> by stripping the international dialing prefix of the region the person is dialing from,
1858
     *       if this is present in the number, and looking at the next digits
1859
     *  <li> by stripping the '+' sign if present and then looking at the next digits
1860
     *  <li> by comparing the start of the number and the country calling code of the default region.
1861
     *       If the number is not considered possible for the numbering plan of the default region
1862
     *       initially, but starts with the country calling code of this region, validation will be
1863
     *       reattempted after stripping this country calling code. If this number is considered a
1864
     *       possible number, then the first digits will be considered the country calling code and
1865
     *       removed as such.
1866
     * </ul>
1867
     * It will throw a NumberParseException if the number starts with a '+' but the country calling
1868
     * code supplied after this does not match that of any known region.
1869
     *
1870
     * @param string $number non-normalized telephone number that we wish to extract a country calling
1871
     *     code from - may begin with '+'
1872
     * @param PhoneMetadata $defaultRegionMetadata metadata about the region this number may be from
1873
     * @param string $nationalNumber a string buffer to store the national significant number in, in the case
1874
     *     that a country calling code was extracted. The number is appended to any existing contents.
1875
     *     If no country calling code was extracted, this will be left unchanged.
1876
     * @param bool $keepRawInput true if the country_code_source and preferred_carrier_code fields of
1877
     *     phoneNumber should be populated.
1878
     * @param PhoneNumber $phoneNumber the PhoneNumber object where the country_code and country_code_source need
1879
     *     to be populated. Note the country_code is always populated, whereas country_code_source is
1880
     *     only populated when keepCountryCodeSource is true.
1881
     * @return int the country calling code extracted or 0 if none could be extracted
1882
     * @throws NumberParseException
1883
     */
1884 3277
    public function maybeExtractCountryCode(
1885
        $number,
1886
        PhoneMetadata $defaultRegionMetadata = null,
1887
        &$nationalNumber,
1888
        $keepRawInput,
1889
        PhoneNumber $phoneNumber
1890
    ) {
1891 3277
        if (mb_strlen($number) == 0) {
1892
            return 0;
1893
        }
1894 3277
        $fullNumber = $number;
1895
        // Set the default prefix to be something that will never match.
1896 3277
        $possibleCountryIddPrefix = 'NonMatch';
1897 3277
        if ($defaultRegionMetadata !== null) {
1898 3259
            $possibleCountryIddPrefix = $defaultRegionMetadata->getInternationalPrefix();
1899
        }
1900 3277
        $countryCodeSource = $this->maybeStripInternationalPrefixAndNormalize($fullNumber, $possibleCountryIddPrefix);
1901
1902 3277
        if ($keepRawInput) {
1903 182
            $phoneNumber->setCountryCodeSource($countryCodeSource);
1904
        }
1905 3277
        if ($countryCodeSource != CountryCodeSource::FROM_DEFAULT_COUNTRY) {
1906 340
            if (mb_strlen($fullNumber) <= static::MIN_LENGTH_FOR_NSN) {
1907 10
                throw new NumberParseException(
1908 10
                    NumberParseException::TOO_SHORT_AFTER_IDD,
1909 10
                    'Phone number had an IDD, but after this was not long enough to be a viable phone number.'
1910
                );
1911
            }
1912 339
            $potentialCountryCode = $this->extractCountryCode($fullNumber, $nationalNumber);
1913
1914 339
            if ($potentialCountryCode != 0) {
1915 339
                $phoneNumber->setCountryCode($potentialCountryCode);
1916 339
                return $potentialCountryCode;
1917
            }
1918
1919
            // If this fails, they must be using a strange country calling code that we don't recognize,
1920
            // or that doesn't exist.
1921 8
            throw new NumberParseException(
1922 8
                NumberParseException::INVALID_COUNTRY_CODE,
1923 8
                'Country calling code supplied was not recognised.'
1924
            );
1925
        }
1926
1927 3217
        if ($defaultRegionMetadata !== null) {
1928
            // Check to see if the number starts with the country calling code for the default region. If
1929
            // so, we remove the country calling code, and do some checks on the validity of the number
1930
            // before and after.
1931 3217
            $defaultCountryCode = $defaultRegionMetadata->getCountryCode();
1932 3217
            $defaultCountryCodeString = (string)$defaultCountryCode;
1933 3217
            $normalizedNumber = $fullNumber;
1934 3217
            if (strpos($normalizedNumber, $defaultCountryCodeString) === 0) {
1935 106
                $potentialNationalNumber = substr($normalizedNumber, mb_strlen($defaultCountryCodeString));
1936 106
                $generalDesc = $defaultRegionMetadata->getGeneralDesc();
1937
                // Don't need the carrier code.
1938 106
                $carriercode = null;
1939 106
                $this->maybeStripNationalPrefixAndCarrierCode(
1940 106
                    $potentialNationalNumber,
1941
                    $defaultRegionMetadata,
1942
                    $carriercode
1943
                );
1944
                // If the number was not valid before but is valid now, or if it was too long before, we
1945
                // consider the number with the country calling code stripped to be a better result and
1946
                // keep that instead.
1947 106
                if ((!$this->matcherAPI->matchNationalNumber($fullNumber, $generalDesc, false)
1948 71
                        && $this->matcherAPI->matchNationalNumber($potentialNationalNumber, $generalDesc, false))
1949 106
                    || $this->testNumberLength($fullNumber, $defaultRegionMetadata) === ValidationResult::TOO_LONG
1950
                ) {
1951 24
                    $nationalNumber .= $potentialNationalNumber;
1952 24
                    if ($keepRawInput) {
1953 15
                        $phoneNumber->setCountryCodeSource(CountryCodeSource::FROM_NUMBER_WITHOUT_PLUS_SIGN);
1954
                    }
1955 24
                    $phoneNumber->setCountryCode($defaultCountryCode);
1956 24
                    return $defaultCountryCode;
1957
                }
1958
            }
1959
        }
1960
        // No country calling code present.
1961 3207
        $phoneNumber->setCountryCode(0);
1962 3207
        return 0;
1963
    }
1964
1965
    /**
1966
     * Strips any international prefix (such as +, 00, 011) present in the number provided, normalizes
1967
     * the resulting number, and indicates if an international prefix was present.
1968
     *
1969
     * @param string $number the non-normalized telephone number that we wish to strip any international
1970
     *     dialing prefix from.
1971
     * @param string $possibleIddPrefix string the international direct dialing prefix from the region we
1972
     *     think this number may be dialed in
1973
     * @return int the corresponding CountryCodeSource if an international dialing prefix could be
1974
     *     removed from the number, otherwise CountryCodeSource.FROM_DEFAULT_COUNTRY if the number did
1975
     *     not seem to be in international format.
1976
     */
1977 3278
    public function maybeStripInternationalPrefixAndNormalize(&$number, $possibleIddPrefix)
1978
    {
1979 3278
        if (mb_strlen($number) == 0) {
1980
            return CountryCodeSource::FROM_DEFAULT_COUNTRY;
1981
        }
1982 3278
        $matches = array();
1983
        // Check to see if the number begins with one or more plus signs.
1984 3278
        $match = preg_match('/^' . static::$PLUS_CHARS_PATTERN . '/' . static::REGEX_FLAGS, $number, $matches, PREG_OFFSET_CAPTURE);
1985 3278
        if ($match > 0) {
1986 338
            $number = mb_substr($number, $matches[0][1] + mb_strlen($matches[0][0]));
1987
            // Can now normalize the rest of the number since we've consumed the "+" sign at the start.
1988 338
            $number = static::normalize($number);
1989 338
            return CountryCodeSource::FROM_NUMBER_WITH_PLUS_SIGN;
1990
        }
1991
        // Attempt to parse the first digits as an international prefix.
1992 3219
        $iddPattern = $possibleIddPrefix;
1993 3219
        $number = static::normalize($number);
1994 3219
        return $this->parsePrefixAsIdd($iddPattern, $number)
1995 19
            ? CountryCodeSource::FROM_NUMBER_WITH_IDD
1996 3219
            : CountryCodeSource::FROM_DEFAULT_COUNTRY;
1997
    }
1998
1999
    /**
2000
     * Normalizes a string of characters representing a phone number. This performs
2001
     * the following conversions:
2002
     *   Punctuation is stripped.
2003
     *   For ALPHA/VANITY numbers:
2004
     *   Letters are converted to their numeric representation on a telephone
2005
     *       keypad. The keypad used here is the one defined in ITU Recommendation
2006
     *       E.161. This is only done if there are 3 or more letters in the number,
2007
     *       to lessen the risk that such letters are typos.
2008
     *   For other numbers:
2009
     *    - Wide-ascii digits are converted to normal ASCII (European) digits.
2010
     *    - Arabic-Indic numerals are converted to European numerals.
2011
     *    - Spurious alpha characters are stripped.
2012
     *
2013
     * @param string $number a string of characters representing a phone number.
2014
     * @return string the normalized string version of the phone number.
2015
     */
2016 3282
    public static function normalize(&$number)
2017
    {
2018 3282
        if (static::$ALPHA_PHONE_MAPPINGS === null) {
0 ignored issues
show
introduced by
The condition static::ALPHA_PHONE_MAPPINGS === null is always false.
Loading history...
2019 1
            static::initAlphaPhoneMappings();
2020
        }
2021
2022 3282
        $m = new Matcher(static::VALID_ALPHA_PHONE_PATTERN, $number);
2023 3282
        if ($m->matches()) {
2024 8
            return static::normalizeHelper($number, static::$ALPHA_PHONE_MAPPINGS, true);
2025
        }
2026
2027 3280
        return static::normalizeDigitsOnly($number);
2028
    }
2029
2030
    /**
2031
     * Normalizes a string of characters representing a phone number. This converts wide-ascii and
2032
     * arabic-indic numerals to European numerals, and strips punctuation and alpha characters.
2033
     *
2034
     * @param $number string  a string of characters representing a phone number
2035
     * @return string the normalized string version of the phone number
2036
     */
2037 3301
    public static function normalizeDigitsOnly($number)
2038
    {
2039 3301
        return static::normalizeDigits($number, false /* strip non-digits */);
2040
    }
2041
2042
    /**
2043
     * @param string $number
2044
     * @param bool $keepNonDigits
2045
     * @return string
2046
     */
2047 3334
    public static function normalizeDigits($number, $keepNonDigits)
2048
    {
2049 3334
        $normalizedDigits = '';
2050 3334
        $numberAsArray = preg_split('/(?<!^)(?!$)/u', $number);
2051 3334
        foreach ($numberAsArray as $character) {
2052
            // Check if we are in the unicode number range
2053 3334
            if (array_key_exists($character, static::$numericCharacters)) {
2054 6
                $normalizedDigits .= static::$numericCharacters[$character];
2055 3332
            } elseif (is_numeric($character)) {
2056 3331
                $normalizedDigits .= $character;
2057 169
            } elseif ($keepNonDigits) {
2058 50
                $normalizedDigits .= $character;
2059
            }
2060
        }
2061 3334
        return $normalizedDigits;
2062
    }
2063
2064
    /**
2065
     * Strips the IDD from the start of the number if present. Helper function used by
2066
     * maybeStripInternationalPrefixAndNormalize.
2067
     * @param string $iddPattern
2068
     * @param string $number
2069
     * @return bool
2070
     */
2071 3219
    protected function parsePrefixAsIdd($iddPattern, &$number)
2072
    {
2073 3219
        $m = new Matcher($iddPattern, $number);
2074 3219
        if ($m->lookingAt()) {
2075 22
            $matchEnd = $m->end();
2076
            // Only strip this if the first digit after the match is not a 0, since country calling codes
2077
            // cannot begin with 0.
2078 22
            $digitMatcher = new Matcher(static::$CAPTURING_DIGIT_PATTERN, substr($number, $matchEnd));
2079 22
            if ($digitMatcher->find()) {
2080 22
                $normalizedGroup = static::normalizeDigitsOnly($digitMatcher->group(1));
2081 22
                if ($normalizedGroup == '0') {
2082 7
                    return false;
2083
                }
2084
            }
2085 19
            $number = substr($number, $matchEnd);
2086 19
            return true;
2087
        }
2088 3215
        return false;
2089
    }
2090
2091
    /**
2092
     * Extracts country calling code from fullNumber, returns it and places the remaining number in  nationalNumber.
2093
     * It assumes that the leading plus sign or IDD has already been removed.
2094
     * Returns 0 if fullNumber doesn't start with a valid country calling code, and leaves nationalNumber unmodified.
2095
     * @param string $fullNumber
2096
     * @param string $nationalNumber
2097
     * @return int
2098
     * @internal
2099
     */
2100 357
    public function extractCountryCode($fullNumber, &$nationalNumber)
2101
    {
2102 357
        if ((mb_strlen($fullNumber) == 0) || ($fullNumber[0] == '0')) {
2103
            // Country codes do not begin with a '0'.
2104 2
            return 0;
2105
        }
2106 357
        $numberLength = mb_strlen($fullNumber);
2107 357
        for ($i = 1; $i <= static::MAX_LENGTH_COUNTRY_CODE && $i <= $numberLength; $i++) {
2108 357
            $potentialCountryCode = (int)substr($fullNumber, 0, $i);
2109 357
            if (isset($this->countryCallingCodeToRegionCodeMap[$potentialCountryCode])) {
2110 357
                $nationalNumber .= substr($fullNumber, $i);
2111 357
                return $potentialCountryCode;
2112
            }
2113
        }
2114 11
        return 0;
2115
    }
2116
2117
    /**
2118
     * Strips any national prefix (such as 0, 1) present in the number provided.
2119
     *
2120
     * @param string $number the normalized telephone number that we wish to strip any national
2121
     *     dialing prefix from
2122
     * @param PhoneMetadata $metadata the metadata for the region that we think this number is from
2123
     * @param string $carrierCode a place to insert the carrier code if one is extracted
2124
     * @return bool true if a national prefix or carrier code (or both) could be extracted.
2125
     */
2126 3277
    public function maybeStripNationalPrefixAndCarrierCode(&$number, PhoneMetadata $metadata, &$carrierCode)
2127
    {
2128 3277
        $numberLength = mb_strlen($number);
2129 3277
        $possibleNationalPrefix = $metadata->getNationalPrefixForParsing();
2130 3277
        if ($numberLength == 0 || $possibleNationalPrefix === null || mb_strlen($possibleNationalPrefix) == 0) {
2131
            // Early return for numbers of zero length.
2132 1095
            return false;
2133
        }
2134
2135
        // Attempt to parse the first digits as a national prefix.
2136 2192
        $prefixMatcher = new Matcher($possibleNationalPrefix, $number);
2137 2192
        if ($prefixMatcher->lookingAt()) {
2138 171
            $generalDesc = $metadata->getGeneralDesc();
2139
            // Check if the original number is viable.
2140 171
            $isViableOriginalNumber = $this->matcherAPI->matchNationalNumber($number, $generalDesc, false);
2141
            // $prefixMatcher->group($numOfGroups) === null implies nothing was captured by the capturing
2142
            // groups in $possibleNationalPrefix; therefore, no transformation is necessary, and we just
2143
            // remove the national prefix
2144 171
            $numOfGroups = $prefixMatcher->groupCount();
2145 171
            $transformRule = $metadata->getNationalPrefixTransformRule();
2146 171
            if ($transformRule === null
2147 47
                || mb_strlen($transformRule) == 0
2148 171
                || $prefixMatcher->group($numOfGroups - 1) === null
2149
            ) {
2150
                // If the original number was viable, and the resultant number is not, we return.
2151 169
                if ($isViableOriginalNumber &&
2152 67
                    !$this->matcherAPI->matchNationalNumber(
2153 67
                        substr($number, $prefixMatcher->end()),
2154
                        $generalDesc,
2155 169
                        false
2156
                    )) {
2157 18
                    return false;
2158
                }
2159 155
                if ($carrierCode !== null && $numOfGroups > 0 && $prefixMatcher->group($numOfGroups) !== null) {
2160 2
                    $carrierCode .= $prefixMatcher->group(1);
2161
                }
2162
2163 155
                $number = substr($number, $prefixMatcher->end());
2164 155
                return true;
2165
            }
2166
2167
            // Check that the resultant number is still viable. If not, return. Check this by copying
2168
            // the string and making the transformation on the copy first.
2169 8
            $transformedNumber = $number;
2170 8
            $transformedNumber = substr_replace(
2171 8
                $transformedNumber,
2172 8
                $prefixMatcher->replaceFirst($transformRule),
2173 8
                0,
2174
                $numberLength
2175
            );
2176 8
            if ($isViableOriginalNumber
2177 8
                && !$this->matcherAPI->matchNationalNumber($transformedNumber, $generalDesc, false)) {
2178
                return false;
2179
            }
2180 8
            if ($carrierCode !== null && $numOfGroups > 1) {
2181
                $carrierCode .= $prefixMatcher->group(1);
2182
            }
2183 8
            $number = substr_replace($number, $transformedNumber, 0, mb_strlen($number));
2184 8
            return true;
2185
        }
2186 2076
        return false;
2187
    }
2188
2189
    /**
2190
     * Convenience wrapper around isPossibleNumberForTypeWithReason. Instead of returning the reason
2191
     * reason for failure, this method returns true if the number is either a possible fully-qualified
2192
     * number (containing the area code and country code), or if the number could be a possible local
2193
     * number (with a country code, but missing an area code). Local numbers are considered possible
2194
     * if they could be possibly dialled in this format: if the area code is needed for a call to
2195
     * connect, the number is not considered possible without it.
2196
     *
2197
     * @param PhoneNumber $number The number that needs to be checked
2198
     * @param int $type PhoneNumberType The type we are interested in
2199
     * @return bool true if the number is possible for this particular type
2200
     */
2201 4
    public function isPossibleNumberForType(PhoneNumber $number, $type)
2202
    {
2203 4
        $result = $this->isPossibleNumberForTypeWithReason($number, $type);
2204 4
        return $result === ValidationResult::IS_POSSIBLE
2205 4
            || $result === ValidationResult::IS_POSSIBLE_LOCAL_ONLY;
2206
    }
2207
2208
    /**
2209
     * Helper method to check a number against possible lengths for this number type, and determine
2210
     * whether it matches, or is too short or too long.
2211
     *
2212
     * @param string $number
2213
     * @param PhoneMetadata $metadata
2214
     * @param int $type PhoneNumberType
2215
     * @return int ValidationResult
2216
     */
2217 3288
    protected function testNumberLength($number, PhoneMetadata $metadata, $type = PhoneNumberType::UNKNOWN)
2218
    {
2219 3288
        $descForType = $this->getNumberDescByType($metadata, $type);
2220
        // There should always be "possibleLengths" set for every element. This is declared in the XML
2221
        // schema which is verified by PhoneNumberMetadataSchemaTest.
2222
        // For size efficiency, where a sub-description (e.g. fixed-line) has the same possibleLengths
2223
        // as the parent, this is missing, so we fall back to the general desc (where no numbers of the
2224
        // type exist at all, there is one possible length (-1) which is guaranteed not to match the
2225
        // length of any real phone number).
2226 3288
        $possibleLengths = (count($descForType->getPossibleLength()) === 0)
2227 3288
            ? $metadata->getGeneralDesc()->getPossibleLength() : $descForType->getPossibleLength();
2228
2229 3288
        $localLengths = $descForType->getPossibleLengthLocalOnly();
2230
2231 3288
        if ($type === PhoneNumberType::FIXED_LINE_OR_MOBILE) {
2232 3
            if (!static::descHasPossibleNumberData($this->getNumberDescByType($metadata, PhoneNumberType::FIXED_LINE))) {
2233
                // The rate case has been encountered where no fixedLine data is available (true for some
2234
                // non-geographical entities), so we just check mobile.
2235 2
                return $this->testNumberLength($number, $metadata, PhoneNumberType::MOBILE);
2236
            }
2237
2238 3
            $mobileDesc = $this->getNumberDescByType($metadata, PhoneNumberType::MOBILE);
2239 3
            if (static::descHasPossibleNumberData($mobileDesc)) {
2240
                // Note that when adding the possible lengths from mobile, we have to again check they
2241
                // aren't empty since if they are this indicates they are the same as the general desc and
2242
                // should be obtained from there.
2243 1
                $possibleLengths = array_merge(
2244 1
                    $possibleLengths,
2245 1
                    (count($mobileDesc->getPossibleLength()) === 0)
2246 1
                        ? $metadata->getGeneralDesc()->getPossibleLength() : $mobileDesc->getPossibleLength()
2247
                );
2248
2249
                // The current list is sorted; we need to merge in the new list and re-sort (duplicates
2250
                // are okay). Sorting isn't so expensive because the lists are very small.
2251 1
                sort($possibleLengths);
2252
2253 1
                if (count($localLengths) === 0) {
2254 1
                    $localLengths = $mobileDesc->getPossibleLengthLocalOnly();
2255
                } else {
2256
                    $localLengths = array_merge($localLengths, $mobileDesc->getPossibleLengthLocalOnly());
2257
                    sort($localLengths);
2258
                }
2259
            }
2260
        }
2261
2262
2263
        // If the type is not supported at all (indicated by the possible lengths containing -1 at this
2264
        // point) we return invalid length.
2265
2266 3288
        if ($possibleLengths[0] === -1) {
2267 2
            return ValidationResult::INVALID_LENGTH;
2268
        }
2269
2270 3288
        $actualLength = mb_strlen($number);
2271
2272
        // This is safe because there is never an overlap between the possible lengths and the local-only
2273
        // lengths; this is checked at build time.
2274
2275 3288
        if (in_array($actualLength, $localLengths)) {
2276 75
            return ValidationResult::IS_POSSIBLE_LOCAL_ONLY;
2277
        }
2278
2279 3241
        $minimumLength = reset($possibleLengths);
2280 3241
        if ($minimumLength == $actualLength) {
2281 1338
            return ValidationResult::IS_POSSIBLE;
2282
        }
2283
2284 1961
        if ($minimumLength > $actualLength) {
2285 1148
            return ValidationResult::TOO_SHORT;
2286 838
        } elseif (isset($possibleLengths[count($possibleLengths) - 1]) && $possibleLengths[count($possibleLengths) - 1] < $actualLength) {
2287 31
            return ValidationResult::TOO_LONG;
2288
        }
2289
2290
        // We skip the first element; we've already checked it.
2291 824
        array_shift($possibleLengths);
2292 824
        return in_array($actualLength, $possibleLengths) ? ValidationResult::IS_POSSIBLE : ValidationResult::INVALID_LENGTH;
2293
    }
2294
2295
    /**
2296
     * Returns a list with the region codes that match the specific country calling code. For
2297
     * non-geographical country calling codes, the region code 001 is returned. Also, in the case
2298
     * of no region code being found, an empty list is returned.
2299
     * @param int $countryCallingCode
2300
     * @return array
2301
     */
2302 9
    public function getRegionCodesForCountryCode($countryCallingCode)
2303
    {
2304 9
        $regionCodes = isset($this->countryCallingCodeToRegionCodeMap[$countryCallingCode]) ? $this->countryCallingCodeToRegionCodeMap[$countryCallingCode] : null;
2305 9
        return $regionCodes === null ? array() : $regionCodes;
2306
    }
2307
2308
    /**
2309
     * Returns the country calling code for a specific region. For example, this would be 1 for the
2310
     * United States, and 64 for New Zealand. Assumes the region is already valid.
2311
     *
2312
     * @param string $regionCode the region that we want to get the country calling code for
2313
     * @return int the country calling code for the region denoted by regionCode
2314
     */
2315 37
    public function getCountryCodeForRegion($regionCode)
2316
    {
2317 37
        if (!$this->isValidRegionCode($regionCode)) {
2318 4
            return 0;
2319
        }
2320 37
        return $this->getCountryCodeForValidRegion($regionCode);
2321
    }
2322
2323
    /**
2324
     * Returns the country calling code for a specific region. For example, this would be 1 for the
2325
     * United States, and 64 for New Zealand. Assumes the region is already valid.
2326
     *
2327
     * @param string $regionCode the region that we want to get the country calling code for
2328
     * @return int the country calling code for the region denoted by regionCode
2329
     * @throws \InvalidArgumentException if the region is invalid
2330
     */
2331 2001
    protected function getCountryCodeForValidRegion($regionCode)
2332
    {
2333 2001
        $metadata = $this->getMetadataForRegion($regionCode);
2334 2001
        if ($metadata === null) {
2335
            throw new \InvalidArgumentException('Invalid region code: ' . $regionCode);
2336
        }
2337 2001
        return $metadata->getCountryCode();
2338
    }
2339
2340
    /**
2341
     * Returns a number formatted in such a way that it can be dialed from a mobile phone in a
2342
     * specific region. If the number cannot be reached from the region (e.g. some countries block
2343
     * toll-free numbers from being called outside of the country), the method returns an empty
2344
     * string.
2345
     *
2346
     * @param PhoneNumber $number the phone number to be formatted
2347
     * @param string $regionCallingFrom the region where the call is being placed
2348
     * @param boolean $withFormatting whether the number should be returned with formatting symbols, such as
2349
     *     spaces and dashes.
2350
     * @return string the formatted phone number
2351
     */
2352 1
    public function formatNumberForMobileDialing(PhoneNumber $number, $regionCallingFrom, $withFormatting)
2353
    {
2354 1
        $countryCallingCode = $number->getCountryCode();
2355 1
        if (!$this->hasValidCountryCallingCode($countryCallingCode)) {
2356
            return $number->hasRawInput() ? $number->getRawInput() : '';
2357
        }
2358
2359 1
        $formattedNumber = '';
2360
        // Clear the extension, as that part cannot normally be dialed together with the main number.
2361 1
        $numberNoExt = new PhoneNumber();
2362 1
        $numberNoExt->mergeFrom($number)->clearExtension();
2363 1
        $regionCode = $this->getRegionCodeForCountryCode($countryCallingCode);
2364 1
        $numberType = $this->getNumberType($numberNoExt);
2365 1
        $isValidNumber = ($numberType !== PhoneNumberType::UNKNOWN);
2366 1
        if ($regionCallingFrom == $regionCode) {
2367 1
            $isFixedLineOrMobile = ($numberType == PhoneNumberType::FIXED_LINE) || ($numberType == PhoneNumberType::MOBILE) || ($numberType == PhoneNumberType::FIXED_LINE_OR_MOBILE);
2368
            // Carrier codes may be needed in some countries. We handle this here.
2369 1
            if ($regionCode == 'CO' && $numberType == PhoneNumberType::FIXED_LINE) {
2370
                $formattedNumber = $this->formatNationalNumberWithCarrierCode(
2371
                    $numberNoExt,
2372
                    static::COLOMBIA_MOBILE_TO_FIXED_LINE_PREFIX
2373
                );
2374 1
            } elseif ($regionCode == 'BR' && $isFixedLineOrMobile) {
2375
                // Historically, we set this to an empty string when parsing with raw input if none was
2376
                // found in the input string. However, this doesn't result in a number we can dial. For this
2377
                // reason, we treat the empty string the same as if it isn't set at all.
2378
                $formattedNumber = mb_strlen($numberNoExt->getPreferredDomesticCarrierCode()) > 0
2379
                    ? $this->formatNationalNumberWithPreferredCarrierCode($numberNoExt, '')
2380
                    // Brazilian fixed line and mobile numbers need to be dialed with a carrier code when
2381
                    // called within Brazil. Without that, most of the carriers won't connect the call.
2382
                    // Because of that, we return an empty string here.
2383
                    : '';
2384 1
            } elseif ($countryCallingCode === static::NANPA_COUNTRY_CODE) {
2385
                // For NANPA countries, we output international format for numbers that can be dialed
2386
                // internationally, since that always works, except for numbers which might potentially be
2387
                // short numbers, which are always dialled in national format.
2388 1
                $regionMetadata = $this->getMetadataForRegion($regionCallingFrom);
2389 1
                if ($this->canBeInternationallyDialled($numberNoExt)
2390 1
                    && $this->testNumberLength($this->getNationalSignificantNumber($numberNoExt), $regionMetadata)
0 ignored issues
show
Bug introduced by
It seems like $regionMetadata can also be of type null; however, parameter $metadata of libphonenumber\PhoneNumberUtil::testNumberLength() does only seem to accept libphonenumber\PhoneMetadata, maybe add an additional type check? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

2390
                    && $this->testNumberLength($this->getNationalSignificantNumber($numberNoExt), /** @scrutinizer ignore-type */ $regionMetadata)
Loading history...
2391 1
                    !== ValidationResult::TOO_SHORT
2392
                ) {
2393 1
                    $formattedNumber = $this->format($numberNoExt, PhoneNumberFormat::INTERNATIONAL);
2394
                } else {
2395 1
                    $formattedNumber = $this->format($numberNoExt, PhoneNumberFormat::NATIONAL);
2396
                }
2397
            } elseif ((
0 ignored issues
show
introduced by
Consider adding parentheses for clarity. Current Interpretation: ($regionCode == static::...lyDialled($numberNoExt), Probably Intended Meaning: $regionCode == static::R...yDialled($numberNoExt))
Loading history...
2398 1
                $regionCode == static::REGION_CODE_FOR_NON_GEO_ENTITY ||
2399
                    // MX fixed line and mobile numbers should always be formatted in international format,
2400
                    // even when dialed within MX. For national format to work, a carrier code needs to be
2401
                    // used, and the correct carrier code depends on if the caller and callee are from the
2402
                    // same local area. It is trickier to get that to work correctly than using
2403
                    // international format, which is tested to work fine on all carriers.
2404
                    // CL fixed line numbers need the national prefix when dialing in the national format,
2405
                    // but don't have it when used for display. The reverse is true for mobile numbers.
2406
                    // As a result, we output them in the international format to make it work.
2407
                    (
2408 1
                        ($regionCode === 'MX' || $regionCode === 'CL' || $regionCode === 'UZ')
2409 1
                        && $isFixedLineOrMobile
2410
                    )
2411 1
            ) && $this->canBeInternationallyDialled($numberNoExt)
2412
            ) {
2413 1
                $formattedNumber = $this->format($numberNoExt, PhoneNumberFormat::INTERNATIONAL);
2414
            } else {
2415 1
                $formattedNumber = $this->format($numberNoExt, PhoneNumberFormat::NATIONAL);
2416
            }
2417 1
        } elseif ($isValidNumber && $this->canBeInternationallyDialled($numberNoExt)) {
2418
            // We assume that short numbers are not diallable from outside their region, so if a number
2419
            // is not a valid regular length phone number, we treat it as if it cannot be internationally
2420
            // dialled.
2421 1
            return $withFormatting ?
2422 1
                $this->format($numberNoExt, PhoneNumberFormat::INTERNATIONAL) :
2423 1
                $this->format($numberNoExt, PhoneNumberFormat::E164);
2424
        }
2425 1
        return $withFormatting ? $formattedNumber : static::normalizeDiallableCharsOnly($formattedNumber);
2426
    }
2427
2428
    /**
2429
     * Formats a phone number in national format for dialing using the carrier as specified in the
2430
     * {@code carrierCode}. The {@code carrierCode} will always be used regardless of whether the
2431
     * phone number already has a preferred domestic carrier code stored. If {@code carrierCode}
2432
     * contains an empty string, returns the number in national format without any carrier code.
2433
     *
2434
     * @param PhoneNumber $number the phone number to be formatted
2435
     * @param string $carrierCode the carrier selection code to be used
2436
     * @return string the formatted phone number in national format for dialing using the carrier as
2437
     * specified in the {@code carrierCode}
2438
     */
2439 2
    public function formatNationalNumberWithCarrierCode(PhoneNumber $number, $carrierCode)
2440
    {
2441 2
        $countryCallingCode = $number->getCountryCode();
2442 2
        $nationalSignificantNumber = $this->getNationalSignificantNumber($number);
2443 2
        if (!$this->hasValidCountryCallingCode($countryCallingCode)) {
2444 1
            return $nationalSignificantNumber;
2445
        }
2446
2447
        // Note getRegionCodeForCountryCode() is used because formatting information for regions which
2448
        // share a country calling code is contained by only one region for performance reasons. For
2449
        // example, for NANPA regions it will be contained in the metadata for US.
2450 2
        $regionCode = $this->getRegionCodeForCountryCode($countryCallingCode);
2451
        // Metadata cannot be null because the country calling code is valid.
2452 2
        $metadata = $this->getMetadataForRegionOrCallingCode($countryCallingCode, $regionCode);
2453
2454 2
        $formattedNumber = $this->formatNsn(
2455 2
            $nationalSignificantNumber,
2456
            $metadata,
2457 2
            PhoneNumberFormat::NATIONAL,
2458
            $carrierCode
2459
        );
2460 2
        $this->maybeAppendFormattedExtension($number, $metadata, PhoneNumberFormat::NATIONAL, $formattedNumber);
2461 2
        $this->prefixNumberWithCountryCallingCode(
2462 2
            $countryCallingCode,
2463 2
            PhoneNumberFormat::NATIONAL,
2464
            $formattedNumber
2465
        );
2466 2
        return $formattedNumber;
2467
    }
2468
2469
    /**
2470
     * Formats a phone number in national format for dialing using the carrier as specified in the
2471
     * preferredDomesticCarrierCode field of the PhoneNumber object passed in. If that is missing,
2472
     * use the {@code fallbackCarrierCode} passed in instead. If there is no
2473
     * {@code preferredDomesticCarrierCode}, and the {@code fallbackCarrierCode} contains an empty
2474
     * string, return the number in national format without any carrier code.
2475
     *
2476
     * <p>Use {@link #formatNationalNumberWithCarrierCode} instead if the carrier code passed in
2477
     * should take precedence over the number's {@code preferredDomesticCarrierCode} when formatting.
2478
     *
2479
     * @param PhoneNumber $number the phone number to be formatted
2480
     * @param string $fallbackCarrierCode the carrier selection code to be used, if none is found in the
2481
     *     phone number itself
2482
     * @return string the formatted phone number in national format for dialing using the number's
2483
     *     {@code preferredDomesticCarrierCode}, or the {@code fallbackCarrierCode} passed in if
2484
     *     none is found
2485
     */
2486 1
    public function formatNationalNumberWithPreferredCarrierCode(PhoneNumber $number, $fallbackCarrierCode)
2487
    {
2488 1
        return $this->formatNationalNumberWithCarrierCode(
2489 1
            $number,
2490
            // Historically, we set this to an empty string when parsing with raw input if none was
2491
            // found in the input string. However, this doesn't result in a number we can dial. For this
2492
            // reason, we treat the empty string the same as if it isn't set at all.
2493 1
            mb_strlen($number->getPreferredDomesticCarrierCode()) > 0
2494 1
                ? $number->getPreferredDomesticCarrierCode()
2495 1
                : $fallbackCarrierCode
2496
        );
2497
    }
2498
2499
    /**
2500
     * Returns true if the number can be dialled from outside the region, or unknown. If the number
2501
     * can only be dialled from within the region, returns false. Does not check the number is a valid
2502
     * number. Note that, at the moment, this method does not handle short numbers (which are
2503
     * currently all presumed to not be diallable from outside their country).
2504
     *
2505
     * @param PhoneNumber $number the phone-number for which we want to know whether it is diallable from outside the region
2506
     * @return bool
2507
     */
2508 2
    public function canBeInternationallyDialled(PhoneNumber $number)
2509
    {
2510 2
        $metadata = $this->getMetadataForRegion($this->getRegionCodeForNumber($number));
2511 2
        if ($metadata === null) {
2512
            // Note numbers belonging to non-geographical entities (e.g. +800 numbers) are always
2513
            // internationally diallable, and will be caught here.
2514 2
            return true;
2515
        }
2516 2
        $nationalSignificantNumber = $this->getNationalSignificantNumber($number);
2517 2
        return !$this->isNumberMatchingDesc($nationalSignificantNumber, $metadata->getNoInternationalDialling());
2518
    }
2519
2520
    /**
2521
     * Normalizes a string of characters representing a phone number. This strips all characters which
2522
     * are not diallable on a mobile phone keypad (including all non-ASCII digits).
2523
     *
2524
     * @param string $number a string of characters representing a phone number
2525
     * @return string the normalized string version of the phone number
2526
     */
2527 29
    public static function normalizeDiallableCharsOnly($number)
2528
    {
2529 29
        if (count(static::$DIALLABLE_CHAR_MAPPINGS) === 0) {
2530 1
            static::initDiallableCharMappings();
2531
        }
2532
2533 29
        return static::normalizeHelper($number, static::$DIALLABLE_CHAR_MAPPINGS, true /* remove non matches */);
2534
    }
2535
2536
    /**
2537
     * Formats a phone number for out-of-country dialing purposes.
2538
     *
2539
     * Note that in this version, if the number was entered originally using alpha characters and
2540
     * this version of the number is stored in raw_input, this representation of the number will be
2541
     * used rather than the digit representation. Grouping information, as specified by characters
2542
     * such as "-" and " ", will be retained.
2543
     *
2544
     * <p><b>Caveats:</b></p>
2545
     * <ul>
2546
     *  <li> This will not produce good results if the country calling code is both present in the raw
2547
     *       input _and_ is the start of the national number. This is not a problem in the regions
2548
     *       which typically use alpha numbers.
2549
     *  <li> This will also not produce good results if the raw input has any grouping information
2550
     *       within the first three digits of the national number, and if the function needs to strip
2551
     *       preceding digits/words in the raw input before these digits. Normally people group the
2552
     *       first three digits together so this is not a huge problem - and will be fixed if it
2553
     *       proves to be so.
2554
     * </ul>
2555
     *
2556
     * @param PhoneNumber $number the phone number that needs to be formatted
2557
     * @param String $regionCallingFrom the region where the call is being placed
2558
     * @return String the formatted phone number
2559
     */
2560 1
    public function formatOutOfCountryKeepingAlphaChars(PhoneNumber $number, $regionCallingFrom)
2561
    {
2562 1
        $rawInput = $number->getRawInput();
2563
        // If there is no raw input, then we can't keep alpha characters because there aren't any.
2564
        // In this case, we return formatOutOfCountryCallingNumber.
2565 1
        if (mb_strlen($rawInput) == 0) {
2566 1
            return $this->formatOutOfCountryCallingNumber($number, $regionCallingFrom);
2567
        }
2568 1
        $countryCode = $number->getCountryCode();
2569 1
        if (!$this->hasValidCountryCallingCode($countryCode)) {
2570 1
            return $rawInput;
2571
        }
2572
        // Strip any prefix such as country calling code, IDD, that was present. We do this by comparing
2573
        // the number in raw_input with the parsed number.
2574
        // To do this, first we normalize punctuation. We retain number grouping symbols such as " "
2575
        // only.
2576 1
        $rawInput = self::normalizeHelper($rawInput, static::$ALL_PLUS_NUMBER_GROUPING_SYMBOLS, true);
2577
        // Now we trim everything before the first three digits in the parsed number. We choose three
2578
        // because all valid alpha numbers have 3 digits at the start - if it does not, then we don't
2579
        // trim anything at all. Similarly, if the national number was less than three digits, we don't
2580
        // trim anything at all.
2581 1
        $nationalNumber = $this->getNationalSignificantNumber($number);
2582 1
        if (mb_strlen($nationalNumber) > 3) {
2583 1
            $firstNationalNumberDigit = strpos($rawInput, substr($nationalNumber, 0, 3));
2584 1
            if ($firstNationalNumberDigit !== false) {
2585 1
                $rawInput = substr($rawInput, $firstNationalNumberDigit);
2586
            }
2587
        }
2588 1
        $metadataForRegionCallingFrom = $this->getMetadataForRegion($regionCallingFrom);
2589 1
        if ($countryCode == static::NANPA_COUNTRY_CODE) {
2590 1
            if ($this->isNANPACountry($regionCallingFrom)) {
2591 1
                return $countryCode . ' ' . $rawInput;
2592
            }
2593 1
        } elseif ($metadataForRegionCallingFrom !== null &&
2594 1
            $countryCode == $this->getCountryCodeForValidRegion($regionCallingFrom)
2595
        ) {
2596
            $formattingPattern =
2597 1
                $this->chooseFormattingPatternForNumber(
2598 1
                    $metadataForRegionCallingFrom->numberFormats(),
2599
                    $nationalNumber
2600
                );
2601 1
            if ($formattingPattern === null) {
2602
                // If no pattern above is matched, we format the original input.
2603 1
                return $rawInput;
2604
            }
2605 1
            $newFormat = new NumberFormat();
2606 1
            $newFormat->mergeFrom($formattingPattern);
2607
            // The first group is the first group of digits that the user wrote together.
2608 1
            $newFormat->setPattern("(\\d+)(.*)");
2609
            // Here we just concatenate them back together after the national prefix has been fixed.
2610 1
            $newFormat->setFormat('$1$2');
2611
            // Now we format using this pattern instead of the default pattern, but with the national
2612
            // prefix prefixed if necessary.
2613
            // This will not work in the cases where the pattern (and not the leading digits) decide
2614
            // whether a national prefix needs to be used, since we have overridden the pattern to match
2615
            // anything, but that is not the case in the metadata to date.
2616 1
            return $this->formatNsnUsingPattern($rawInput, $newFormat, PhoneNumberFormat::NATIONAL);
2617
        }
2618 1
        $internationalPrefixForFormatting = '';
2619
        // If an unsupported region-calling-from is entered, or a country with multiple international
2620
        // prefixes, the international format of the number is returned, unless there is a preferred
2621
        // international prefix.
2622 1
        if ($metadataForRegionCallingFrom !== null) {
2623 1
            $internationalPrefix = $metadataForRegionCallingFrom->getInternationalPrefix();
2624 1
            $uniqueInternationalPrefixMatcher = new Matcher(static::SINGLE_INTERNATIONAL_PREFIX, $internationalPrefix);
2625
            $internationalPrefixForFormatting =
2626 1
                $uniqueInternationalPrefixMatcher->matches()
2627 1
                    ? $internationalPrefix
2628 1
                    : $metadataForRegionCallingFrom->getPreferredInternationalPrefix();
2629
        }
2630 1
        $formattedNumber = $rawInput;
2631 1
        $regionCode = $this->getRegionCodeForCountryCode($countryCode);
2632
        // Metadata cannot be null because the country calling code is valid.
2633 1
        $metadataForRegion = $this->getMetadataForRegionOrCallingCode($countryCode, $regionCode);
2634 1
        $this->maybeAppendFormattedExtension(
2635 1
            $number,
2636
            $metadataForRegion,
2637 1
            PhoneNumberFormat::INTERNATIONAL,
2638
            $formattedNumber
2639
        );
2640 1
        if (mb_strlen($internationalPrefixForFormatting) > 0) {
2641 1
            $formattedNumber = $internationalPrefixForFormatting . ' ' . $countryCode . ' ' . $formattedNumber;
2642
        } else {
2643
            // Invalid region entered as country-calling-from (so no metadata was found for it) or the
2644
            // region chosen has multiple international dialling prefixes.
2645 1
            $this->prefixNumberWithCountryCallingCode(
2646 1
                $countryCode,
2647 1
                PhoneNumberFormat::INTERNATIONAL,
2648
                $formattedNumber
2649
            );
2650
        }
2651 1
        return $formattedNumber;
2652
    }
2653
2654
    /**
2655
     * Formats a phone number for out-of-country dialing purposes. If no regionCallingFrom is
2656
     * supplied, we format the number in its INTERNATIONAL format. If the country calling code is the
2657
     * same as that of the region where the number is from, then NATIONAL formatting will be applied.
2658
     *
2659
     * <p>If the number itself has a country calling code of zero or an otherwise invalid country
2660
     * calling code, then we return the number with no formatting applied.
2661
     *
2662
     * <p>Note this function takes care of the case for calling inside of NANPA and between Russia and
2663
     * Kazakhstan (who share the same country calling code). In those cases, no international prefix
2664
     * is used. For regions which have multiple international prefixes, the number in its
2665
     * INTERNATIONAL format will be returned instead.
2666
     *
2667
     * @param PhoneNumber $number the phone number to be formatted
2668
     * @param string $regionCallingFrom the region where the call is being placed
2669
     * @return string  the formatted phone number
2670
     */
2671 8
    public function formatOutOfCountryCallingNumber(PhoneNumber $number, $regionCallingFrom)
2672
    {
2673 8
        if (!$this->isValidRegionCode($regionCallingFrom)) {
2674 1
            return $this->format($number, PhoneNumberFormat::INTERNATIONAL);
2675
        }
2676 7
        $countryCallingCode = $number->getCountryCode();
2677 7
        $nationalSignificantNumber = $this->getNationalSignificantNumber($number);
2678 7
        if (!$this->hasValidCountryCallingCode($countryCallingCode)) {
2679
            return $nationalSignificantNumber;
2680
        }
2681 7
        if ($countryCallingCode == static::NANPA_COUNTRY_CODE) {
2682 4
            if ($this->isNANPACountry($regionCallingFrom)) {
2683
                // For NANPA regions, return the national format for these regions but prefix it with the
2684
                // country calling code.
2685 4
                return $countryCallingCode . ' ' . $this->format($number, PhoneNumberFormat::NATIONAL);
2686
            }
2687 6
        } elseif ($countryCallingCode == $this->getCountryCodeForValidRegion($regionCallingFrom)) {
2688
            // If regions share a country calling code, the country calling code need not be dialled.
2689
            // This also applies when dialling within a region, so this if clause covers both these cases.
2690
            // Technically this is the case for dialling from La Reunion to other overseas departments of
2691
            // France (French Guiana, Martinique, Guadeloupe), but not vice versa - so we don't cover this
2692
            // edge case for now and for those cases return the version including country calling code.
2693
            // Details here: http://www.petitfute.com/voyage/225-info-pratiques-reunion
2694 2
            return $this->format($number, PhoneNumberFormat::NATIONAL);
2695
        }
2696
        // Metadata cannot be null because we checked 'isValidRegionCode()' above.
2697 7
        $metadataForRegionCallingFrom = $this->getMetadataForRegion($regionCallingFrom);
2698
2699 7
        $internationalPrefix = $metadataForRegionCallingFrom->getInternationalPrefix();
2700
2701
        // For regions that have multiple international prefixes, the international format of the
2702
        // number is returned, unless there is a preferred international prefix.
2703 7
        $internationalPrefixForFormatting = '';
2704 7
        $uniqueInternationalPrefixMatcher = new Matcher(static::SINGLE_INTERNATIONAL_PREFIX, $internationalPrefix);
2705
2706 7
        if ($uniqueInternationalPrefixMatcher->matches()) {
2707 6
            $internationalPrefixForFormatting = $internationalPrefix;
2708 3
        } elseif ($metadataForRegionCallingFrom->hasPreferredInternationalPrefix()) {
2709 3
            $internationalPrefixForFormatting = $metadataForRegionCallingFrom->getPreferredInternationalPrefix();
2710
        }
2711
2712 7
        $regionCode = $this->getRegionCodeForCountryCode($countryCallingCode);
2713
        // Metadata cannot be null because the country calling code is valid.
2714 7
        $metadataForRegion = $this->getMetadataForRegionOrCallingCode($countryCallingCode, $regionCode);
2715 7
        $formattedNationalNumber = $this->formatNsn(
2716 7
            $nationalSignificantNumber,
2717
            $metadataForRegion,
2718 7
            PhoneNumberFormat::INTERNATIONAL
2719
        );
2720 7
        $formattedNumber = $formattedNationalNumber;
2721 7
        $this->maybeAppendFormattedExtension(
2722 7
            $number,
2723
            $metadataForRegion,
2724 7
            PhoneNumberFormat::INTERNATIONAL,
2725
            $formattedNumber
2726
        );
2727 7
        if (mb_strlen($internationalPrefixForFormatting) > 0) {
2728 7
            $formattedNumber = $internationalPrefixForFormatting . ' ' . $countryCallingCode . ' ' . $formattedNumber;
2729
        } else {
2730 1
            $this->prefixNumberWithCountryCallingCode(
2731 1
                $countryCallingCode,
2732 1
                PhoneNumberFormat::INTERNATIONAL,
2733
                $formattedNumber
2734
            );
2735
        }
2736 7
        return $formattedNumber;
2737
    }
2738
2739
    /**
2740
     * Checks if this is a region under the North American Numbering Plan Administration (NANPA).
2741
     * @param string $regionCode
2742
     * @return boolean true if regionCode is one of the regions under NANPA
2743
     */
2744 5
    public function isNANPACountry($regionCode)
2745
    {
2746 5
        return in_array($regionCode, $this->nanpaRegions);
2747
    }
2748
2749
    /**
2750
     * Formats a phone number using the original phone number format that the number is parsed from.
2751
     * The original format is embedded in the country_code_source field of the PhoneNumber object
2752
     * passed in. If such information is missing, the number will be formatted into the NATIONAL
2753
     * format by default. When we don't have a formatting pattern for the number, the method returns
2754
     * the raw inptu when it is available.
2755
     *
2756
     * Note this method guarantees no digit will be inserted, removed or modified as a result of
2757
     * formatting.
2758
     *
2759
     * @param PhoneNumber $number the phone number that needs to be formatted in its original number format
2760
     * @param string $regionCallingFrom the region whose IDD needs to be prefixed if the original number
2761
     *     has one
2762
     * @return string the formatted phone number in its original number format
2763
     */
2764 1
    public function formatInOriginalFormat(PhoneNumber $number, $regionCallingFrom)
2765
    {
2766 1
        if ($number->hasRawInput() && !$this->hasFormattingPatternForNumber($number)) {
2767
            // We check if we have the formatting pattern because without that, we might format the number
2768
            // as a group without national prefix.
2769 1
            return $number->getRawInput();
2770
        }
2771 1
        if (!$number->hasCountryCodeSource()) {
2772 1
            return $this->format($number, PhoneNumberFormat::NATIONAL);
2773
        }
2774 1
        switch ($number->getCountryCodeSource()) {
2775 1
            case CountryCodeSource::FROM_NUMBER_WITH_PLUS_SIGN:
2776 1
                $formattedNumber = $this->format($number, PhoneNumberFormat::INTERNATIONAL);
2777 1
                break;
2778 1
            case CountryCodeSource::FROM_NUMBER_WITH_IDD:
2779 1
                $formattedNumber = $this->formatOutOfCountryCallingNumber($number, $regionCallingFrom);
2780 1
                break;
2781 1
            case CountryCodeSource::FROM_NUMBER_WITHOUT_PLUS_SIGN:
2782 1
                $formattedNumber = substr($this->format($number, PhoneNumberFormat::INTERNATIONAL), 1);
2783 1
                break;
2784 1
            case CountryCodeSource::FROM_DEFAULT_COUNTRY:
2785
                // Fall-through to default case.
2786
            default:
2787
2788 1
                $regionCode = $this->getRegionCodeForCountryCode($number->getCountryCode());
2789
                // We strip non-digits from the NDD here, and from the raw input later, so that we can
2790
                // compare them easily.
2791 1
                $nationalPrefix = $this->getNddPrefixForRegion($regionCode, true /* strip non-digits */);
2792 1
                $nationalFormat = $this->format($number, PhoneNumberFormat::NATIONAL);
2793 1
                if ($nationalPrefix === null || mb_strlen($nationalPrefix) == 0) {
2794
                    // If the region doesn't have a national prefix at all, we can safely return the national
2795
                    // format without worrying about a national prefix being added.
2796 1
                    $formattedNumber = $nationalFormat;
2797 1
                    break;
2798
                }
2799
                // Otherwise, we check if the original number was entered with a national prefix.
2800 1
                if ($this->rawInputContainsNationalPrefix(
2801 1
                    $number->getRawInput(),
2802
                    $nationalPrefix,
2803
                    $regionCode
2804
                )
2805
                ) {
2806
                    // If so, we can safely return the national format.
2807 1
                    $formattedNumber = $nationalFormat;
2808 1
                    break;
2809
                }
2810
                // Metadata cannot be null here because getNddPrefixForRegion() (above) returns null if
2811
                // there is no metadata for the region.
2812 1
                $metadata = $this->getMetadataForRegion($regionCode);
2813 1
                $nationalNumber = $this->getNationalSignificantNumber($number);
2814 1
                $formatRule = $this->chooseFormattingPatternForNumber($metadata->numberFormats(), $nationalNumber);
2815
                // The format rule could still be null here if the national number was 0 and there was no
2816
                // raw input (this should not be possible for numbers generated by the phonenumber library
2817
                // as they would also not have a country calling code and we would have exited earlier).
2818 1
                if ($formatRule === null) {
2819
                    $formattedNumber = $nationalFormat;
2820
                    break;
2821
                }
2822
                // When the format we apply to this number doesn't contain national prefix, we can just
2823
                // return the national format.
2824
                // TODO: Refactor the code below with the code in isNationalPrefixPresentIfRequired.
2825 1
                $candidateNationalPrefixRule = $formatRule->getNationalPrefixFormattingRule();
2826
                // We assume that the first-group symbol will never be _before_ the national prefix.
2827 1
                $indexOfFirstGroup = strpos($candidateNationalPrefixRule, '$1');
2828 1
                if ($indexOfFirstGroup <= 0) {
2829 1
                    $formattedNumber = $nationalFormat;
2830 1
                    break;
2831
                }
2832 1
                $candidateNationalPrefixRule = substr($candidateNationalPrefixRule, 0, $indexOfFirstGroup);
2833 1
                $candidateNationalPrefixRule = static::normalizeDigitsOnly($candidateNationalPrefixRule);
2834 1
                if (mb_strlen($candidateNationalPrefixRule) == 0) {
2835
                    // National prefix not used when formatting this number.
2836
                    $formattedNumber = $nationalFormat;
2837
                    break;
2838
                }
2839
                // Otherwise, we need to remove the national prefix from our output.
2840 1
                $numFormatCopy = new NumberFormat();
2841 1
                $numFormatCopy->mergeFrom($formatRule);
2842 1
                $numFormatCopy->clearNationalPrefixFormattingRule();
2843 1
                $numberFormats = array();
2844 1
                $numberFormats[] = $numFormatCopy;
2845 1
                $formattedNumber = $this->formatByPattern($number, PhoneNumberFormat::NATIONAL, $numberFormats);
2846 1
                break;
2847
        }
2848 1
        $rawInput = $number->getRawInput();
2849
        // If no digit is inserted/removed/modified as a result of our formatting, we return the
2850
        // formatted phone number; otherwise we return the raw input the user entered.
2851 1
        if ($formattedNumber !== null && mb_strlen($rawInput) > 0) {
2852 1
            $normalizedFormattedNumber = static::normalizeDiallableCharsOnly($formattedNumber);
2853 1
            $normalizedRawInput = static::normalizeDiallableCharsOnly($rawInput);
2854 1
            if ($normalizedFormattedNumber != $normalizedRawInput) {
2855 1
                $formattedNumber = $rawInput;
2856
            }
2857
        }
2858 1
        return $formattedNumber;
2859
    }
2860
2861
    /**
2862
     * @param PhoneNumber $number
2863
     * @return bool
2864
     */
2865 1
    protected function hasFormattingPatternForNumber(PhoneNumber $number)
2866
    {
2867 1
        $countryCallingCode = $number->getCountryCode();
2868 1
        $phoneNumberRegion = $this->getRegionCodeForCountryCode($countryCallingCode);
2869 1
        $metadata = $this->getMetadataForRegionOrCallingCode($countryCallingCode, $phoneNumberRegion);
2870 1
        if ($metadata === null) {
2871
            return false;
2872
        }
2873 1
        $nationalNumber = $this->getNationalSignificantNumber($number);
2874 1
        $formatRule = $this->chooseFormattingPatternForNumber($metadata->numberFormats(), $nationalNumber);
2875 1
        return $formatRule !== null;
2876
    }
2877
2878
    /**
2879
     * Returns the national dialling prefix for a specific region. For example, this would be 1 for
2880
     * the United States, and 0 for New Zealand. Set stripNonDigits to true to strip symbols like "~"
2881
     * (which indicates a wait for a dialling tone) from the prefix returned. If no national prefix is
2882
     * present, we return null.
2883
     *
2884
     * <p>Warning: Do not use this method for do-your-own formatting - for some regions, the
2885
     * national dialling prefix is used only for certain types of numbers. Use the library's
2886
     * formatting functions to prefix the national prefix when required.
2887
     *
2888
     * @param string $regionCode the region that we want to get the dialling prefix for
2889
     * @param boolean $stripNonDigits true to strip non-digits from the national dialling prefix
2890
     * @return string the dialling prefix for the region denoted by regionCode
2891
     */
2892 28
    public function getNddPrefixForRegion($regionCode, $stripNonDigits)
2893
    {
2894 28
        $metadata = $this->getMetadataForRegion($regionCode);
2895 28
        if ($metadata === null) {
2896 1
            return null;
2897
        }
2898 28
        $nationalPrefix = $metadata->getNationalPrefix();
2899
        // If no national prefix was found, we return null.
2900 28
        if (mb_strlen($nationalPrefix) == 0) {
2901 1
            return null;
2902
        }
2903 28
        if ($stripNonDigits) {
2904
            // Note: if any other non-numeric symbols are ever used in national prefixes, these would have
2905
            // to be removed here as well.
2906 28
            $nationalPrefix = str_replace('~', '', $nationalPrefix);
2907
        }
2908 28
        return $nationalPrefix;
2909
    }
2910
2911
    /**
2912
     * Check if rawInput, which is assumed to be in the national format, has a national prefix. The
2913
     * national prefix is assumed to be in digits-only form.
2914
     * @param string $rawInput
2915
     * @param string $nationalPrefix
2916
     * @param string $regionCode
2917
     * @return bool
2918
     */
2919 1
    protected function rawInputContainsNationalPrefix($rawInput, $nationalPrefix, $regionCode)
2920
    {
2921 1
        $normalizedNationalNumber = static::normalizeDigitsOnly($rawInput);
2922 1
        if (strpos($normalizedNationalNumber, $nationalPrefix) === 0) {
2923
            try {
2924
                // Some Japanese numbers (e.g. 00777123) might be mistaken to contain the national prefix
2925
                // when written without it (e.g. 0777123) if we just do prefix matching. To tackle that, we
2926
                // check the validity of the number if the assumed national prefix is removed (777123 won't
2927
                // be valid in Japan).
2928 1
                return $this->isValidNumber(
2929 1
                    $this->parse(substr($normalizedNationalNumber, mb_strlen($nationalPrefix)), $regionCode)
2930
                );
2931
            } catch (NumberParseException $e) {
2932
                return false;
2933
            }
2934
        }
2935 1
        return false;
2936
    }
2937
2938
    /**
2939
     * Tests whether a phone number matches a valid pattern. Note this doesn't verify the number
2940
     * is actually in use, which is impossible to tell by just looking at a number itself. It only
2941
     * verifies whether the parsed, canonicalised number is valid: not whether a particular series of
2942
     * digits entered by the user is diallable from the region provided when parsing. For example, the
2943
     * number +41 (0) 78 927 2696 can be parsed into a number with country code "41" and national
2944
     * significant number "789272696". This is valid, while the original string is not diallable.
2945
     *
2946
     * @param PhoneNumber $number the phone number that we want to validate
2947
     * @return boolean that indicates whether the number is of a valid pattern
2948
     */
2949 2014
    public function isValidNumber(PhoneNumber $number)
2950
    {
2951 2014
        $regionCode = $this->getRegionCodeForNumber($number);
2952 2014
        return $this->isValidNumberForRegion($number, $regionCode);
2953
    }
2954
2955
    /**
2956
     * Tests whether a phone number is valid for a certain region. Note this doesn't verify the number
2957
     * is actually in use, which is impossible to tell by just looking at a number itself. If the
2958
     * country calling code is not the same as the country calling code for the region, this
2959
     * immediately exits with false. After this, the specific number pattern rules for the region are
2960
     * examined. This is useful for determining for example whether a particular number is valid for
2961
     * Canada, rather than just a valid NANPA number.
2962
     * Warning: In most cases, you want to use {@link #isValidNumber} instead. For example, this
2963
     * method will mark numbers from British Crown dependencies such as the Isle of Man as invalid for
2964
     * the region "GB" (United Kingdom), since it has its own region code, "IM", which may be
2965
     * undesirable.
2966
     *
2967
     * @param PhoneNumber $number the phone number that we want to validate
2968
     * @param string $regionCode the region that we want to validate the phone number for
2969
     * @return boolean that indicates whether the number is of a valid pattern
2970
     */
2971 2020
    public function isValidNumberForRegion(PhoneNumber $number, $regionCode)
2972
    {
2973 2020
        $countryCode = $number->getCountryCode();
2974 2020
        $metadata = $this->getMetadataForRegionOrCallingCode($countryCode, $regionCode);
2975 2020
        if (($metadata === null) ||
2976 1970
            (static::REGION_CODE_FOR_NON_GEO_ENTITY !== $regionCode &&
2977 2020
                $countryCode !== $this->getCountryCodeForValidRegion($regionCode))
2978
        ) {
2979
            // Either the region code was invalid, or the country calling code for this number does not
2980
            // match that of the region code.
2981 64
            return false;
2982
        }
2983 1969
        $nationalSignificantNumber = $this->getNationalSignificantNumber($number);
2984
2985 1969
        return $this->getNumberTypeHelper($nationalSignificantNumber, $metadata) != PhoneNumberType::UNKNOWN;
2986
    }
2987
2988
    /**
2989
     * Parses a string and returns it as a phone number in proto buffer format. The method is quite
2990
     * lenient and looks for a number in the input text (raw input) and does not check whether the
2991
     * string is definitely only a phone number. To do this, it ignores punctuation and white-space,
2992
     * as well as any text before the number (e.g. a leading “Tel: ”) and trims the non-number bits.
2993
     * It will accept a number in any format (E164, national, international etc), assuming it can
2994
     * interpreted with the defaultRegion supplied. It also attempts to convert any alpha characters
2995
     * into digits if it thinks this is a vanity number of the type "1800 MICROSOFT".
2996
     *
2997
     * <p> This method will throw a {@link NumberParseException} if the number is not considered to
2998
     * be a possible number. Note that validation of whether the number is actually a valid number
2999
     * for a particular region is not performed. This can be done separately with {@link #isValidNumber}.
3000
     *
3001
     * <p> Note this method canonicalizes the phone number such that different representations can be
3002
     * easily compared, no matter what form it was originally entered in (e.g. national,
3003
     * international). If you want to record context about the number being parsed, such as the raw
3004
     * input that was entered, how the country code was derived etc. then call {@link
3005
     * #parseAndKeepRawInput} instead.
3006
     *
3007
     * @param string $numberToParse number that we are attempting to parse. This can contain formatting
3008
     *                          such as +, ( and -, as well as a phone number extension.
3009
     * @param string|null $defaultRegion region that we are expecting the number to be from. This is only used
3010
     *                          if the number being parsed is not written in international format.
3011
     *                          The country_code for the number in this case would be stored as that
3012
     *                          of the default region supplied. If the number is guaranteed to
3013
     *                          start with a '+' followed by the country calling code, then
3014
     *                          "ZZ" or null can be supplied.
3015
     * @param PhoneNumber|null $phoneNumber
3016
     * @param bool $keepRawInput
3017
     * @return PhoneNumber a phone number proto buffer filled with the parsed number
3018
     * @throws NumberParseException  if the string is not considered to be a viable phone number (e.g.
3019
     *                               too few or too many digits) or if no default region was supplied
3020
     *                               and the number is not in international format (does not start
3021
     *                               with +)
3022
     */
3023 3114
    public function parse($numberToParse, $defaultRegion = null, PhoneNumber $phoneNumber = null, $keepRawInput = false)
3024
    {
3025 3114
        if ($phoneNumber === null) {
3026 3114
            $phoneNumber = new PhoneNumber();
3027
        }
3028 3114
        $this->parseHelper($numberToParse, $defaultRegion, $keepRawInput, true, $phoneNumber);
3029 3109
        return $phoneNumber;
3030
    }
3031
3032
    /**
3033
     * Formats a phone number in the specified format using client-defined formatting rules. Note that
3034
     * if the phone number has a country calling code of zero or an otherwise invalid country calling
3035
     * code, we cannot work out things like whether there should be a national prefix applied, or how
3036
     * to format extensions, so we return the national significant number with no formatting applied.
3037
     *
3038
     * @param PhoneNumber $number the phone number to be formatted
3039
     * @param int $numberFormat the format the phone number should be formatted into
3040
     * @param array $userDefinedFormats formatting rules specified by clients
3041
     * @return String the formatted phone number
3042
     */
3043 2
    public function formatByPattern(PhoneNumber $number, $numberFormat, array $userDefinedFormats)
3044
    {
3045 2
        $countryCallingCode = $number->getCountryCode();
3046 2
        $nationalSignificantNumber = $this->getNationalSignificantNumber($number);
3047 2
        if (!$this->hasValidCountryCallingCode($countryCallingCode)) {
3048
            return $nationalSignificantNumber;
3049
        }
3050
        // Note getRegionCodeForCountryCode() is used because formatting information for regions which
3051
        // share a country calling code is contained by only one region for performance reasons. For
3052
        // example, for NANPA regions it will be contained in the metadata for US.
3053 2
        $regionCode = $this->getRegionCodeForCountryCode($countryCallingCode);
3054
        // Metadata cannot be null because the country calling code is valid
3055 2
        $metadata = $this->getMetadataForRegionOrCallingCode($countryCallingCode, $regionCode);
3056
3057 2
        $formattedNumber = '';
3058
3059 2
        $formattingPattern = $this->chooseFormattingPatternForNumber($userDefinedFormats, $nationalSignificantNumber);
3060 2
        if ($formattingPattern === null) {
3061
            // If no pattern above is matched, we format the number as a whole.
3062
            $formattedNumber .= $nationalSignificantNumber;
3063
        } else {
3064 2
            $numFormatCopy = new NumberFormat();
3065
            // Before we do a replacement of the national prefix pattern $NP with the national prefix, we
3066
            // need to copy the rule so that subsequent replacements for different numbers have the
3067
            // appropriate national prefix.
3068 2
            $numFormatCopy->mergeFrom($formattingPattern);
3069 2
            $nationalPrefixFormattingRule = $formattingPattern->getNationalPrefixFormattingRule();
3070 2
            if (mb_strlen($nationalPrefixFormattingRule) > 0) {
3071 1
                $nationalPrefix = $metadata->getNationalPrefix();
3072 1
                if (mb_strlen($nationalPrefix) > 0) {
3073
                    // Replace $NP with national prefix and $FG with the first group ($1).
3074 1
                    $nationalPrefixFormattingRule = str_replace(
3075 1
                        array(static::NP_STRING, static::FG_STRING),
3076 1
                        array($nationalPrefix, '$1'),
3077
                        $nationalPrefixFormattingRule
3078
                    );
3079 1
                    $numFormatCopy->setNationalPrefixFormattingRule($nationalPrefixFormattingRule);
3080
                } else {
3081
                    // We don't want to have a rule for how to format the national prefix if there isn't one.
3082 1
                    $numFormatCopy->clearNationalPrefixFormattingRule();
3083
                }
3084
            }
3085 2
            $formattedNumber .= $this->formatNsnUsingPattern($nationalSignificantNumber, $numFormatCopy, $numberFormat);
3086
        }
3087 2
        $this->maybeAppendFormattedExtension($number, $metadata, $numberFormat, $formattedNumber);
3088 2
        $this->prefixNumberWithCountryCallingCode($countryCallingCode, $numberFormat, $formattedNumber);
3089 2
        return $formattedNumber;
3090
    }
3091
3092
    /**
3093
     * Gets a valid number for the specified region.
3094
     *
3095
     * @param string regionCode  the region for which an example number is needed
0 ignored issues
show
Bug introduced by
The type libphonenumber\regionCode was not found. Maybe you did not declare it correctly or list all dependencies?

The issue could also be caused by a filter entry in the build configuration. If the path has been excluded in your configuration, e.g. excluded_paths: ["lib/*"], you can move it to the dependency path list as follows:

filter:
    dependency_paths: ["lib/*"]

For further information see https://scrutinizer-ci.com/docs/tools/php/php-scrutinizer/#list-dependency-paths

Loading history...
3096
     * @return PhoneNumber a valid fixed-line number for the specified region. Returns null when the metadata
3097
     *    does not contain such information, or the region 001 is passed in. For 001 (representing
3098
     *    non-geographical numbers), call {@link #getExampleNumberForNonGeoEntity} instead.
3099
     */
3100 248
    public function getExampleNumber($regionCode)
3101
    {
3102 248
        return $this->getExampleNumberForType($regionCode, PhoneNumberType::FIXED_LINE);
3103
    }
3104
3105
    /**
3106
     * Gets an invalid number for the specified region. This is useful for unit-testing purposes,
3107
     * where you want to test what will happen with an invalid number. Note that the number that is
3108
     * returned will always be able to be parsed and will have the correct country code. It may also
3109
     * be a valid *short* number/code for this region. Validity checking such numbers is handled with
3110
     * {@link ShortNumberInfo}.
3111
     *
3112
     * @param string $regionCode The region for which an example number is needed
3113
     * @return PhoneNumber|null An invalid number for the specified region. Returns null when an unsupported region
3114
     * or the region 001 (Earth) is passed in.
3115
     */
3116 245
    public function getInvalidExampleNumber($regionCode)
3117
    {
3118 245
        if (!$this->isValidRegionCode($regionCode)) {
3119
            return null;
3120
        }
3121
3122
        // We start off with a valid fixed-line number since every country supports this. Alternatively
3123
        // we could start with a different number type, since fixed-line numbers typically have a wide
3124
        // breadth of valid number lengths and we may have to make it very short before we get an
3125
        // invalid number.
3126
3127 245
        $desc = $this->getNumberDescByType($this->getMetadataForRegion($regionCode), PhoneNumberType::FIXED_LINE);
0 ignored issues
show
Bug introduced by
It seems like $this->getMetadataForRegion($regionCode) can also be of type null; however, parameter $metadata of libphonenumber\PhoneNumb...::getNumberDescByType() does only seem to accept libphonenumber\PhoneMetadata, maybe add an additional type check? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

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

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

3191
                $desc = $this->getNumberDescByType(/** @scrutinizer ignore-type */ $this->getMetadataForNonGeographicalRegion($countryCallingCode), $regionCodeOrType);
Loading history...
3192
                try {
3193
                    if ($desc->getExampleNumber() != '') {
3194
                        return $this->parse('+' . $countryCallingCode . $desc->getExampleNumber(), static::UNKNOWN_REGION);
3195
                    }
3196
                } catch (NumberParseException $e) {
3197
                    // noop
3198
                }
3199
            }
3200
            // There are no example numbers of this type for any country in the library.
3201
            return null;
3202
        }
3203
3204
        // Check the region code is valid.
3205 3188
        if (!$this->isValidRegionCode($regionCodeOrType)) {
3206 1
            return null;
3207
        }
3208 3188
        $desc = $this->getNumberDescByType($this->getMetadataForRegion($regionCodeOrType), $type);
3209
        try {
3210 3188
            if ($desc->hasExampleNumber()) {
3211 3188
                return $this->parse($desc->getExampleNumber(), $regionCodeOrType);
3212
            }
3213
        } catch (NumberParseException $e) {
3214
            // noop
3215
        }
3216 1352
        return null;
3217
    }
3218
3219
    /**
3220
     * @param PhoneMetadata $metadata
3221
     * @param int $type PhoneNumberType
3222
     * @return PhoneNumberDesc
3223
     */
3224 4636
    protected function getNumberDescByType(PhoneMetadata $metadata, $type)
3225
    {
3226
        switch ($type) {
3227 4636
            case PhoneNumberType::PREMIUM_RATE:
3228 251
                return $metadata->getPremiumRate();
3229 4534
            case PhoneNumberType::TOLL_FREE:
3230 251
                return $metadata->getTollFree();
3231 4459
            case PhoneNumberType::MOBILE:
3232 257
                return $metadata->getMobile();
3233 4458
            case PhoneNumberType::FIXED_LINE:
3234 4458
            case PhoneNumberType::FIXED_LINE_OR_MOBILE:
3235 1230
                return $metadata->getFixedLine();
3236 4455
            case PhoneNumberType::SHARED_COST:
3237 248
                return $metadata->getSharedCost();
3238 4263
            case PhoneNumberType::VOIP:
3239 248
                return $metadata->getVoip();
3240 4107
            case PhoneNumberType::PERSONAL_NUMBER:
3241 248
                return $metadata->getPersonalNumber();
3242 3921
            case PhoneNumberType::PAGER:
3243 248
                return $metadata->getPager();
3244 3699
            case PhoneNumberType::UAN:
3245 248
                return $metadata->getUan();
3246 3517
            case PhoneNumberType::VOICEMAIL:
3247 249
                return $metadata->getVoicemail();
3248
            default:
3249 3287
                return $metadata->getGeneralDesc();
3250
        }
3251
    }
3252
3253
    /**
3254
     * Gets a valid number for the specified country calling code for a non-geographical entity.
3255
     *
3256
     * @param int $countryCallingCode the country calling code for a non-geographical entity
3257
     * @return PhoneNumber a valid number for the non-geographical entity. Returns null when the metadata
3258
     *    does not contain such information, or the country calling code passed in does not belong
3259
     *    to a non-geographical entity.
3260
     */
3261 10
    public function getExampleNumberForNonGeoEntity($countryCallingCode)
3262
    {
3263 10
        $metadata = $this->getMetadataForNonGeographicalRegion($countryCallingCode);
3264 10
        if ($metadata !== null) {
3265
            // For geographical entities, fixed-line data is always present. However, for non-geographical
3266
            // entities, this is not the case, so we have to go through different types to find the
3267
            // example number. We don't check fixed-line or personal number since they aren't used by
3268
            // non-geographical entities (if this changes, a unit-test will catch this.)
3269
            /** @var PhoneNumberDesc[] $list */
3270
            $list = array(
3271 10
                $metadata->getMobile(),
3272 10
                $metadata->getTollFree(),
3273 10
                $metadata->getSharedCost(),
3274 10
                $metadata->getVoip(),
3275 10
                $metadata->getVoicemail(),
3276 10
                $metadata->getUan(),
3277 10
                $metadata->getPremiumRate(),
3278
            );
3279 10
            foreach ($list as $desc) {
3280
                try {
3281 10
                    if ($desc !== null && $desc->hasExampleNumber()) {
3282 10
                        return $this->parse('+' . $countryCallingCode . $desc->getExampleNumber(), self::UNKNOWN_REGION);
3283
                    }
3284
                } catch (NumberParseException $e) {
3285
                    // noop
3286
                }
3287
            }
3288
        }
3289
        return null;
3290
    }
3291
3292
3293
    /**
3294
     * Takes two phone numbers and compares them for equality.
3295
     *
3296
     * <p>Returns EXACT_MATCH if the country_code, NSN, presence of a leading zero
3297
     * for Italian numbers and any extension present are the same. Returns NSN_MATCH
3298
     * if either or both has no region specified, and the NSNs and extensions are
3299
     * the same. Returns SHORT_NSN_MATCH if either or both has no region specified,
3300
     * or the region specified is the same, and one NSN could be a shorter version
3301
     * of the other number. This includes the case where one has an extension
3302
     * specified, and the other does not. Returns NO_MATCH otherwise. For example,
3303
     * the numbers +1 345 657 1234 and 657 1234 are a SHORT_NSN_MATCH. The numbers
3304
     * +1 345 657 1234 and 345 657 are a NO_MATCH.
3305
     *
3306
     * @param $firstNumberIn PhoneNumber|string First number to compare. If it is a
3307
     * string it can contain formatting, and can have country calling code specified
3308
     * with + at the start.
3309
     * @param $secondNumberIn PhoneNumber|string Second number to compare. If it is a
3310
     * string it can contain formatting, and can have country calling code specified
3311
     * with + at the start.
3312
     * @throws \InvalidArgumentException
3313
     * @return int {MatchType} NOT_A_NUMBER, NO_MATCH,
3314
     */
3315 8
    public function isNumberMatch($firstNumberIn, $secondNumberIn)
3316
    {
3317 8
        if (is_string($firstNumberIn) && is_string($secondNumberIn)) {
3318
            try {
3319 4
                $firstNumberAsProto = $this->parse($firstNumberIn, static::UNKNOWN_REGION);
3320 4
                return $this->isNumberMatch($firstNumberAsProto, $secondNumberIn);
3321 3
            } catch (NumberParseException $e) {
3322 3
                if ($e->getErrorType() === NumberParseException::INVALID_COUNTRY_CODE) {
3323
                    try {
3324 3
                        $secondNumberAsProto = $this->parse($secondNumberIn, static::UNKNOWN_REGION);
3325 2
                        return $this->isNumberMatch($secondNumberAsProto, $firstNumberIn);
3326 3
                    } catch (NumberParseException $e2) {
3327 3
                        if ($e2->getErrorType() === NumberParseException::INVALID_COUNTRY_CODE) {
3328
                            try {
3329 3
                                $firstNumberProto = new PhoneNumber();
3330 3
                                $secondNumberProto = new PhoneNumber();
3331 3
                                $this->parseHelper($firstNumberIn, null, false, false, $firstNumberProto);
3332 3
                                $this->parseHelper($secondNumberIn, null, false, false, $secondNumberProto);
3333 3
                                return $this->isNumberMatch($firstNumberProto, $secondNumberProto);
3334
                            } catch (NumberParseException $e3) {
3335
                                // Fall through and return MatchType::NOT_A_NUMBER
3336
                            }
3337
                        }
3338
                    }
3339
                }
3340
            }
3341 1
            return MatchType::NOT_A_NUMBER;
3342
        }
3343 8
        if ($firstNumberIn instanceof PhoneNumber && is_string($secondNumberIn)) {
3344
            // First see if the second number has an implicit country calling code, by attempting to parse
3345
            // it.
3346
            try {
3347 4
                $secondNumberAsProto = $this->parse($secondNumberIn, static::UNKNOWN_REGION);
3348 2
                return $this->isNumberMatch($firstNumberIn, $secondNumberAsProto);
3349 3
            } catch (NumberParseException $e) {
3350 3
                if ($e->getErrorType() === NumberParseException::INVALID_COUNTRY_CODE) {
3351
                    // The second number has no country calling code. EXACT_MATCH is no longer possible.
3352
                    // We parse it as if the region was the same as that for the first number, and if
3353
                    // EXACT_MATCH is returned, we replace this with NSN_MATCH.
3354 3
                    $firstNumberRegion = $this->getRegionCodeForCountryCode($firstNumberIn->getCountryCode());
3355
                    try {
3356 3
                        if ($firstNumberRegion != static::UNKNOWN_REGION) {
3357 3
                            $secondNumberWithFirstNumberRegion = $this->parse($secondNumberIn, $firstNumberRegion);
3358 3
                            $match = $this->isNumberMatch($firstNumberIn, $secondNumberWithFirstNumberRegion);
3359 3
                            if ($match === MatchType::EXACT_MATCH) {
3360 1
                                return MatchType::NSN_MATCH;
3361
                            }
3362 2
                            return $match;
3363
                        }
3364
3365
                        // If the first number didn't have a valid country calling code, then we parse the
3366
                        // second number without one as well.
3367 1
                        $secondNumberProto = new PhoneNumber();
3368 1
                        $this->parseHelper($secondNumberIn, null, false, false, $secondNumberProto);
3369 1
                        return $this->isNumberMatch($firstNumberIn, $secondNumberProto);
3370
                    } catch (NumberParseException $e2) {
3371
                        // Fall-through to return NOT_A_NUMBER.
3372
                    }
3373
                }
3374
            }
3375
        }
3376 8
        if ($firstNumberIn instanceof PhoneNumber && $secondNumberIn instanceof PhoneNumber) {
3377
            // We only care about the fields that uniquely define a number, so we copy these across
3378
            // explicitly.
3379 8
            $firstNumber = self::copyCoreFieldsOnly($firstNumberIn);
3380 8
            $secondNumber = self::copyCoreFieldsOnly($secondNumberIn);
3381
3382
            // Early exit if both had extensions and these are different.
3383 8
            if ($firstNumber->hasExtension() && $secondNumber->hasExtension() &&
3384 8
                $firstNumber->getExtension() != $secondNumber->getExtension()
3385
            ) {
3386 1
                return MatchType::NO_MATCH;
3387
            }
3388
3389 8
            $firstNumberCountryCode = $firstNumber->getCountryCode();
3390 8
            $secondNumberCountryCode = $secondNumber->getCountryCode();
3391
            // Both had country_code specified.
3392 8
            if ($firstNumberCountryCode != 0 && $secondNumberCountryCode != 0) {
0 ignored issues
show
Bug Best Practice 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 Best Practice 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...
3393 8
                if ($firstNumber->equals($secondNumber)) {
3394 5
                    return MatchType::EXACT_MATCH;
3395
                }
3396
3397 3
                if ($firstNumberCountryCode == $secondNumberCountryCode &&
3398 3
                    $this->isNationalNumberSuffixOfTheOther($firstNumber, $secondNumber)) {
3399
                    // A SHORT_NSN_MATCH occurs if there is a difference because of the presence or absence of
3400
                    // an 'Italian leading zero', the presence or absence of an extension, or one NSN being a
3401
                    // shorter variant of the other.
3402 2
                    return MatchType::SHORT_NSN_MATCH;
3403
                }
3404
                // This is not a match.
3405 1
                return MatchType::NO_MATCH;
3406
            }
3407
            // Checks cases where one or both country_code fields were not specified. To make equality
3408
            // checks easier, we first set the country_code fields to be equal.
3409 3
            $firstNumber->setCountryCode($secondNumberCountryCode);
3410
            // If all else was the same, then this is an NSN_MATCH.
3411 3
            if ($firstNumber->equals($secondNumber)) {
3412 1
                return MatchType::NSN_MATCH;
3413
            }
3414 3
            if ($this->isNationalNumberSuffixOfTheOther($firstNumber, $secondNumber)) {
3415 2
                return MatchType::SHORT_NSN_MATCH;
3416
            }
3417 1
            return MatchType::NO_MATCH;
3418
        }
3419
        return MatchType::NOT_A_NUMBER;
3420
    }
3421
3422
    /**
3423
     * Returns true when one national number is the suffix of the other or both are the same.
3424
     * @param PhoneNumber $firstNumber
3425
     * @param PhoneNumber $secondNumber
3426
     * @return bool
3427
     */
3428 4
    protected function isNationalNumberSuffixOfTheOther(PhoneNumber $firstNumber, PhoneNumber $secondNumber)
3429
    {
3430 4
        $firstNumberNationalNumber = trim((string)$firstNumber->getNationalNumber());
3431 4
        $secondNumberNationalNumber = trim((string)$secondNumber->getNationalNumber());
3432 4
        return $this->stringEndsWithString($firstNumberNationalNumber, $secondNumberNationalNumber) ||
3433 4
        $this->stringEndsWithString($secondNumberNationalNumber, $firstNumberNationalNumber);
3434
    }
3435
3436 4
    protected function stringEndsWithString($hayStack, $needle)
3437
    {
3438 4
        $revNeedle = strrev($needle);
3439 4
        $revHayStack = strrev($hayStack);
3440 4
        return strpos($revHayStack, $revNeedle) === 0;
3441
    }
3442
3443
    /**
3444
     * Returns true if the supplied region supports mobile number portability. Returns false for
3445
     * invalid, unknown or regions that don't support mobile number portability.
3446
     *
3447
     * @param string $regionCode the region for which we want to know whether it supports mobile number
3448
     *                    portability or not.
3449
     * @return bool
3450
     */
3451 3
    public function isMobileNumberPortableRegion($regionCode)
3452
    {
3453 3
        $metadata = $this->getMetadataForRegion($regionCode);
3454 3
        if ($metadata === null) {
3455
            return false;
3456
        }
3457
3458 3
        return $metadata->isMobileNumberPortableRegion();
3459
    }
3460
3461
    /**
3462
     * Check whether a phone number is a possible number given a number in the form of a string, and
3463
     * the region where the number could be dialed from. It provides a more lenient check than
3464
     * {@link #isValidNumber}. See {@link #isPossibleNumber(PhoneNumber)} for details.
3465
     *
3466
     * Convenience wrapper around {@link #isPossibleNumberWithReason}. Instead of returning the reason
3467
     * for failure, this method returns a boolean value.
3468
     * for failure, this method returns true if the number is either a possible fully-qualified number
3469
     * (containing the area code and country code), or if the number could be a possible local number
3470
     * (with a country code, but missing an area code). Local numbers are considered possible if they
3471
     * could be possibly dialled in this format: if the area code is needed for a call to connect, the
3472
     * number is not considered possible without it.
3473
     *
3474
     * Note: There are two ways to call this method.
3475
     *
3476
     * isPossibleNumber(PhoneNumber $numberObject)
3477
     * isPossibleNumber(string '+441174960126', string 'GB')
3478
     *
3479
     * @param PhoneNumber|string $number the number that needs to be checked, in the form of a string
3480
     * @param string|null $regionDialingFrom the region that we are expecting the number to be dialed from.
3481
     *     Note this is different from the region where the number belongs.  For example, the number
3482
     *     +1 650 253 0000 is a number that belongs to US. When written in this form, it can be
3483
     *     dialed from any region. When it is written as 00 1 650 253 0000, it can be dialed from any
3484
     *     region which uses an international dialling prefix of 00. When it is written as
3485
     *     650 253 0000, it can only be dialed from within the US, and when written as 253 0000, it
3486
     *     can only be dialed from within a smaller area in the US (Mountain View, CA, to be more
3487
     *     specific).
3488
     * @return boolean true if the number is possible
3489
     */
3490 58
    public function isPossibleNumber($number, $regionDialingFrom = null)
3491
    {
3492 58
        if (is_string($number)) {
3493
            try {
3494 3
                return $this->isPossibleNumber($this->parse($number, $regionDialingFrom));
3495 1
            } catch (NumberParseException $e) {
3496 1
                return false;
3497
            }
3498
        } else {
3499 58
            $result = $this->isPossibleNumberWithReason($number);
3500 58
            return $result === ValidationResult::IS_POSSIBLE
3501 58
                || $result === ValidationResult::IS_POSSIBLE_LOCAL_ONLY;
3502
        }
3503
    }
3504
3505
3506
    /**
3507
     * Check whether a phone number is a possible number. It provides a more lenient check than
3508
     * {@link #isValidNumber} in the following sense:
3509
     * <ol>
3510
     *   <li> It only checks the length of phone numbers. In particular, it doesn't check starting
3511
     *        digits of the number.
3512
     *   <li> It doesn't attempt to figure out the type of the number, but uses general rules which
3513
     *        applies to all types of phone numbers in a region. Therefore, it is much faster than
3514
     *        isValidNumber.
3515
     *   <li> For some numbers (particularly fixed-line), many regions have the concept of area code,
3516
     *        which together with subscriber number constitute the national significant number. It is
3517
     *        sometimes okay to dial only the subscriber number when dialing in the same area. This
3518
     *        function will return IS_POSSIBLE_LOCAL_ONLY if the subscriber-number-only version is
3519
     *        passed in. On the other hand, because isValidNumber validates using information on both
3520
     *        starting digits (for fixed line numbers, that would most likely be area codes) and
3521
     *        length (obviously includes the length of area codes for fixed line numbers), it will
3522
     *        return false for the subscriber-number-only version.
3523
     * </ol>
3524
     * @param PhoneNumber $number the number that needs to be checked
3525
     * @return int a ValidationResult object which indicates whether the number is possible
3526
     */
3527 60
    public function isPossibleNumberWithReason(PhoneNumber $number)
3528
    {
3529 60
        return $this->isPossibleNumberForTypeWithReason($number, PhoneNumberType::UNKNOWN);
3530
    }
3531
3532
    /**
3533
     * Check whether a phone number is a possible number of a particular type. For types that don't
3534
     * exist in a particular region, this will return a result that isn't so useful; it is recommended
3535
     * that you use {@link #getSupportedTypesForRegion} or {@link #getSupportedTypesForNonGeoEntity}
3536
     * respectively before calling this method to determine whether you should call it for this number
3537
     * at all.
3538
     *
3539
     * This provides a more lenient check than {@link #isValidNumber} in the following sense:
3540
     *
3541
     * <ol>
3542
     *   <li> It only checks the length of phone numbers. In particular, it doesn't check starting
3543
     *        digits of the number.
3544
     *   <li> For some numbers (particularly fixed-line), many regions have the concept of area code,
3545
     *        which together with subscriber number constitute the national significant number. It is
3546
     *        sometimes okay to dial only the subscriber number when dialing in the same area. This
3547
     *        function will return IS_POSSIBLE_LOCAL_ONLY if the subscriber-number-only version is
3548
     *        passed in. On the other hand, because isValidNumber validates using information on both
3549
     *        starting digits (for fixed line numbers, that would most likely be area codes) and
3550
     *        length (obviously includes the length of area codes for fixed line numbers), it will
3551
     *        return false for the subscriber-number-only version.
3552
     * </ol>
3553
     *
3554
     * @param PhoneNumber $number the number that needs to be checked
3555
     * @param int $type the PhoneNumberType we are interested in
3556
     * @return int a ValidationResult object which indicates whether the number is possible
3557
     */
3558 69
    public function isPossibleNumberForTypeWithReason(PhoneNumber $number, $type)
3559
    {
3560 69
        $nationalNumber = $this->getNationalSignificantNumber($number);
3561 69
        $countryCode = $number->getCountryCode();
3562
3563
        // Note: For regions that share a country calling code, like NANPA numbers, we just use the
3564
        // rules from the default region (US in this case) since the getRegionCodeForNumber will not
3565
        // work if the number is possible but not valid. There is in fact one country calling code (290)
3566
        // where the possible number pattern differs between various regions (Saint Helena and Tristan
3567
        // da Cuñha), but this is handled by putting all possible lengths for any country with this
3568
        // country calling code in the metadata for the default region in this case.
3569 69
        if (!$this->hasValidCountryCallingCode($countryCode)) {
3570 1
            return ValidationResult::INVALID_COUNTRY_CODE;
3571
        }
3572
3573 69
        $regionCode = $this->getRegionCodeForCountryCode($countryCode);
3574
        // Metadata cannot be null because the country calling code is valid.
3575 69
        $metadata = $this->getMetadataForRegionOrCallingCode($countryCode, $regionCode);
3576 69
        return $this->testNumberLength($nationalNumber, $metadata, $type);
3577
    }
3578
3579
    /**
3580
     * Attempts to extract a valid number from a phone number that is too long to be valid, and resets
3581
     * the PhoneNumber object passed in to that valid version. If no valid number could be extracted,
3582
     * the PhoneNumber object passed in will not be modified.
3583
     * @param PhoneNumber $number a PhoneNumber object which contains a number that is too long to be valid.
3584
     * @return boolean true if a valid phone number can be successfully extracted.
3585
     */
3586 1
    public function truncateTooLongNumber(PhoneNumber $number)
3587
    {
3588 1
        if ($this->isValidNumber($number)) {
3589 1
            return true;
3590
        }
3591 1
        $numberCopy = new PhoneNumber();
3592 1
        $numberCopy->mergeFrom($number);
3593 1
        $nationalNumber = $number->getNationalNumber();
3594
        do {
3595 1
            $nationalNumber = floor($nationalNumber / 10);
3596 1
            $numberCopy->setNationalNumber($nationalNumber);
3597 1
            if ($this->isPossibleNumberWithReason($numberCopy) == ValidationResult::TOO_SHORT || $nationalNumber == 0) {
3598 1
                return false;
3599
            }
3600 1
        } while (!$this->isValidNumber($numberCopy));
3601 1
        $number->setNationalNumber($nationalNumber);
3602 1
        return true;
3603
    }
3604
}
3605