Completed
Push — master ( e796c9...563c73 )
by Joshua
10:55
created

PhoneNumberUtil::getInvalidExampleNumber()   B

Complexity

Conditions 6
Paths 7

Size

Total Lines 46
Code Lines 15

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 11
CRAP Score 6.1308

Importance

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

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

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

function doesNotAcceptNull(stdClass $x) { }

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

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

// Safe - Alternative 2
function withCheck2() {
    $x = mayReturnNull();
    if ($x instanceof stdClass) {
        doesNotAcceptNull($x);
    }
}
Loading history...
739 515
                return $regionCode;
740
            }
741
        }
742 37
        return null;
743
    }
744
745
    /**
746
     * Gets the national significant number of the a phone number. Note a national significant number
747
     * doesn't contain a national prefix or any formatting.
748
     *
749
     * @param PhoneNumber $number the phone number for which the national significant number is needed
750
     * @return string the national significant number of the PhoneNumber object passed in
751
     */
752 2001
    public function getNationalSignificantNumber(PhoneNumber $number)
753
    {
754
        // If leading zero(s) have been set, we prefix this now. Note this is not a national prefix.
755 2001
        $nationalNumber = '';
756 2001
        if ($number->isItalianLeadingZero()) {
757 44
            $zeros = str_repeat('0', $number->getNumberOfLeadingZeros());
758 44
            $nationalNumber .= $zeros;
759
        }
760 2001
        $nationalNumber .= $number->getNationalNumber();
761 2001
        return $nationalNumber;
762
    }
763
764
    /**
765
     * @param string $nationalNumber
766
     * @param PhoneMetadata $metadata
767
     * @return int PhoneNumberType constant
768
     */
769 1935
    protected function getNumberTypeHelper($nationalNumber, PhoneMetadata $metadata)
770
    {
771 1935
        if (!$this->isNumberMatchingDesc($nationalNumber, $metadata->getGeneralDesc())) {
772 251
            return PhoneNumberType::UNKNOWN;
773
        }
774 1734
        if ($this->isNumberMatchingDesc($nationalNumber, $metadata->getPremiumRate())) {
775 146
            return PhoneNumberType::PREMIUM_RATE;
776
        }
777 1589
        if ($this->isNumberMatchingDesc($nationalNumber, $metadata->getTollFree())) {
778 180
            return PhoneNumberType::TOLL_FREE;
779
        }
780
781
782 1418
        if ($this->isNumberMatchingDesc($nationalNumber, $metadata->getSharedCost())) {
783 62
            return PhoneNumberType::SHARED_COST;
784
        }
785 1356
        if ($this->isNumberMatchingDesc($nationalNumber, $metadata->getVoip())) {
786 80
            return PhoneNumberType::VOIP;
787
        }
788 1279
        if ($this->isNumberMatchingDesc($nationalNumber, $metadata->getPersonalNumber())) {
789 63
            return PhoneNumberType::PERSONAL_NUMBER;
790
        }
791 1216
        if ($this->isNumberMatchingDesc($nationalNumber, $metadata->getPager())) {
792 27
            return PhoneNumberType::PAGER;
793
        }
794 1193
        if ($this->isNumberMatchingDesc($nationalNumber, $metadata->getUan())) {
795 59
            return PhoneNumberType::UAN;
796
        }
797 1136
        if ($this->isNumberMatchingDesc($nationalNumber, $metadata->getVoicemail())) {
798 12
            return PhoneNumberType::VOICEMAIL;
799
        }
800 1125
        $isFixedLine = $this->isNumberMatchingDesc($nationalNumber, $metadata->getFixedLine());
801 1125
        if ($isFixedLine) {
802 809
            if ($metadata->isSameMobileAndFixedLinePattern()) {
803
                return PhoneNumberType::FIXED_LINE_OR_MOBILE;
804 809
            } elseif ($this->isNumberMatchingDesc($nationalNumber, $metadata->getMobile())) {
805 57
                return PhoneNumberType::FIXED_LINE_OR_MOBILE;
806
            }
807 760
            return PhoneNumberType::FIXED_LINE;
808
        }
809
        // Otherwise, test to see if the number is mobile. Only do this if certain that the patterns for
810
        // mobile and fixed line aren't the same.
811 445
        if (!$metadata->isSameMobileAndFixedLinePattern() &&
812 445
            $this->isNumberMatchingDesc($nationalNumber, $metadata->getMobile())
813
        ) {
814 256
            return PhoneNumberType::MOBILE;
815
        }
816 210
        return PhoneNumberType::UNKNOWN;
817
    }
818
819
    /**
820
     * @param string $nationalNumber
821
     * @param PhoneNumberDesc $numberDesc
822
     * @return bool
823
     */
824 1962
    public function isNumberMatchingDesc($nationalNumber, PhoneNumberDesc $numberDesc)
825
    {
826
        // Check if any possible number lengths are present; if so, we use them to avoid checking the
827
        // validation pattern if they don't match. If they are absent, this means they match the general
828
        // description, which we have already checked before checking a specific number type.
829 1962
        $actualLength = mb_strlen($nationalNumber);
830 1962
        $possibleLengths = $numberDesc->getPossibleLength();
831 1962
        if (count($possibleLengths) > 0 && !in_array($actualLength, $possibleLengths)) {
832 1560
            return false;
833
        }
834
835 1775
        $nationalNumberPatternMatcher = new Matcher($numberDesc->getNationalNumberPattern(), $nationalNumber);
836
837 1775
        return $nationalNumberPatternMatcher->matches();
838
    }
839
840
    /**
841
     * isNumberGeographical(PhoneNumber)
842
     *
843
     * Tests whether a phone number has a geographical association. It checks if the number is
844
     * associated to a certain region in the country where it belongs to. Note that this doesn't
845
     * verify if the number is actually in use.
846
     *
847
     * isNumberGeographical(PhoneNumberType, $countryCallingCode)
848
     *
849
     * Tests whether a phone number has a geographical association, as represented by its type and the
850
     * country it belongs to.
851
     *
852
     * This version exists since calculating the phone number type is expensive; if we have already
853
     * done this, we don't want to do it again.
854
     *
855
     * @param PhoneNumber|int $phoneNumberObjOrType A PhoneNumber object, or a PhoneNumberType integer
856
     * @param int|null $countryCallingCode Used when passing a PhoneNumberType
857
     * @return bool
858
     */
859 21
    public function isNumberGeographical($phoneNumberObjOrType, $countryCallingCode = null)
860
    {
861 21
        if ($phoneNumberObjOrType instanceof PhoneNumber) {
862 1
            return $this->isNumberGeographical($this->getNumberType($phoneNumberObjOrType), $phoneNumberObjOrType->getCountryCode());
863
        }
864
865 21
        return $phoneNumberObjOrType == PhoneNumberType::FIXED_LINE
866 17
        || $phoneNumberObjOrType == PhoneNumberType::FIXED_LINE_OR_MOBILE
867 12
        || (in_array($countryCallingCode, static::$GEO_MOBILE_COUNTRIES)
868 21
            && $phoneNumberObjOrType == PhoneNumberType::MOBILE);
869
    }
870
871
    /**
872
     * Gets the type of a phone number.
873
     * @param PhoneNumber $number the number the phone number that we want to know the type
874
     * @return int PhoneNumberType the type of the phone number
875
     */
876 1369
    public function getNumberType(PhoneNumber $number)
877
    {
878 1369
        $regionCode = $this->getRegionCodeForNumber($number);
879 1369
        $metadata = $this->getMetadataForRegionOrCallingCode($number->getCountryCode(), $regionCode);
880 1369
        if ($metadata === null) {
881 8
            return PhoneNumberType::UNKNOWN;
882
        }
883 1368
        $nationalSignificantNumber = $this->getNationalSignificantNumber($number);
884 1368
        return $this->getNumberTypeHelper($nationalSignificantNumber, $metadata);
885
    }
886
887
    /**
888
     * @param int $countryCallingCode
889
     * @param string $regionCode
890
     * @return PhoneMetadata
891
     */
892 1923
    protected function getMetadataForRegionOrCallingCode($countryCallingCode, $regionCode)
893
    {
894 1923
        return static::REGION_CODE_FOR_NON_GEO_ENTITY === $regionCode ?
895 1923
            $this->getMetadataForNonGeographicalRegion($countryCallingCode) : $this->getMetadataForRegion($regionCode);
896
    }
897
898
    /**
899
     * @param int $countryCallingCode
900
     * @return PhoneMetadata
901
     */
902 31
    public function getMetadataForNonGeographicalRegion($countryCallingCode)
903
    {
904 31
        if (!isset($this->countryCallingCodeToRegionCodeMap[$countryCallingCode])) {
905 1
            return null;
906
        }
907 31
        return $this->metadataSource->getMetadataForNonGeographicalRegion($countryCallingCode);
908
    }
909
910
    /**
911
     * Gets the length of the national destination code (NDC) from the PhoneNumber object passed in,
912
     * so that clients could use it to split a national significant number into NDC and subscriber
913
     * number. The NDC of a phone number is normally the first group of digit(s) right after the
914
     * country calling code when the number is formatted in the international format, if there is a
915
     * subscriber number part that follows. An example of how this could be used:
916
     *
917
     * <code>
918
     * $phoneUtil = PhoneNumberUtil::getInstance();
919
     * $number = $phoneUtil->parse("18002530000", "US");
920
     * $nationalSignificantNumber = $phoneUtil->getNationalSignificantNumber($number);
921
     *
922
     * $nationalDestinationCodeLength = $phoneUtil->getLengthOfNationalDestinationCode($number);
923
     * if ($nationalDestinationCodeLength > 0) {
924
     *     $nationalDestinationCode = substr($nationalSignificantNumber, 0, $nationalDestinationCodeLength);
925
     *     $subscriberNumber = substr($nationalSignificantNumber, $nationalDestinationCodeLength);
926
     * } else {
927
     *     $nationalDestinationCode = "";
928
     *     $subscriberNumber = $nationalSignificantNumber;
929
     * }
930
     * </code>
931
     *
932
     * Refer to the unit tests to see the difference between this function and
933
     * {@link #getLengthOfGeographicalAreaCode}.
934
     *
935
     * @param PhoneNumber $number the PhoneNumber object for which clients want to know the length of the NDC.
936
     * @return int the length of NDC of the PhoneNumber object passed in.
937
     */
