Completed
Pull Request — master (#164)
by Joshua
16:09
created

PhoneNumberUtil::isValidNumberForRegion()   A

Complexity

Conditions 4
Paths 2

Size

Total Lines 16
Code Lines 9

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 2
CRAP Score 4

Importance

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