938 2
    public function getLengthOfNationalDestinationCode(PhoneNumber $number)
939
    {
940 2
        if ($number->hasExtension()) {
941
            // We don't want to alter the proto given to us, but we don't want to include the extension
942
            // when we format it, so we copy it and clear the extension here.
943
            $copiedProto = new PhoneNumber();
944
            $copiedProto->mergeFrom($number);
945
            $copiedProto->clearExtension();
946
        } else {
947 2
            $copiedProto = clone $number;
948
        }
949
950 2
        $nationalSignificantNumber = $this->format($copiedProto, PhoneNumberFormat::INTERNATIONAL);
951
952 2
        $numberGroups = preg_split('/' . static::NON_DIGITS_PATTERN . '/', $nationalSignificantNumber);
953
954
        // The pattern will start with "+COUNTRY_CODE " so the first group will always be the empty
955
        // string (before the + symbol) and the second group will be the country calling code. The third
956
        // group will be area code if it is not the last group.
957 2
        if (count($numberGroups) <= 3) {
958 1
            return 0;
959
        }
960
961 2
        if ($this->getNumberType($number) == PhoneNumberType::MOBILE) {
962
            // For example Argentinian mobile numbers, when formatted in the international format, are in
963
            // the form of +54 9 NDC XXXX.... As a result, we take the length of the third group (NDC) and
964
            // add the length of the second group (which is the mobile token), which also forms part of
965
            // the national significant number. This assumes that the mobile token is always formatted
966
            // separately from the rest of the phone number.
967
968 2
            $mobileToken = static::getCountryMobileToken($number->getCountryCode());
969 2
            if ($mobileToken !== "") {
970 2
                return mb_strlen($numberGroups[2]) + mb_strlen($numberGroups[3]);
971
            }
972
        }
973 2
        return mb_strlen($numberGroups[2]);
974
    }
975
976
    /**
977
     * Formats a phone number in the specified format using default rules. Note that this does not
978
     * promise to produce a phone number that the user can dial from where they are - although we do
979
     * format in either 'national' or 'international' format depending on what the client asks for, we
980
     * do not currently support a more abbreviated format, such as for users in the same "area" who
981
     * could potentially dial the number without area code. Note that if the phone number has a
982
     * country calling code of 0 or an otherwise invalid country calling code, we cannot work out
983
     * which formatting rules to apply so we return the national significant number with no formatting
984
     * applied.
985
     *
986
     * @param PhoneNumber $number the phone number to be formatted
987
     * @param int $numberFormat the PhoneNumberFormat the phone number should be formatted into
988
     * @return string the formatted phone number
989
     */
990 290
    public function format(PhoneNumber $number, $numberFormat)
991
    {
992 290
        if ($number->getNationalNumber() == 0 && $number->hasRawInput()) {
993
            // Unparseable numbers that kept their raw input just use that.
994
            // This is the only case where a number can be formatted as E164 without a
995
            // leading '+' symbol (but the original number wasn't parseable anyway).
996
            // TODO: Consider removing the 'if' above so that unparseable
997
            // strings without raw input format to the empty string instead of "+00"
998 1
            $rawInput = $number->getRawInput();
999 1
            if (mb_strlen($rawInput) > 0) {
1000 1
                return $rawInput;
1001
            }
1002
        }
1003
1004 290
        $formattedNumber = "";
1005 290
        $countryCallingCode = $number->getCountryCode();
1006 290
        $nationalSignificantNumber = $this->getNationalSignificantNumber($number);
1007
1008 290
        if ($numberFormat == PhoneNumberFormat::E164) {
1009
            // Early exit for E164 case (even if the country calling code is invalid) since no formatting
1010
            // of the national number needs to be applied. Extensions are not formatted.
1011 266
            $formattedNumber .= $nationalSignificantNumber;
1012 266
            $this->prefixNumberWithCountryCallingCode($countryCallingCode, PhoneNumberFormat::E164, $formattedNumber);
1013 266
            return $formattedNumber;
1014
        }
1015
1016 42
        if (!$this->hasValidCountryCallingCode($countryCallingCode)) {
1017 1
            $formattedNumber .= $nationalSignificantNumber;
1018 1
            return $formattedNumber;
1019
        }
1020
1021
        // Note getRegionCodeForCountryCode() is used because formatting information for regions which
1022
        // share a country calling code is contained by only one region for performance reasons. For
1023
        // example, for NANPA regions it will be contained in the metadata for US.
1024 42
        $regionCode = $this->getRegionCodeForCountryCode($countryCallingCode);
1025
        // Metadata cannot be null because the country calling code is valid (which means that the
1026
        // region code cannot be ZZ and must be one of our supported region codes).
1027 42
        $metadata = $this->getMetadataForRegionOrCallingCode($countryCallingCode, $regionCode);
1028 42
        $formattedNumber .= $this->formatNsn($nationalSignificantNumber, $metadata, $numberFormat);
0 ignored issues
show
Bug introduced by
It seems like $metadata defined by $this->getMetadataForReg...llingCode, $regionCode) on line 1027 can be null; however, libphonenumber\PhoneNumberUtil::formatNsn() does not accept null, maybe add an additional type check?

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

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

function doesNotAcceptNull(stdClass $x) { }

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

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

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

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

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

function doesNotAcceptNull(stdClass $x) { }

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

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

// Safe - Alternative 2
function withCheck2() {
    $x = mayReturnNull();
    if ($x instanceof stdClass) {
        doesNotAcceptNull($x);
    }
}
Loading history...
2214
            PhoneNumberFormat::NATIONAL,
2215
            $carrierCode
2216
        );
2217
        $this->maybeAppendFormattedExtension($number, $metadata, PhoneNumberFormat::NATIONAL, $formattedNumber);
2218
        $this->prefixNumberWithCountryCallingCode(
2219 1
            $countryCallingCode,
2220
            PhoneNumberFormat::NATIONAL,
2221 1
            $formattedNumber
2222
        );
2223
        return $formattedNumber;
2224
    }
2225
2226 1
    /**
2227 1
     * Formats a phone number in national format for dialing using the carrier as specified in the
2228 1
     * preferredDomesticCarrierCode field of the PhoneNumber object passed in. If that is missing,
2229
     * use the {@code fallbackCarrierCode} passed in instead. If there is no
2230
     * {@code preferredDomesticCarrierCode}, and the {@code fallbackCarrierCode} contains an empty
2231
     * string, return the number in national format without any carrier code.
2232
     *
2233
     * <p>Use {@link #formatNationalNumberWithCarrierCode} instead if the carrier code passed in
2234
     * should take precedence over the number's {@code preferredDomesticCarrierCode} when formatting.
2235
     *
2236
     * @param PhoneNumber $number the phone number to be formatted
2237
     * @param string $fallbackCarrierCode the carrier selection code to be used, if none is found in the
2238
     *     phone number itself
2239
     * @return string the formatted phone number in national format for dialing using the number's
2240
     *     {@code preferredDomesticCarrierCode}, or the {@code fallbackCarrierCode} passed in if
2241 35
     *     none is found
2242
     */
2243 35
    public function formatNationalNumberWithPreferredCarrierCode(PhoneNumber $number, $fallbackCarrierCode)
2244 35
    {
2245
        return $this->formatNationalNumberWithCarrierCode(
2246
            $number,
2247 2
            // Historically, we set this to an empty string when parsing with raw input if none was
2248
            // found in the input string. However, this doesn't result in a number we can dial. For this
2249 35
            // reason, we treat the empty string the same as if it isn't set at all.
2250 35
            mb_strlen($number->getPreferredDomesticCarrierCode()) > 0
2251
                ? $number->getPreferredDomesticCarrierCode()
2252
                : $fallbackCarrierCode
2253
        );
2254
    }
2255
2256
    /**
2257
     * Returns true if the number can be dialled from outside the region, or unknown. If the number
2258
     * can only be dialled from within the region, returns false. Does not check the number is a valid
2259
     * number.
2260 4
     * TODO: Make this method public when we have enough metadata to make it worthwhile.
2261
     *
2262 4
     * @param PhoneNumber $number the phone-number for which we want to know whether it is diallable from outside the region
2263 1
     * @return bool
2264
     */
2265
    public function canBeInternationallyDialled(PhoneNumber $number)
2266 4
    {
2267
        $metadata = $this->getMetadataForRegion($this->getRegionCodeForNumber($number));
2268
        if ($metadata === null) {
2269
            // Note numbers belonging to non-geographical entities (e.g. +800 numbers) are always
2270
            // internationally diallable, and will be caught here.
2271
            return true;
2272
        }
2273
        $nationalSignificantNumber = $this->getNationalSignificantNumber($number);
2274
        return !$this->isNumberMatchingDesc($nationalSignificantNumber, $metadata->getNoInternationalDialling());
2275
    }
2276
2277
    /**
2278
     * Normalizes a string of characters representing a phone number. This strips all characters which
2279
     * are not diallable on a mobile phone keypad (including all non-ASCII digits).
2280
     *
2281
     * @param string $number a string of characters representing a phone number
2282
     * @return string the normalized string version of the phone number
2283
     */
2284
    public static function normalizeDiallableCharsOnly($number)
2285
    {
2286
        if (count(static::$DIALLABLE_CHAR_MAPPINGS) === 0) {
2287
            static::initDiallableCharMappings();
2288
        }
2289
2290
        return static::normalizeHelper($number, static::$DIALLABLE_CHAR_MAPPINGS, true /* remove non matches */);
2291
    }
2292
2293 1
    /**
2294
     * Formats a phone number for out-of-country dialing purposes.
2295 1
     *
2296
     * Note that in this version, if the number was entered originally using alpha characters and
2297
     * this version of the number is stored in raw_input, this representation of the number will be
2298 1
     * used rather than the digit representation. Grouping information, as specified by characters
2299 1
     * such as "-" and " ", will be retained.
2300
     *
2301 1
     * <p><b>Caveats:</b></p>
2302 1
     * <ul>
2303 1
     *  <li> This will not produce good results if the country calling code is both present in the raw
2304
     *       input _and_ is the start of the national number. This is not a problem in the regions
2305
     *       which typically use alpha numbers.
2306
     *  <li> This will also not produce good results if the raw input has any grouping information
2307
     *       within the first three digits of the national number, and if the function needs to strip
2308
     *       preceding digits/words in the raw input before these digits. Normally people group the
2309 1
     *       first three digits together so this is not a huge problem - and will be fixed if it
2310
     *       proves to be so.
2311
     * </ul>
2312
     *
2313
     * @param PhoneNumber $number the phone number that needs to be formatted
2314 1
     * @param String $regionCallingFrom the region where the call is being placed
2315 1
     * @return String the formatted phone number
2316 1
     */
2317 1
    public function formatOutOfCountryKeepingAlphaChars(PhoneNumber $number, $regionCallingFrom)
2318 1
    {
2319
        $rawInput = $number->getRawInput();
2320
        // If there is no raw input, then we can't keep alpha characters because there aren't any.
2321 1
        // In this case, we return formatOutOfCountryCallingNumber.
2322 1
        if (mb_strlen($rawInput) == 0) {
2323 1
            return $this->formatOutOfCountryCallingNumber($number, $regionCallingFrom);
2324 1
        }
2325
        $countryCode = $number->getCountryCode();
2326 1
        if (!$this->hasValidCountryCallingCode($countryCode)) {
2327 1
            return $rawInput;
2328
        }
2329
        // Strip any prefix such as country calling code, IDD, that was present. We do this by comparing
2330 1
        // the number in raw_input with the parsed number.
2331 1
        // To do this, first we normalize punctuation. We retain number grouping symbols such as " "
2332
        // only.
2333
        $rawInput = $this->normalizeHelper($rawInput, static::$ALL_PLUS_NUMBER_GROUPING_SYMBOLS, true);
2334 1
        // Now we trim everything before the first three digits in the parsed number. We choose three
2335
        // because all valid alpha numbers have 3 digits at the start - if it does not, then we don't
2336 1
        // trim anything at all. Similarly, if the national number was less than three digits, we don't
2337
        // trim anything at all.
2338 1
        $nationalNumber = $this->getNationalSignificantNumber($number);
2339 1
        if (mb_strlen($nationalNumber) > 3) {
2340
            $firstNationalNumberDigit = strpos($rawInput, substr($nationalNumber, 0, 3));
2341 1
            if ($firstNationalNumberDigit !== false) {
2342
                $rawInput = substr($rawInput, $firstNationalNumberDigit);
2343 1
            }
2344
        }
2345
        $metadataForRegionCallingFrom = $this->getMetadataForRegion($regionCallingFrom);
2346
        if ($countryCode == static::NANPA_COUNTRY_CODE) {
2347
            if ($this->isNANPACountry($regionCallingFrom)) {
2348
                return $countryCode . " " . $rawInput;
2349 1
            }
2350
        } elseif ($metadataForRegionCallingFrom !== null &&
2351 1
            $countryCode == $this->getCountryCodeForValidRegion($regionCallingFrom)
2352
        ) {
2353
            $formattingPattern =
2354
                $this->chooseFormattingPatternForNumber(
2355 1
                    $metadataForRegionCallingFrom->numberFormats(),
2356 1
                    $nationalNumber
2357 1
                );
2358
            if ($formattingPattern === null) {
2359 1
                // If no pattern above is matched, we format the original input.
2360 1
                return $rawInput;
2361 1
            }
2362
            $newFormat = new NumberFormat();
2363 1
            $newFormat->mergeFrom($formattingPattern);
2364 1
            // The first group is the first group of digits that the user wrote together.
2365
            $newFormat->setPattern("(\\d+)(.*)");
2366 1
            // Here we just concatenate them back together after the national prefix has been fixed.
2367 1
            $newFormat->setFormat("$1$2");
2368
            // Now we format using this pattern instead of the default pattern, but with the national
2369
            // prefix prefixed if necessary.
2370 1
            // This will not work in the cases where the pattern (and not the leading digits) decide
2371
            // whether a national prefix needs to be used, since we have overridden the pattern to match
2372
            // anything, but that is not the case in the metadata to date.
2373 1
            return $this->formatNsnUsingPattern($rawInput, $newFormat, PhoneNumberFormat::NATIONAL);
2374 1
        }
2375
        $internationalPrefixForFormatting = "";
2376
        // If an unsupported region-calling-from is entered, or a country with multiple international
2377
        // prefixes, the international format of the number is returned, unless there is a preferred
2378 1
        // international prefix.
2379
        if ($metadataForRegionCallingFrom !== null) {
2380 1
            $internationalPrefix = $metadataForRegionCallingFrom->getInternationalPrefix();
2381
            $uniqueInternationalPrefixMatcher = new Matcher(static::UNIQUE_INTERNATIONAL_PREFIX, $internationalPrefix);
2382
            $internationalPrefixForFormatting =
2383
                $uniqueInternationalPrefixMatcher->matches()
2384 1
                    ? $internationalPrefix
2385
                    : $metadataForRegionCallingFrom->getPreferredInternationalPrefix();
2386
        }
2387
        $formattedNumber = $rawInput;
2388
        $regionCode = $this->getRegionCodeForCountryCode($countryCode);
2389
        // Metadata cannot be null because the country calling code is valid.
2390
        $metadataForRegion = $this->getMetadataForRegionOrCallingCode($countryCode, $regionCode);
2391
        $this->maybeAppendFormattedExtension(
2392
            $number,
2393
            $metadataForRegion,
2394
            PhoneNumberFormat::INTERNATIONAL,
2395
            $formattedNumber
2396
        );
2397
        if (mb_strlen($internationalPrefixForFormatting) > 0) {
2398
            $formattedNumber = $internationalPrefixForFormatting . " " . $countryCode . " " . $formattedNumber;
2399
        } else {
2400
            // Invalid region entered as country-calling-from (so no metadata was found for it) or the
2401
            // region chosen has multiple international dialling prefixes.
2402
            $this->prefixNumberWithCountryCallingCode(
2403
                $countryCode,
2404 8
                PhoneNumberFormat::INTERNATIONAL,
2405
                $formattedNumber
2406 8
            );
2407 1
        }
2408
        return $formattedNumber;
2409 7
    }
2410 7
2411 7
    /**
2412
     * Formats a phone number for out-of-country dialing purposes. If no regionCallingFrom is
2413
     * supplied, we format the number in its INTERNATIONAL format. If the country calling code is the
2414 7
     * same as that of the region where the number is from, then NATIONAL formatting will be applied.
2415 4
     *
2416
     * <p>If the number itself has a country calling code of zero or an otherwise invalid country
2417
     * calling code, then we return the number with no formatting applied.
2418 4
     *
2419
     * <p>Note this function takes care of the case for calling inside of NANPA and between Russia and
2420 6
     * Kazakhstan (who share the same country calling code). In those cases, no international prefix
2421
     * is used. For regions which have multiple international prefixes, the number in its
2422
     * INTERNATIONAL format will be returned instead.
2423
     *
2424
     * @param PhoneNumber $number the phone number to be formatted
2425
     * @param string $regionCallingFrom the region where the call is being placed
2426
     * @return string  the formatted phone number
2427 2
     */
2428
    public function formatOutOfCountryCallingNumber(PhoneNumber $number, $regionCallingFrom)
2429
    {
2430 7
        if (!$this->isValidRegionCode($regionCallingFrom)) {
2431
            return $this->format($number, PhoneNumberFormat::INTERNATIONAL);
2432 7
        }
2433
        $countryCallingCode = $number->getCountryCode();
2434
        $nationalSignificantNumber = $this->getNationalSignificantNumber($number);
2435
        if (!$this->hasValidCountryCallingCode($countryCallingCode)) {
2436 7
            return $nationalSignificantNumber;
2437 7
        }
2438
        if ($countryCallingCode == static::NANPA_COUNTRY_CODE) {
2439 7
            if ($this->isNANPACountry($regionCallingFrom)) {
2440 6
                // For NANPA regions, return the national format for these regions but prefix it with the
2441 3
                // country calling code.
2442 3
                return $countryCallingCode . " " . $this->format($number, PhoneNumberFormat::NATIONAL);
2443
            }
2444
        } elseif ($countryCallingCode == $this->getCountryCodeForValidRegion($regionCallingFrom)) {
2445 7
            // If regions share a country calling code, the country calling code need not be dialled.
2446
            // This also applies when dialling within a region, so this if clause covers both these cases.
2447 7
            // Technically this is the case for dialling from La Reunion to other overseas departments of
2448 7
            // France (French Guiana, Martinique, Guadeloupe), but not vice versa - so we don't cover this
2449
            // edge case for now and for those cases return the version including country calling code.
2450
            // Details here: http://www.petitfute.com/voyage/225-info-pratiques-reunion
2451 7
            return $this->format($number, PhoneNumberFormat::NATIONAL);
2452
        }
2453 7
        // Metadata cannot be null because we checked 'isValidRegionCode()' above.
2454 7
        $metadataForRegionCallingFrom = $this->getMetadataForRegion($regionCallingFrom);
2455
2456
        $internationalPrefix = $metadataForRegionCallingFrom->getInternationalPrefix();
2457 7
2458
        // For regions that have multiple international prefixes, the international format of the
2459
        // number is returned, unless there is a preferred international prefix.
2460 7
        $internationalPrefixForFormatting = "";
2461 7
        $uniqueInternationalPrefixMatcher = new Matcher(static::UNIQUE_INTERNATIONAL_PREFIX, $internationalPrefix);
2462
2463 1
        if ($uniqueInternationalPrefixMatcher->matches()) {
2464
            $internationalPrefixForFormatting = $internationalPrefix;
2465 1
        } elseif ($metadataForRegionCallingFrom->hasPreferredInternationalPrefix()) {
2466
            $internationalPrefixForFormatting = $metadataForRegionCallingFrom->getPreferredInternationalPrefix();
2467
        }
2468
2469 7
        $regionCode = $this->getRegionCodeForCountryCode($countryCallingCode);
2470
        // Metadata cannot be null because the country calling code is valid.
2471
        $metadataForRegion = $this->getMetadataForRegionOrCallingCode($countryCallingCode, $regionCode);
2472
        $formattedNationalNumber = $this->formatNsn(
2473
            $nationalSignificantNumber,
2474
            $metadataForRegion,
0 ignored issues
show
Bug introduced by
It seems like $metadataForRegion defined by $this->getMetadataForReg...llingCode, $regionCode) on line 2471 can be null; however, libphonenumber\PhoneNumberUtil::formatNsn() does not accept null, maybe add an additional type check?

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

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

function doesNotAcceptNull(stdClass $x) { }

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

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

// Safe - Alternative 2
function withCheck2() {
    $x = mayReturnNull();
    if ($x instanceof stdClass) {
        doesNotAcceptNull($x);
    }
}
Loading history...
2475
            PhoneNumberFormat::INTERNATIONAL
2476
        );
2477 5
        $formattedNumber = $formattedNationalNumber;
2478
        $this->maybeAppendFormattedExtension(
2479 5
            $number,
2480
            $metadataForRegion,
2481
            PhoneNumberFormat::INTERNATIONAL,
2482
            $formattedNumber
2483
        );
2484
        if (mb_strlen($internationalPrefixForFormatting) > 0) {
2485
            $formattedNumber = $internationalPrefixForFormatting . " " . $countryCallingCode . " " . $formattedNumber;
2486
        } else {
2487
            $this->prefixNumberWithCountryCallingCode(
2488
                $countryCallingCode,
2489
                PhoneNumberFormat::INTERNATIONAL,
2490
                $formattedNumber
2491
            );
2492
        }
2493
        return $formattedNumber;
2494
    }
2495
2496
    /**
2497
     * Checks if this is a region under the North American Numbering Plan Administration (NANPA).
2498 1
     * @param string $regionCode
2499
     * @return boolean true if regionCode is one of the regions under NANPA
2500 1
     */
2501 1
    public function isNANPACountry($regionCode)
2502
    {
2503
        return in_array($regionCode, $this->nanpaRegions);
2504
    }
2505 1
2506
    /**
2507 1
     * Formats a phone number using the original phone number format that the number is parsed from.
2508 1
     * The original format is embedded in the country_code_source field of the PhoneNumber object
2509
     * passed in. If such information is missing, the number will be formatted into the NATIONAL
2510 1
     * format by default. When the number contains a leading zero and this is unexpected for this
2511 1
     * country, or we don't have a formatting pattern for the number, the method returns the raw input
2512 1
     * when it is available.
2513 1
     *
2514 1
     * Note this method guarantees no digit will be inserted, removed or modified as a result of
2515 1
     * formatting.
2516 1
     *
2517 1
     * @param PhoneNumber $number the phone number that needs to be formatted in its original number format
2518 1
     * @param string $regionCallingFrom the region whose IDD needs to be prefixed if the original number
2519 1
     *     has one
2520 1
     * @return string the formatted phone number in its original number format
2521
     */
2522
    public function formatInOriginalFormat(PhoneNumber $number, $regionCallingFrom)
2523
    {
2524 1
        if ($number->hasRawInput() &&
2525
            ($this->hasUnexpectedItalianLeadingZero($number) || !$this->hasFormattingPatternForNumber($number))
2526
        ) {
2527 1
            // We check if we have the formatting pattern because without that, we might format the number
2528 1
            // as a group without national prefix.
2529 1
            return $number->getRawInput();
2530
        }
2531
        if (!$number->hasCountryCodeSource()) {
2532 1
            return $this->format($number, PhoneNumberFormat::NATIONAL);
2533 1
        }
2534
        switch ($number->getCountryCodeSource()) {
2535
            case CountryCodeSource::FROM_NUMBER_WITH_PLUS_SIGN:
2536 1
                $formattedNumber = $this->format($number, PhoneNumberFormat::INTERNATIONAL);
2537 1
                break;
2538
            case CountryCodeSource::FROM_NUMBER_WITH_IDD:
2539
                $formattedNumber = $this->formatOutOfCountryCallingNumber($number, $regionCallingFrom);
2540
                break;
2541
            case CountryCodeSource::FROM_NUMBER_WITHOUT_PLUS_SIGN:
2542
                $formattedNumber = substr($this->format($number, PhoneNumberFormat::INTERNATIONAL), 1);
2543 1
                break;
2544 1
            case CountryCodeSource::FROM_DEFAULT_COUNTRY:
2545
                // Fall-through to default case.
2546
            default:
0 ignored issues
show
Coding Style introduced by
The default body in a switch statement must start on the line following the statement.

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

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


switch ($expr) {
    default:

        doSomething(); //wrong
        break;
}

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

Loading history...
2547
2548 1
                $regionCode = $this->getRegionCodeForCountryCode($number->getCountryCode());
2549 1
                // We strip non-digits from the NDD here, and from the raw input later, so that we can
2550 1
                // compare them easily.
2551
                $nationalPrefix = $this->getNddPrefixForRegion($regionCode, true /* strip non-digits */);
2552
                $nationalFormat = $this->format($number, PhoneNumberFormat::NATIONAL);
2553
                if ($nationalPrefix === null || mb_strlen($nationalPrefix) == 0) {
2554 1
                    // If the region doesn't have a national prefix at all, we can safely return the national
2555
                    // format without worrying about a national prefix being added.
2556
                    $formattedNumber = $nationalFormat;
2557
                    break;
2558
                }
2559
                // Otherwise, we check if the original number was entered with a national prefix.
2560
                if ($this->rawInputContainsNationalPrefix(
2561 1
                    $number->getRawInput(),
2562
                    $nationalPrefix,
2563 1
                    $regionCode
2564 1
                )
2565 1
                ) {
2566 1
                    // If so, we can safely return the national format.
2567
                    $formattedNumber = $nationalFormat;
2568 1
                    break;
2569 1
                }
2570 1
                // Metadata cannot be null here because getNddPrefixForRegion() (above) returns null if
2571
                // there is no metadata for the region.
2572
                $metadata = $this->getMetadataForRegion($regionCode);
2573
                $nationalNumber = $this->getNationalSignificantNumber($number);
2574
                $formatRule = $this->chooseFormattingPatternForNumber($metadata->numberFormats(), $nationalNumber);
2575
                // The format rule could still be null here if the national number was 0 and there was no
2576 1
                // raw input (this should not be possible for numbers generated by the phonenumber library
2577 1
                // as they would also not have a country calling code and we would have exited earlier).
2578 1
                if ($formatRule === null) {
2579 1
                    $formattedNumber = $nationalFormat;
2580 1
                    break;
2581 1
                }
2582 1
                // When the format we apply to this number doesn't contain national prefix, we can just
2583
                // return the national format.
2584 1
                // TODO: Refactor the code below with the code in isNationalPrefixPresentIfRequired.
2585
                $candidateNationalPrefixRule = $formatRule->getNationalPrefixFormattingRule();
2586
                // We assume that the first-group symbol will never be _before_ the national prefix.
2587 1
                $indexOfFirstGroup = strpos($candidateNationalPrefixRule, '$1');
2588 1
                if ($indexOfFirstGroup <= 0) {
2589 1
                    $formattedNumber = $nationalFormat;
2590 1
                    break;
2591 1
                }
2592
                $candidateNationalPrefixRule = substr($candidateNationalPrefixRule, 0, $indexOfFirstGroup);
2593
                $candidateNationalPrefixRule = static::normalizeDigitsOnly($candidateNationalPrefixRule);
2594 1
                if (mb_strlen($candidateNationalPrefixRule) == 0) {
2595
                    // National prefix not used when formatting this number.
2596
                    $formattedNumber = $nationalFormat;
2597
                    break;
2598
                }
2599
                // Otherwise, we need to remove the national prefix from our output.
2600
                $numFormatCopy = new NumberFormat();
2601
                $numFormatCopy->mergeFrom($formatRule);
2602
                $numFormatCopy->clearNationalPrefixFormattingRule();
2603 1
                $numberFormats = array();
2604
                $numberFormats[] = $numFormatCopy;
2605 1
                $formattedNumber = $this->formatByPattern($number, PhoneNumberFormat::NATIONAL, $numberFormats);
2606
                break;
2607
        }
2608
        $rawInput = $number->getRawInput();
2609
        // If no digit is inserted/removed/modified as a result of our formatting, we return the
2610
        // formatted phone number; otherwise we return the raw input the user entered.
2611
        if ($formattedNumber !== null && mb_strlen($rawInput) > 0) {
2612
            $normalizedFormattedNumber = static::normalizeDiallableCharsOnly($formattedNumber);
2613
            $normalizedRawInput = static::normalizeDiallableCharsOnly($rawInput);
2614
            if ($normalizedFormattedNumber != $normalizedRawInput) {
2615 2
                $formattedNumber = $rawInput;
2616
            }
2617 2
        }
2618
        return $formattedNumber;
2619 2
    }
2620
2621 2
    /**
2622 1
     * Returns true if a number is from a region whose national significant number couldn't contain a
2623
     * leading zero, but has the italian_leading_zero field set to true.
2624 2
     * @param PhoneNumber $number
2625
     * @return bool
2626
     */
2627
    protected function hasUnexpectedItalianLeadingZero(PhoneNumber $number)
2628
    {
2629
        return $number->isItalianLeadingZero() && !$this->isLeadingZeroPossible($number->getCountryCode());
2630
    }
2631 1
2632
    /**
2633 1
     * Checks whether the country calling code is from a region whose national significant number
2634 1
     * could contain a leading zero. An example of such a region is Italy. Returns false if no
2635 1
     * metadata for the country is found.
2636 1
     * @param int $countryCallingCode
2637
     * @return bool
2638
     */
2639 1
    public function isLeadingZeroPossible($countryCallingCode)
2640 1
    {
2641 1
        $mainMetadataForCallingCode = $this->getMetadataForRegionOrCallingCode(
2642
            $countryCallingCode,
2643
            $this->getRegionCodeForCountryCode($countryCallingCode)
2644
        );
2645
        if ($mainMetadataForCallingCode === null) {
2646
            return false;
2647
        }
2648
        return (bool)$mainMetadataForCallingCode->isLeadingZeroPossible();
2649
    }
2650
2651
    /**
2652
     * @param PhoneNumber $number
2653
     * @return bool
2654
     */
2655
    protected function hasFormattingPatternForNumber(PhoneNumber $number)
2656
    {
2657
        $countryCallingCode = $number->getCountryCode();
2658 3
        $phoneNumberRegion = $this->getRegionCodeForCountryCode($countryCallingCode);
2659
        $metadata = $this->getMetadataForRegionOrCallingCode($countryCallingCode, $phoneNumberRegion);
2660 3
        if ($metadata === null) {
2661 3
            return false;
2662 1
        }
2663
        $nationalNumber = $this->getNationalSignificantNumber($number);
2664 3
        $formatRule = $this->chooseFormattingPatternForNumber($metadata->numberFormats(), $nationalNumber);
2665
        return $formatRule !== null;
2666 3
    }
2667 1
2668
    /**
2669 3
     * Returns the national dialling prefix for a specific region. For example, this would be 1 for
2670
     * the United States, and 0 for New Zealand. Set stripNonDigits to true to strip symbols like "~"
2671
     * (which indicates a wait for a dialling tone) from the prefix returned. If no national prefix is
2672 3
     * present, we return null.
2673
     *
2674 3
     * <p>Warning: Do not use this method for do-your-own formatting - for some regions, the
2675
     * national dialling prefix is used only for certain types of numbers. Use the library's
2676
     * formatting functions to prefix the national prefix when required.
2677
     *
2678
     * @param string $regionCode the region that we want to get the dialling prefix for
2679
     * @param boolean $stripNonDigits true to strip non-digits from the national dialling prefix
2680
     * @return string the dialling prefix for the region denoted by regionCode
2681
     */
2682
    public function getNddPrefixForRegion($regionCode, $stripNonDigits)
2683
    {
2684
        $metadata = $this->getMetadataForRegion($regionCode);
2685 1
        if ($metadata === null) {
2686
            return null;
2687 1
        }
2688 1
        $nationalPrefix = $metadata->getNationalPrefix();
2689
        // If no national prefix was found, we return null.
2690
        if (mb_strlen($nationalPrefix) == 0) {
2691
            return null;
2692
        }
2693
        if ($stripNonDigits) {
2694 1
            // Note: if any other non-numeric symbols are ever used in national prefixes, these would have
2695 1
            // to be removed here as well.
2696
            $nationalPrefix = str_replace("~", "", $nationalPrefix);
2697
        }
2698
        return $nationalPrefix;
2699
    }
2700
2701 1
    /**
2702
     * Check if rawInput, which is assumed to be in the national format, has a national prefix. The
2703
     * national prefix is assumed to be in digits-only form.
2704
     * @param string $rawInput
2705
     * @param string $nationalPrefix
2706
     * @param string $regionCode
2707
     * @return bool
2708
     */
2709
    protected function rawInputContainsNationalPrefix($rawInput, $nationalPrefix, $regionCode)
2710
    {
2711
        $normalizedNationalNumber = static::normalizeDigitsOnly($rawInput);
2712
        if (strpos($normalizedNationalNumber, $nationalPrefix) === 0) {
2713
            try {
2714
                // Some Japanese numbers (e.g. 00777123) might be mistaken to contain the national prefix
2715 1844
                // when written without it (e.g. 0777123) if we just do prefix matching. To tackle that, we
2716
                // check the validity of the number if the assumed national prefix is removed (777123 won't
2717 1844
                // be valid in Japan).
2718 1844
                return $this->isValidNumber(
2719
                    $this->parse(substr($normalizedNationalNumber, mb_strlen($nationalPrefix)), $regionCode)
2720
                );
2721
            } catch (NumberParseException $e) {
2722
                return false;
2723
            }
2724
        }
2725
        return false;
2726
    }
2727
2728
    /**
2729
     * Tests whether a phone number matches a valid pattern. Note this doesn't verify the number
2730
     * is actually in use, which is impossible to tell by just looking at a number itself. It only
2731
     * verifies whether the parsed, canonicalised number is valid: not whether a particular series of
2732
     * digits entered by the user is diallable from the region provided when parsing. For example, the
2733
     * number +41 (0) 78 927 2696 can be parsed into a number with country code "41" and national
2734
     * significant number "789272696". This is valid, while the original string is not diallable.
2735
     *
2736
     * @param PhoneNumber $number the phone number that we want to validate
2737 1850
     * @return boolean that indicates whether the number is of a valid pattern
2738
     */
2739 1850
    public function isValidNumber(PhoneNumber $number)
2740 1850
    {
2741 1850
        $regionCode = $this->getRegionCodeForNumber($number);
2742 1827
        return $this->isValidNumberForRegion($number, $regionCode);
2743 1850
    }
2744
2745
    /**
2746
     * Tests whether a phone number is valid for a certain region. Note this doesn't verify the number
2747 31
     * is actually in use, which is impossible to tell by just looking at a number itself. If the
2748
     * country calling code is not the same as the country calling code for the region, this
2749 1826
     * immediately exits with false. After this, the specific number pattern rules for the region are
2750
     * examined. This is useful for determining for example whether a particular number is valid for
2751 1826
     * Canada, rather than just a valid NANPA number.
2752
     * Warning: In most cases, you want to use {@link #isValidNumber} instead. For example, this
2753
     * method will mark numbers from British Crown dependencies such as the Isle of Man as invalid for
2754
     * the region "GB" (United Kingdom), since it has its own region code, "IM", which may be
2755
     * undesirable.
2756
     *
2757
     * @param PhoneNumber $number the phone number that we want to validate
2758
     * @param string $regionCode the region that we want to validate the phone number for
2759
     * @return boolean that indicates whether the number is of a valid pattern
2760
     */
2761
    public function isValidNumberForRegion(PhoneNumber $number, $regionCode)
2762
    {
2763
        $countryCode = $number->getCountryCode();
2764
        $metadata = $this->getMetadataForRegionOrCallingCode($countryCode, $regionCode);
2765
        if (($metadata === null) ||
2766
            (static::REGION_CODE_FOR_NON_GEO_ENTITY !== $regionCode &&
2767
                $countryCode !== $this->getCountryCodeForValidRegion($regionCode))
2768
        ) {
2769
            // Either the region code was invalid, or the country calling code for this number does not
2770
            // match that of the region code.
2771
            return false;
2772
        }
2773
        $nationalSignificantNumber = $this->getNationalSignificantNumber($number);
2774
2775
        return $this->getNumberTypeHelper($nationalSignificantNumber, $metadata) != PhoneNumberType::UNKNOWN;
2776
    }
2777
2778
    /**
2779
     * Parses a string and returns it as a phone number in proto buffer format. The method is quite
2780
     * lenient and looks for a number in the input text (raw input) and does not check whether the
2781
     * string is definitely only a phone number. To do this, it ignores punctuation and white-space,
2782
     * as well as any text before the number (e.g. a leading “Tel: ”) and trims the non-number bits.
2783 2789
     * It will accept a number in any format (E164, national, international etc), assuming it can
2784
     * interpreted with the defaultRegion supplied. It also attempts to convert any alpha characters
2785 2789
     * into digits if it thinks this is a vanity number of the type "1800 MICROSOFT".
2786 2789
     *
2787
     * <p> This method will throw a {@link NumberParseException} if the number is not considered to
2788 2789
     * be a possible number. Note that validation of whether the number is actually a valid number
2789 2784
     * for a particular region is not performed. This can be done separately with {@link #isValidnumber}.
2790
     *
2791
     * @param string $numberToParse number that we are attempting to parse. This can contain formatting
2792
     *                          such as +, ( and -, as well as a phone number extension.
2793
     * @param string $defaultRegion region that we are expecting the number to be from. This is only used
2794
     *                          if the number being parsed is not written in international format.
2795
     *                          The country_code for the number in this case would be stored as that
2796
     *                          of the default region supplied. If the number is guaranteed to
2797
     *                          start with a '+' followed by the country calling code, then
2798
     *                          "ZZ" or null can be supplied.
2799
     * @param PhoneNumber|null $phoneNumber
2800
     * @param bool $keepRawInput
2801
     * @return PhoneNumber a phone number proto buffer filled with the parsed number
2802
     * @throws NumberParseException  if the string is not considered to be a viable phone number (e.g.
2803 2
     *                               too few or too many digits) or if no default region was supplied
2804
     *                               and the number is not in international format (does not start
2805 2
     *                               with +)
2806 2
     */
2807 2
    public function parse($numberToParse, $defaultRegion, PhoneNumber $phoneNumber = null, $keepRawInput = false)
2808
    {
2809
        if ($phoneNumber === null) {
2810
            $phoneNumber = new PhoneNumber();
2811
        }
2812
        $this->parseHelper($numberToParse, $defaultRegion, $keepRawInput, true, $phoneNumber);
2813 2
        return $phoneNumber;
2814
    }
2815 2
2816
    /**
2817 2
     * Formats a phone number in the specified format using client-defined formatting rules. Note that
2818
     * if the phone number has a country calling code of zero or an otherwise invalid country calling
2819 2
     * code, we cannot work out things like whether there should be a national prefix applied, or how
2820 2
     * to format extensions, so we return the national significant number with no formatting applied.
2821
     *
2822
     * @param PhoneNumber $number the phone number to be formatted
2823
     * @param int $numberFormat the format the phone number should be formatted into
2824 2
     * @param array $userDefinedFormats formatting rules specified by clients
2825
     * @return String the formatted phone number
2826
     */
2827
    public function formatByPattern(PhoneNumber $number, $numberFormat, array $userDefinedFormats)
2828 2
    {
2829 2
        $countryCallingCode = $number->getCountryCode();
2830 2
        $nationalSignificantNumber = $this->getNationalSignificantNumber($number);
2831 1
        if (!$this->hasValidCountryCallingCode($countryCallingCode)) {
2832 1
            return $nationalSignificantNumber;
2833
        }
2834 1
        // Note getRegionCodeForCountryCode() is used because formatting information for regions which
2835 1
        // share a country calling code is contained by only one region for performance reasons. For
2836 1
        // example, for NANPA regions it will be contained in the metadata for US.
2837 1
        $regionCode = $this->getRegionCodeForCountryCode($countryCallingCode);
2838 1
        // Metadata cannot be null because the country calling code is valid
2839
        $metadata = $this->getMetadataForRegionOrCallingCode($countryCallingCode, $regionCode);
2840
2841 1
        $formattedNumber = "";
2842
2843
        $formattingPattern = $this->chooseFormattingPatternForNumber($userDefinedFormats, $nationalSignificantNumber);
2844 2
        if ($formattingPattern === null) {
2845
            // If no pattern above is matched, we format the number as a whole.
2846 2
            $formattedNumber .= $nationalSignificantNumber;
2847 2
        } else {
2848 2
            $numFormatCopy = new NumberFormat();
2849
            // Before we do a replacement of the national prefix pattern $NP with the national prefix, we
2850
            // need to copy the rule so that subsequent replacements for different numbers have the
2851
            // appropriate national prefix.
2852
            $numFormatCopy->mergeFrom($formattingPattern);
2853
            $nationalPrefixFormattingRule = $formattingPattern->getNationalPrefixFormattingRule();
2854
            if (mb_strlen($nationalPrefixFormattingRule) > 0) {
2855
                $nationalPrefix = $metadata->getNationalPrefix();
2856
                if (mb_strlen($nationalPrefix) > 0) {
2857
                    // Replace $NP with national prefix and $FG with the first group ($1).
2858
                    $npPatternMatcher = new Matcher(static::NP_PATTERN, $nationalPrefixFormattingRule);
2859 247
                    $nationalPrefixFormattingRule = $npPatternMatcher->replaceFirst($nationalPrefix);
2860
                    $fgPatternMatcher = new Matcher(static::FG_PATTERN, $nationalPrefixFormattingRule);
2861 247
                    $nationalPrefixFormattingRule = $fgPatternMatcher->replaceFirst("\\$1");
2862
                    $numFormatCopy->setNationalPrefixFormattingRule($nationalPrefixFormattingRule);
2863
                } else {
2864
                    // We don't want to have a rule for how to format the national prefix if there isn't one.
2865
                    $numFormatCopy->clearNationalPrefixFormattingRule();
2866
                }
2867
            }
2868
            $formattedNumber .= $this->formatNsnUsingPattern($nationalSignificantNumber, $numFormatCopy, $numberFormat);
2869
        }
2870
        $this->maybeAppendFormattedExtension($number, $metadata, $numberFormat, $formattedNumber);
2871
        $this->prefixNumberWithCountryCallingCode($countryCallingCode, $numberFormat, $formattedNumber);
2872
        return $formattedNumber;
2873
    }
2874
2875 244
    /**
2876
     * Gets a valid number for the specified region.
2877 244
     *
2878
     * @param string regionCode  the region for which an example number is needed
2879
     * @return PhoneNumber a valid fixed-line number for the specified region. Returns null when the metadata
2880
     *    does not contain such information, or the region 001 is passed in. For 001 (representing
2881
     *    non-geographical numbers), call {@link #getExampleNumberForNonGeoEntity} instead.
2882
     */
2883
    public function getExampleNumber($regionCode)
2884
    {
2885
        return $this->getExampleNumberForType($regionCode, PhoneNumberType::FIXED_LINE);
2886 244
    }
2887
2888 244
    /**
2889
     * Gets an invalid number for the specified region. This is useful for unit-testing purposes,
2890
     * where you want to test what will happen with an invalid number. Note that the number that is
2891
     * returned will always be able to be parsed and will have the correct country code. It may also
2892
     * be a valid *short* number/code for this region. Validity checking such numbers is handled with
2893 244
     * {@link ShortNumberInfo}.
2894
     *
2895
     * @param string $regionCode The region for which an example number is needed
2896
     * @return PhoneNumber|null An invalid number for the specified region. Returns null when an unsupported region
2897
     * or the region 001 (Earth) is passed in.
2898
     */
2899
    public function getInvalidExampleNumber($regionCode)
2900
    {
2901
        if (!$this->isValidRegionCode($regionCode)) {
2902
            return null;
2903
        }
2904
2905
        // We start off with a valid fixed-line number since every country supports this. Alternatively
2906 244
        // we could start with a different number type, since fixed-line numbers typically have a wide
2907 244
        // breadth of valid number lengths and we may have to make it very short before we get an
2908
        // invalid number.
2909 244
2910 244
        $desc = $this->getNumberDescByType($this->getMetadataForRegion($regionCode), PhoneNumberType::FIXED_LINE);
0 ignored issues
show
Bug introduced by
It seems like $this->getMetadataForRegion($regionCode) can be null; however, getNumberDescByType() does not accept null, maybe add an additional type check?

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

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

function doesNotAcceptNull(stdClass $x) { }

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

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

// Safe - Alternative 2
function withCheck2() {
    $x = mayReturnNull();
    if ($x instanceof stdClass) {
        doesNotAcceptNull($x);
    }
}
Loading history...
2911 244
2912
        if ($desc->getExampleNumber() == '') {
2913
            // This shouldn't happen; we have a test for this.
2914
            return null;
2915
        }
2916
2917
        $exampleNumber = $desc->getExampleNumber();
2918
2919
        // Try and make the number invalid. We do this by changing the length. We try reducing the
2920
        // length of the number, since currently no region has a number that is the same length as
2921
        // MIN_LENGTH_FOR_NSN. This is probably quicker than making the number longer, which is another
2922
        // alternative. We could also use the possible number pattern to extract the possible lengths of
2923
        // the number to make this faster, but this method is only for unit-testing so simplicity is
2924
        // preferred to performance.  We don't want to return a number that can't be parsed, so we check
2925
        // the number is long enough. We try all possible lengths because phone number plans often have
2926
        // overlapping prefixes so the number 123456 might be valid as a fixed-line number, and 12345 as
2927
        // a mobile number. It would be faster to loop in a different order, but we prefer numbers that
2928
        // look closer to real numbers (and it gives us a variety of different lengths for the resulting
2929
        // phone numbers - otherwise they would all be MIN_LENGTH_FOR_NSN digits long.)
2930
        for ($phoneNumberLength = mb_strlen($exampleNumber) - 1; $phoneNumberLength >= static::MIN_LENGTH_FOR_NSN; $phoneNumberLength--) {
2931
            $numberToTry = mb_substr($exampleNumber, 0, $phoneNumberLength);
2932
            try {
2933
                $possiblyValidNumber = $this->parse($numberToTry, $regionCode);
2934
                if (!$this->isValidNumber($possiblyValidNumber)) {
2935 3175
                    return $possiblyValidNumber;
2936
                }
2937 3175
            } catch (NumberParseException $e) {
2938
                // Shouldn't happen: we have already checked the length, we know example numbers have
2939
                // only valid digits, and we know the region code is fine.
2940
            }
2941 11
        }
2942 11
        // We have a test to check that this doesn't happen for any of our supported regions.
2943 11
        return null;
2944 11
    }
2945
2946
    /**
2947
     * Gets a valid number for the specified region and number type.
2948
     *
2949
     * @param string|int $regionCodeOrType the region for which an example number is needed
2950
     * @param int $type the PhoneNumberType of number that is needed
2951
     * @return PhoneNumber a valid number for the specified region and type. Returns null when the metadata
2952
     *     does not contain such information or if an invalid region or region 001 was entered.
2953
     *     For 001 (representing non-geographical numbers), call
2954
     *     {@link #getExampleNumberForNonGeoEntity} instead.
2955
     *
2956
     * If $regionCodeOrType is the only parameter supplied, then a valid number for the specified number type
2957
     * will be returned that may belong to any country.
2958
     */
2959
    public function getExampleNumberForType($regionCodeOrType, $type = null)
2960
    {
2961
        if ($regionCodeOrType !== null && $type === null) {
2962
            /*
2963 3175
             * Gets a valid number for the specified number type (it may belong to any country).
2964 1
             */
2965
            foreach ($this->getSupportedRegions() as $regionCode) {
2966 3175
                $exampleNumber = $this->getExampleNumberForType($regionCode, $regionCodeOrType);
2967
                if ($exampleNumber !== null) {
2968 3175
                    return $exampleNumber;
2969 3175
                }
2970
            }
2971
2972
            // If there wasn't an example number for a region, try the non-geographical entities
2973 1373
            foreach ($this->getSupportedGlobalNetworkCallingCodes() as $countryCallingCode) {
2974
                $desc = $this->getNumberDescByType($this->getMetadataForNonGeographicalRegion($countryCallingCode), $regionCodeOrType);
0 ignored issues
show
Bug introduced by
It seems like $this->getMetadataForNon...on($countryCallingCode) can be null; however, getNumberDescByType() does not accept null, maybe add an additional type check?

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

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

function doesNotAcceptNull(stdClass $x) { }

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

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

// Safe - Alternative 2
function withCheck2() {
    $x = mayReturnNull();
    if ($x instanceof stdClass) {
        doesNotAcceptNull($x);
    }
}
Loading history...
2975
                try {
2976
                    if ($desc->getExampleNumber() != '') {
2977
                        return $this->parse("+" . $countryCallingCode . $desc->getExampleNumber(), static::UNKNOWN_REGION);
2978
                    }
2979
                } catch (NumberParseException $e) {
2980
                    // noop
2981 3419
                }
2982
            }
2983
            // There are no example numbers of this type for any country in the library.
2984 3419
            return null;
2985 245
        }
2986 3174
2987 245
        // Check the region code is valid.
2988 2929
        if (!$this->isValidRegionCode($regionCodeOrType)) {
2989 246
            return null;
2990 2684
        }
2991 1948
        $desc = $this->getNumberDescByType($this->getMetadataForRegion($regionCodeOrType), $type);
0 ignored issues
show
Bug introduced by
It seems like $this->getMetadataForRegion($regionCodeOrType) can be null; however, getNumberDescByType() does not accept null, maybe add an additional type check?

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

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

function doesNotAcceptNull(stdClass $x) { }

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

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

// Safe - Alternative 2
function withCheck2() {
    $x = mayReturnNull();
    if ($x instanceof stdClass) {
        doesNotAcceptNull($x);
    }
}
Loading history...
2992 1214
        try {
2993 1470
            if ($desc->hasExampleNumber()) {
2994 245
                return $this->parse($desc->getExampleNumber(), $regionCodeOrType);
2995 1225
            }
2996 245
        } catch (NumberParseException $e) {
2997 980
            // noop
2998 245
        }
2999 735
        return null;
3000 245
    }
3001 490
3002 245
    /**
3003 245
     * @param PhoneMetadata $metadata
3004 245
     * @param int $type PhoneNumberType
3005
     * @return PhoneNumberDesc
3006
     */
3007
    protected function getNumberDescByType(PhoneMetadata $metadata, $type)
3008
    {
3009
        switch ($type) {
3010
            case PhoneNumberType::PREMIUM_RATE:
3011
                return $metadata->getPremiumRate();
3012
            case PhoneNumberType::TOLL_FREE:
3013
                return $metadata->getTollFree();
3014
            case PhoneNumberType::MOBILE:
3015
                return $metadata->getMobile();
3016
            case PhoneNumberType::FIXED_LINE:
3017
            case PhoneNumberType::FIXED_LINE_OR_MOBILE:
3018 10
                return $metadata->getFixedLine();
3019
            case PhoneNumberType::SHARED_COST:
3020 10
                return $metadata->getSharedCost();
3021 10
            case PhoneNumberType::VOIP:
3022
                return $metadata->getVoip();
3023
            case PhoneNumberType::PERSONAL_NUMBER:
3024
                return $metadata->getPersonalNumber();
3025
            case PhoneNumberType::PAGER:
3026
                return $metadata->getPager();
3027
            case PhoneNumberType::UAN:
3028 10
                return $metadata->getUan();
3029 10
            case PhoneNumberType::VOICEMAIL:
3030 10
                return $metadata->getVoicemail();
3031 10
            default:
3032 10
                return $metadata->getGeneralDesc();
3033 10
        }
3034 10
    }
3035
3036 10
    /**
3037
     * Gets a valid number for the specified country calling code for a non-geographical entity.
3038 10
     *
3039 10
     * @param int $countryCallingCode the country calling code for a non-geographical entity
3040
     * @return PhoneNumber a valid number for the non-geographical entity. Returns null when the metadata
3041 7
     *    does not contain such information, or the country calling code passed in does not belong
3042
     *    to a non-geographical entity.
3043
     */
3044
    public function getExampleNumberForNonGeoEntity($countryCallingCode)
3045
    {
3046
        $metadata = $this->getMetadataForNonGeographicalRegion($countryCallingCode);
3047
        if ($metadata !== null) {
3048
            // For geographical entities, fixed-line data is always present. However, for non-geographical
3049
            // entities, this is not the case, so we have to go through different types to find the
3050
            // example number. We don't check fixed-line or personal number since they aren't used by
3051
            // non-geographical entities (if this changes, a unit-test will catch this.)
3052
            /** @var PhoneNumberDesc[] $list */
3053
            $list = array(
3054
                $metadata->getMobile(),
3055
                $metadata->getTollFree(),
3056
                $metadata->getSharedCost(),
3057
                $metadata->getVoip(),
3058
                $metadata->getVoicemail(),
3059
                $metadata->getUan(),
3060
                $metadata->getPremiumRate(),
3061
            );
3062
            foreach ($list as $desc) {
3063
                try {
3064
                    if ($desc !== null && $desc->hasExampleNumber()) {
3065
                        return $this->parse('+' . $countryCallingCode . $desc->getExampleNumber(), self::UNKNOWN_REGION);
3066
                    }
3067
                } catch (NumberParseException $e) {
3068
                    // noop
3069
                }
3070
            }
3071 4
        }
3072
        return null;
3073 4
    }
3074
3075 4
3076 4
    /**
3077 3
     * Takes two phone numbers and compares them for equality.
3078 3
     *
3079
     * <p>Returns EXACT_MATCH if the country_code, NSN, presence of a leading zero
3080 3
     * for Italian numbers and any extension present are the same. Returns NSN_MATCH
3081 2
     * if either or both has no region specified, and the NSNs and extensions are
3082 3
     * the same. Returns SHORT_NSN_MATCH if either or both has no region specified,
3083 3
     * or the region specified is the same, and one NSN could be a shorter version
3084
     * of the other number. This includes the case where one has an extension
3085 3
     * specified, and the other does not. Returns NO_MATCH otherwise. For example,
3086 3
     * the numbers +1 345 657 1234 and 657 1234 are a SHORT_NSN_MATCH. The numbers
3087 3
     * +1 345 657 1234 and 345 657 are a NO_MATCH.
3088 3
     *
3089 3
     * @param $firstNumberIn PhoneNumber|string First number to compare. If it is a
3090
     * string it can contain formatting, and can have country calling code specified
3091
     * with + at the start.
3092
     * @param $secondNumberIn PhoneNumber|string Second number to compare. If it is a
3093
     * string it can contain formatting, and can have country calling code specified
3094
     * with + at the start.
3095
     * @throws \InvalidArgumentException
3096
     * @return int {MatchType} NOT_A_NUMBER, NO_MATCH,
3097 1
     */
3098
    public function isNumberMatch($firstNumberIn, $secondNumberIn)
3099 4
    {
3100
        if (is_string($firstNumberIn) && is_string($secondNumberIn)) {
3101
            try {
3102
                $firstNumberAsProto = $this->parse($firstNumberIn, static::UNKNOWN_REGION);
3103 4
                return $this->isNumberMatch($firstNumberAsProto, $secondNumberIn);
3104 2
            } catch (NumberParseException $e) {
3105 3
                if ($e->getErrorType() === NumberParseException::INVALID_COUNTRY_CODE) {
3106 3
                    try {
3107
                        $secondNumberAsProto = $this->parse($secondNumberIn, static::UNKNOWN_REGION);
3108
                        return $this->isNumberMatch($secondNumberAsProto, $firstNumberIn);
3109
                    } catch (NumberParseException $e2) {
3110 3
                        if ($e2->getErrorType() === NumberParseException::INVALID_COUNTRY_CODE) {
3111
                            try {
3112 3
                                $firstNumberProto = new PhoneNumber();
3113 3
                                $secondNumberProto = new PhoneNumber();
3114 3
                                $this->parseHelper($firstNumberIn, null, false, false, $firstNumberProto);
3115 3
                                $this->parseHelper($secondNumberIn, null, false, false, $secondNumberProto);
3116 1
                                return $this->isNumberMatch($firstNumberProto, $secondNumberProto);
3117
                            } catch (NumberParseException $e3) {
3118 2
                                // Fall through and return MatchType::NOT_A_NUMBER
3119
                            }
3120
                        }
3121
                    }
3122 1
                }
3123 1
            }
3124 1
            return MatchType::NOT_A_NUMBER;
3125
        }
3126
        if ($firstNumberIn instanceof PhoneNumber && is_string($secondNumberIn)) {
3127
            // First see if the second number has an implicit country calling code, by attempting to parse
3128
            // it.
3129
            try {
3130
                $secondNumberAsProto = $this->parse($secondNumberIn, static::UNKNOWN_REGION);
3131
                return $this->isNumberMatch($firstNumberIn, $secondNumberAsProto);
3132 4
            } catch (NumberParseException $e) {
3133
                if ($e->getErrorType() === NumberParseException::INVALID_COUNTRY_CODE) {
3134 4
                    // The second number has no country calling code. EXACT_MATCH is no longer possible.
3135 4
                    // We parse it as if the region was the same as that for the first number, and if
3136 4
                    // EXACT_MATCH is returned, we replace this with NSN_MATCH.
3137 4
                    $firstNumberRegion = $this->getRegionCodeForCountryCode($firstNumberIn->getCountryCode());
3138
                    try {
3139
                        if ($firstNumberRegion != static::UNKNOWN_REGION) {
3140
                            $secondNumberWithFirstNumberRegion = $this->parse($secondNumberIn, $firstNumberRegion);
3141 4
                            $match = $this->isNumberMatch($firstNumberIn, $secondNumberWithFirstNumberRegion);
3142 4
                            if ($match === MatchType::EXACT_MATCH) {
3143 4
                                return MatchType::NSN_MATCH;
3144 4
                            }
3145 4
                            return $match;
3146 4
                        } else {
3147 4
                            // If the first number didn't have a valid country calling code, then we parse the
3148 1
                            // second number without one as well.
3149
                            $secondNumberProto = new PhoneNumber();
3150
                            $this->parseHelper($secondNumberIn, null, false, false, $secondNumberProto);
3151 4
                            return $this->isNumberMatch($firstNumberIn, $secondNumberProto);
3152 1
                        }
3153
                    } catch (NumberParseException $e2) {
3154
                        // Fall-through to return NOT_A_NUMBER.
3155
                    }
3156 4
                }
3157 4
            }
3158
        }
3159 1
        if ($firstNumberIn instanceof PhoneNumber && $secondNumberIn instanceof PhoneNumber) {
3160
            // We only care about the fields that uniquely define a number, so we copy these across
3161
            // explicitly.
3162 4
            $firstNumber = self::copyCoreFieldsOnly($firstNumberIn);
3163 4
            $secondNumber = self::copyCoreFieldsOnly($secondNumberIn);
3164
3165 4
            // Early exit if both had extensions and these are different.
3166 4
            if ($firstNumber->hasExtension() && $secondNumber->hasExtension() &&
3167 2
                $firstNumber->getExtension() != $secondNumber->getExtension()
3168 2
            ) {
3169 2
                return MatchType::NO_MATCH;
3170
            }
3171
3172
            $firstNumberCountryCode = $firstNumber->getCountryCode();
3173
            $secondNumberCountryCode = $secondNumber->getCountryCode();
3174 1
            // Both had country_code specified.
3175
            if ($firstNumberCountryCode != 0 && $secondNumberCountryCode != 0) {
0 ignored issues
show
Bug introduced by
It seems like you are loosely comparing $firstNumberCountryCode of type integer|null to 0; this is ambiguous as not only 0 == 0 is true, but null == 0 is true, too. Consider using a strict comparison ===.
Loading history...
Bug introduced by
It seems like you are loosely comparing $secondNumberCountryCode of type integer|null to 0; this is ambiguous as not only 0 == 0 is true, but null == 0 is true, too. Consider using a strict comparison ===.
Loading history...
3176
                if ($firstNumber->equals($secondNumber)) {
3177 1
                    return MatchType::EXACT_MATCH;
3178
                } elseif ($firstNumberCountryCode == $secondNumberCountryCode &&
3179
                    $this->isNationalNumberSuffixOfTheOther($firstNumber, $secondNumber)
3180
                ) {
3181 3
                    // A SHORT_NSN_MATCH occurs if there is a difference because of the presence or absence of
3182
                    // an 'Italian leading zero', the presence or absence of an extension, or one NSN being a
3183 3
                    // shorter variant of the other.
3184 1
                    return MatchType::SHORT_NSN_MATCH;
3185
                }
3186 3
                // This is not a match.
3187 2
                return MatchType::NO_MATCH;
3188
            }
3189 1
            // Checks cases where one or both country_code fields were not specified. To make equality
3190
            // checks easier, we first set the country_code fields to be equal.
3191
            $firstNumber->setCountryCode($secondNumberCountryCode);
3192
            // If all else was the same, then this is an NSN_MATCH.
3193
            if ($firstNumber->equals($secondNumber)) {
3194
                return MatchType::NSN_MATCH;
3195
            }
3196
            if ($this->isNationalNumberSuffixOfTheOther($firstNumber, $secondNumber)) {
3197
                return MatchType::SHORT_NSN_MATCH;
3198
            }
3199
            return MatchType::NO_MATCH;
3200 3
        }
3201
        return MatchType::NOT_A_NUMBER;
3202 3
    }
3203 3
3204 3
    /**
3205 3
     * Returns true when one national number is the suffix of the other or both are the same.
3206
     * @param PhoneNumber $firstNumber
3207
     * @param PhoneNumber $secondNumber
3208 3
     * @return bool
3209
     */
3210 3
    protected function isNationalNumberSuffixOfTheOther(PhoneNumber $firstNumber, PhoneNumber $secondNumber)
3211 3
    {
3212 3
        $firstNumberNationalNumber = trim((string)$firstNumber->getNationalNumber());
3213
        $secondNumberNationalNumber = trim((string)$secondNumber->getNationalNumber());
3214
        return $this->stringEndsWithString($firstNumberNationalNumber, $secondNumberNationalNumber) ||
3215
        $this->stringEndsWithString($secondNumberNationalNumber, $firstNumberNationalNumber);
3216
    }
3217
3218
    protected function stringEndsWithString($hayStack, $needle)
3219
    {
3220
        $revNeedle = strrev($needle);
3221
        $revHayStack = strrev($hayStack);
3222
        return strpos($revHayStack, $revNeedle) === 0;
3223 3
    }
3224
3225 3
    /**
3226 3
     * Returns true if the supplied region supports mobile number portability. Returns false for
3227
     * invalid, unknown or regions that don't support mobile number portability.
3228
     *
3229
     * @param string $regionCode the region for which we want to know whether it supports mobile number
3230 3
     *                    portability or not.
3231
     * @return bool
3232
     */
3233
    public function isMobileNumberPortableRegion($regionCode)
3234
    {
3235
        $metadata = $this->getMetadataForRegion($regionCode);
3236
        if ($metadata === null) {
3237
            return false;
3238
        }
3239
3240
        return $metadata->isMobileNumberPortableRegion();
3241
    }
3242
3243
    /**
3244
     * Check whether a phone number is a possible number given a number in the form of a string, and
3245
     * the region where the number could be dialed from. It provides a more lenient check than
3246
     * {@link #isValidNumber}. See {@link #isPossibleNumber(PhoneNumber)} for details.
3247
     *
3248
     * <p>This method first parses the number, then invokes {@link #isPossibleNumber(PhoneNumber)}
3249
     * with the resultant PhoneNumber object.
3250
     *
3251
     * @param PhoneNumber|string $number the number that needs to be checked, in the form of a string
3252 2
     * @param string $regionDialingFrom the region that we are expecting the number to be dialed from.
3253
     *     Note this is different from the region where the number belongs.  For example, the number
3254 2
     *     +1 650 253 0000 is a number that belongs to US. When written in this form, it can be
3255
     *     dialed from any region. When it is written as 00 1 650 253 0000, it can be dialed from any
3256 2
     *     region which uses an international dialling prefix of 00. When it is written as
3257 2
     *     650 253 0000, it can only be dialed from within the US, and when written as 253 0000, it
3258 2
     *     can only be dialed from within a smaller area in the US (Mountain View, CA, to be more
3259 1
     *     specific).
3260 1
     * @return boolean true if the number is possible
3261
     */
3262
    public function isPossibleNumber($number, $regionDialingFrom = null)
3263 2
    {
3264
        if ($regionDialingFrom !== null && is_string($number)) {
3265
            try {
3266
                return $this->isPossibleNumberWithReason(
3267
                    $this->parse($number, $regionDialingFrom)
3268
                ) === ValidationResult::IS_POSSIBLE;
3269
            } catch (NumberParseException $e) {
3270
                return false;
3271
            }
3272
        } else {
3273
            return $this->isPossibleNumberWithReason($number) === ValidationResult::IS_POSSIBLE;
0 ignored issues
show
Bug introduced by
It seems like $number defined by parameter $number on line 3262 can also be of type string; however, libphonenumber\PhoneNumb...sibleNumberWithReason() does only seem to accept object<libphonenumber\PhoneNumber>, maybe add an additional type check?

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

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

An additional type check may prevent trouble.

Loading history...
3274
        }
3275
    }
3276
3277
3278
    /**
3279
     * Check whether a phone number is a possible number. It provides a more lenient check than
3280
     * {@link #isValidNumber} in the following sense:
3281
     * <ol>
3282
     * <li> It only checks the length of phone numbers. In particular, it doesn't check starting
3283
     *      digits of the number.
3284
     * <li> It doesn't attempt to figure out the type of the number, but uses general rules which
3285
     *      applies to all types of phone numbers in a region. Therefore, it is much faster than
3286
     *      isValidNumber.
3287
     * <li> For fixed line numbers, many regions have the concept of area code, which together with
3288
     *      subscriber number constitute the national significant number. It is sometimes okay to dial
3289 4
     *      the subscriber number only when dialing in the same area. This function will return
3290
     *      true if the subscriber-number-only version is passed in. On the other hand, because
3291 4
     *      isValidNumber validates using information on both starting digits (for fixed line
3292 4
     *      numbers, that would most likely be area codes) and length (obviously includes the
3293
     *      length of area codes for fixed line numbers), it will return false for the
3294
     *      subscriber-number-only version.
3295
     * </ol>
3296
     * @param PhoneNumber $number the number that needs to be checked
3297 4
     * @return int a ValidationResult object which indicates whether the number is possible
3298 1
     */
3299
    public function isPossibleNumberWithReason(PhoneNumber $number)
3300
    {
3301 4
        $nationalNumber = $this->getNationalSignificantNumber($number);
3302
        $countryCode = $number->getCountryCode();
3303 4
        // Note: For Russian Fed and NANPA numbers, we just use the rules from the default region (US or
3304
        // Russia) since the getRegionCodeForNumber will not work if the number is possible but not
3305 4
        // valid. This would need to be revisited if the possible number pattern ever differed between
3306
        // various regions within those plans.
3307
        if (!$this->hasValidCountryCallingCode($countryCode)) {
3308
            return ValidationResult::INVALID_COUNTRY_CODE;
3309
        }
3310
3311
        $regionCode = $this->getRegionCodeForCountryCode($countryCode);
3312
        // Metadata cannot be null because the country calling code is valid.
3313
        $metadata = $this->getMetadataForRegionOrCallingCode($countryCode, $regionCode);
3314
3315 1
        return $this->testNumberLength($nationalNumber, $metadata->getGeneralDesc());
3316
    }
3317 1
3318 1
    /**
3319
     * Attempts to extract a valid number from a phone number that is too long to be valid, and resets
3320 1
     * the PhoneNumber object passed in to that valid version. If no valid number could be extracted,
3321 1
     * the PhoneNumber object passed in will not be modified.
3322 1
     * @param PhoneNumber $number a PhoneNumber object which contains a number that is too long to be valid.
3323
     * @return boolean true if a valid phone number can be successfully extracted.
3324 1
     */
3325 1
    public function truncateTooLongNumber(PhoneNumber $number)
3326 1
    {
3327 1
        if ($this->isValidNumber($number)) {
3328
            return true;
3329 1
        }
3330 1
        $numberCopy = new PhoneNumber();
3331 1
        $numberCopy->mergeFrom($number);
3332
        $nationalNumber = $number->getNationalNumber();
3333
        do {
3334
            $nationalNumber = floor($nationalNumber / 10);
3335
            $numberCopy->setNationalNumber($nationalNumber);
3336
            if ($this->isPossibleNumberWithReason($numberCopy) == ValidationResult::TOO_SHORT || $nationalNumber == 0) {
3337
                return false;
3338
            }
3339
        } while (!$this->isValidNumber($numberCopy));
3340
        $number->setNationalNumber($nationalNumber);
3341
        return true;
3342
    }
3343
}
3344