Completed
Pull Request — master (#131)
by
unknown
15:54
created

PhoneNumberUtil::maybeExtractCountryCode()   C

Complexity

Conditions 13
Paths 33

Size

Total Lines 81
Code Lines 52

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 22
CRAP Score 13

Importance

Changes 0
Metric Value
c 0
b 0
f 0
dl 0
loc 81
rs 5.0112
ccs 22
cts 22
cp 1
cc 13
eloc 52
nc 33
nop 5
crap 13

How to fix   Long Method    Complexity   

Long Method

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

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

Commonly applied refactorings include:

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

It seems like the type of the argument is not accepted by the function/method which you are calling.

In some cases, in particular if PHP’s automatic type-juggling kicks in this might be fine. In other cases, however this might be a bug.

We suggest to add an explicit type cast like in the following example:

function acceptsInteger($int) { }

$x = '123'; // string "123"

// Instead of
acceptsInteger($x);

// we recommend to use
acceptsInteger((integer) $x);
Loading history...
640
            return 0;
641
        }
642
643
        return $this->getLengthOfNationalDestinationCode($number);
644
    }
645
646
    /**
647
     * Returns the metadata for the given region code or {@code null} if the region code is invalid
648
     * or unknown.
649
     * @param string $regionCode
650
     * @return PhoneMetadata
651
     */
652 296
    public function getMetadataForRegion($regionCode)
653
    {
654
        if (!$this->isValidRegionCode($regionCode)) {
655 296
            return null;
656
        }
657
658
        return $this->metadataSource->getMetadataForRegion($regionCode);
659
    }
660
661
    /**
662
     * Helper function to check region code is not unknown or null.
663
     * @param string $regionCode
664
     * @return bool
665
     */
666 2
    protected function isValidRegionCode($regionCode)
667
    {
668 2
        return $regionCode !== null && in_array($regionCode, $this->supportedRegions);
669
    }
670
671
    /**
672
     * Returns the region where a phone number is from. This could be used for geocoding at the region
673
     * level.
674
     *
675
     * @param PhoneNumber $number the phone number whose origin we want to know
676
     * @return null|string  the region where the phone number is from, or null if no region matches this calling
677
     * code
678
     */
679 545
    public function getRegionCodeForNumber(PhoneNumber $number)
680
    {
681
        $countryCode = $number->getCountryCode();
682 545
        if (!isset($this->countryCallingCodeToRegionCodeMap[$countryCode])) {
683 3
            return null;
684
        }
685 545
        $regions = $this->countryCallingCodeToRegionCodeMap[$countryCode];
686
        if (count($regions) == 1) {
687 430
            return $regions[0];
688
        } else {
689
            return $this->getRegionCodeForNumberFromRegionList($number, $regions);
690
        }
691 545
    }
692
693
    /**
694
     * @param PhoneNumber $number
695
     * @param array $regionCodes
696
     * @return null|string
697
     */
698 128
    protected function getRegionCodeForNumberFromRegionList(PhoneNumber $number, array $regionCodes)
699
    {
700
        $nationalNumber = $this->getNationalSignificantNumber($number);
701
        foreach ($regionCodes as $regionCode) {
702
            // If leadingDigits is present, use this. Otherwise, do full validation.
703
            // Metadata cannot be null because the region codes come from the country calling code map.
704
            $metadata = $this->getMetadataForRegion($regionCode);
705
            if ($metadata->hasLeadingDigits()) {
706
                $nbMatches = preg_match(
707
                    '/' . $metadata->getLeadingDigits() . '/',
708
                    $nationalNumber,
709
                    $matches,
710 7
                    PREG_OFFSET_CAPTURE
711
                );
712 7
                if ($nbMatches > 0 && $matches[0][1] === 0) {
713 58
                    return $regionCode;
714
                }
715
            } 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 704 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...
716 45
                return $regionCode;
717 5
            }
718 30
        }
719 34
        return null;
720 128
    }
721
722
    /**
723
     * Gets the national significant number of the a phone number. Note a national significant number
724
     * doesn't contain a national prefix or any formatting.
725
     *
726
     * @param PhoneNumber $number the phone number for which the national significant number is needed
727
     * @return string the national significant number of the PhoneNumber object passed in
728
     */
729 248
    public function getNationalSignificantNumber(PhoneNumber $number)
730
    {
731
        // If leading zero(s) have been set, we prefix this now. Note this is not a national prefix.
732 248
        $nationalNumber = '';
733
        if ($number->isItalianLeadingZero()) {
734
            $zeros = str_repeat('0', $number->getNumberOfLeadingZeros());
735 10
            $nationalNumber .= $zeros;
736
        }
737
        $nationalNumber .= $number->getNationalNumber();
738 248
        return $nationalNumber;
739 248
    }
740
741
    /**
742
     * @param string $nationalNumber
743
     * @param PhoneMetadata $metadata
744
     * @return int PhoneNumberType constant
745
     */
746 220
    protected function getNumberTypeHelper($nationalNumber, PhoneMetadata $metadata)
747
    {
748
        if (!$this->isNumberMatchingDesc($nationalNumber, $metadata->getGeneralDesc())) {
749 180
            return PhoneNumberType::UNKNOWN;
750
        }
751
        if ($this->isNumberMatchingDesc($nationalNumber, $metadata->getPremiumRate())) {
752 3
            return PhoneNumberType::PREMIUM_RATE;
753
        }
754
        if ($this->isNumberMatchingDesc($nationalNumber, $metadata->getTollFree())) {
755 7
            return PhoneNumberType::TOLL_FREE;
756
        }
757
758
759
        if ($this->isNumberMatchingDesc($nationalNumber, $metadata->getSharedCost())) {
760 5
            return PhoneNumberType::SHARED_COST;
761
        }
762
        if ($this->isNumberMatchingDesc($nationalNumber, $metadata->getVoip())) {
763 4
            return PhoneNumberType::VOIP;
764
        }
765
        if ($this->isNumberMatchingDesc($nationalNumber, $metadata->getPersonalNumber())) {
766
            return PhoneNumberType::PERSONAL_NUMBER;
767
        }
768
        if ($this->isNumberMatchingDesc($nationalNumber, $metadata->getPager())) {
769 1
            return PhoneNumberType::PAGER;
770
        }
771
        if ($this->isNumberMatchingDesc($nationalNumber, $metadata->getUan())) {
772 3
            return PhoneNumberType::UAN;
773
        }
774
        if ($this->isNumberMatchingDesc($nationalNumber, $metadata->getVoicemail())) {
775
            return PhoneNumberType::VOICEMAIL;
776
        }
777
        $isFixedLine = $this->isNumberMatchingDesc($nationalNumber, $metadata->getFixedLine());
778 59
        if ($isFixedLine) {
779
            if ($metadata->isSameMobileAndFixedLinePattern()) {
780
                return PhoneNumberType::FIXED_LINE_OR_MOBILE;
781
            } elseif ($this->isNumberMatchingDesc($nationalNumber, $metadata->getMobile())) {
782 3
                return PhoneNumberType::FIXED_LINE_OR_MOBILE;
783
            }
784 18
            return PhoneNumberType::FIXED_LINE;
785
        }
786
        // Otherwise, test to see if the number is mobile. Only do this if certain that the patterns for
787
        // mobile and fixed line aren't the same.
788
        if (!$metadata->isSameMobileAndFixedLinePattern() &&
789
            $this->isNumberMatchingDesc($nationalNumber, $metadata->getMobile())
790
        ) {
791 10
            return PhoneNumberType::MOBILE;
792
        }
793 56
        return PhoneNumberType::UNKNOWN;
794 220
    }
795
796
    /**
797
     * @param string $nationalNumber
798
     * @param PhoneNumberDesc $numberDesc
799
     * @return bool
800
     */
801 179
    public function isNumberMatchingDesc($nationalNumber, PhoneNumberDesc $numberDesc)
802
    {
803
        $nationalNumberPatternMatcher = new Matcher($numberDesc->getNationalNumberPattern(), $nationalNumber);
804
805
        return $this->isNumberPossibleForDesc($nationalNumber, $numberDesc) && $nationalNumberPatternMatcher->matches();
806 179
    }
807
808
    /**
809
     *
810
     * Helper method to check whether a number is too short to be a regular length phone number in a
811
     * region.
812
     *
813
     * @param PhoneMetadata $regionMetadata
814
     * @param string $number
815
     * @return bool
816
     */
817 2207
    protected function isShorterThanPossibleNormalNumber(PhoneMetadata $regionMetadata, $number)
818
    {
819
        $possibleNumberPattern = $regionMetadata->getGeneralDesc()->getPossibleNumberPattern();
820
        return ($this->testNumberLengthAgainstPattern($possibleNumberPattern, $number) === ValidationResult::TOO_SHORT);
821 2207
    }
822
823
    /**
824
     * @param string $nationalNumber
825
     * @param PhoneNumberDesc $numberDesc
826
     * @return bool
827
     */
828 179
    public function isNumberPossibleForDesc($nationalNumber, PhoneNumberDesc $numberDesc)
829
    {
830
        $possibleNumberPatternMatcher = new Matcher($numberDesc->getPossibleNumberPattern(), $nationalNumber);
831
832
        return $possibleNumberPatternMatcher->matches();
833 179
    }
834
835
    /**
836
     * isNumberGeographical(PhoneNumber)
837
     *
838
     * Tests whether a phone number has a geographical association. It checks if the number is
839
     * associated to a certain region in the country where it belongs to. Note that this doesn't
840
     * verify if the number is actually in use.
841
     *
842
     * isNumberGeographical(PhoneNumberType, $countryCallingCode)
843
     *
844
     * Tests whether a phone number has a geographical association, as represented by its type and the
845
     * country it belongs to.
846
     *
847
     * This version exists since calculating the phone number type is expensive; if we have already
848
     * done this, we don't want to do it again.
849
     *
850
     * @param PhoneNumber|PhoneNumberType $phoneNumberObjOrType A PhoneNumber object, or a PhoneNumberType integer
851
     * @param int|null $countryCallingCode Used when passing a PhoneNumberType
852
     * @return bool
853
     */
854 10
    public function isNumberGeographical($phoneNumberObjOrType, $countryCallingCode = null)
855
    {
856 10
        if ($phoneNumberObjOrType instanceof PhoneNumber) {
857
            return $this->isNumberGeographical($this->getNumberType($phoneNumberObjOrType), $phoneNumberObjOrType->getCountryCode());
0 ignored issues
show
Documentation introduced by
$this->getNumberType($phoneNumberObjOrType) is of type integer, but the function expects a object<libphonenumber\Ph...number\PhoneNumberType>.

It seems like the type of the argument is not accepted by the function/method which you are calling.

In some cases, in particular if PHP’s automatic type-juggling kicks in this might be fine. In other cases, however this might be a bug.

We suggest to add an explicit type cast like in the following example:

function acceptsInteger($int) { }

$x = '123'; // string "123"

// Instead of
acceptsInteger($x);

// we recommend to use
acceptsInteger((integer) $x);
Loading history...
858
        }
859
860 10
        return $phoneNumberObjOrType == PhoneNumberType::FIXED_LINE
861 9
        || $phoneNumberObjOrType == PhoneNumberType::FIXED_LINE_OR_MOBILE
862
        || (in_array($countryCallingCode, static::$GEO_MOBILE_COUNTRIES)
863 10
            && $phoneNumberObjOrType == PhoneNumberType::MOBILE);
864
    }
865
866
    /**
867
     * Gets the type of a phone number.
868
     * @param PhoneNumber $number the number the phone number that we want to know the type
869
     * @return int PhoneNumberType the type of the phone number
870
     */
871 1335
    public function getNumberType(PhoneNumber $number)
872
    {
873
        $regionCode = $this->getRegionCodeForNumber($number);
874
        $metadata = $this->getMetadataForRegionOrCallingCode($number->getCountryCode(), $regionCode);
875 1335
        if ($metadata === null) {
876 7
            return PhoneNumberType::UNKNOWN;
877
        }
878
        $nationalSignificantNumber = $this->getNationalSignificantNumber($number);
879
        return $this->getNumberTypeHelper($nationalSignificantNumber, $metadata);
880 1335
    }
881
882
    /**
883
     * @param int $countryCallingCode
884
     * @param string $regionCode
885
     * @return PhoneMetadata
886
     */
887 259
    protected function getMetadataForRegionOrCallingCode($countryCallingCode, $regionCode)
888
    {
889 259
        return static::REGION_CODE_FOR_NON_GEO_ENTITY === $regionCode ?
890
            $this->getMetadataForNonGeographicalRegion($countryCallingCode) : $this->getMetadataForRegion($regionCode);
891
    }
892
893
    /**
894
     * @param int $countryCallingCode
895
     * @return PhoneMetadata
896
     */
897 10
    public function getMetadataForNonGeographicalRegion($countryCallingCode)
898
    {
899 10
        if (!isset($this->countryCallingCodeToRegionCodeMap[$countryCallingCode])) {
900
            return null;
901
        }
902
        return $this->metadataSource->getMetadataForNonGeographicalRegion($countryCallingCode);
903
    }
904
905
    /**
906
     * Gets the length of the national destination code (NDC) from the PhoneNumber object passed in,
907
     * so that clients could use it to split a national significant number into NDC and subscriber
908
     * number. The NDC of a phone number is normally the first group of digit(s) right after the
909
     * country calling code when the number is formatted in the international format, if there is a
910
     * subscriber number part that follows. An example of how this could be used:
911
     *
912
     * <code>
913
     * $phoneUtil = PhoneNumberUtil::getInstance();
914
     * $number = $phoneUtil->parse("18002530000", "US");
915
     * $nationalSignificantNumber = $phoneUtil->getNationalSignificantNumber($number);
916
     *
917
     * $nationalDestinationCodeLength = $phoneUtil->getLengthOfNationalDestinationCode($number);
918
     * if ($nationalDestinationCodeLength > 0) {
919
     *     $nationalDestinationCode = substr($nationalSignificantNumber, 0, $nationalDestinationCodeLength);
920
     *     $subscriberNumber = substr($nationalSignificantNumber, $nationalDestinationCodeLength);
921
     * } else {
922
     *     $nationalDestinationCode = "";
923
     *     $subscriberNumber = $nationalSignificantNumber;
924
     * }
925
     * </code>
926
     *
927
     * Refer to the unit tests to see the difference between this function and
928
     * {@link #getLengthOfGeographicalAreaCode}.
929
     *
930
     * @param PhoneNumber $number the PhoneNumber object for which clients want to know the length of the NDC.
931
     * @return int the length of NDC of the PhoneNumber object passed in.
932
     */
933 1
    public function getLengthOfNationalDestinationCode(PhoneNumber $number)
934
    {
935
        if ($number->hasExtension()) {
936
            // We don't want to alter the proto given to us, but we don't want to include the extension
937
            // when we format it, so we copy it and clear the extension here.
938
            $copiedProto = new PhoneNumber();
939
            $copiedProto->mergeFrom($number);
940
            $copiedProto->clearExtension();
941
        } else {
942
            $copiedProto = clone $number;
943
        }
944
945
        $nationalSignificantNumber = $this->format($copiedProto, PhoneNumberFormat::INTERNATIONAL);
946
947
        $numberGroups = preg_split('/' . static::NON_DIGITS_PATTERN . '/', $nationalSignificantNumber);
948
949
        // The pattern will start with "+COUNTRY_CODE " so the first group will always be the empty
950
        // string (before the + symbol) and the second group will be the country calling code. The third
951
        // group will be area code if it is not the last group.
952
        if (count($numberGroups) <= 3) {
953
            return 0;
954
        }
955
956
        if ($this->getNumberType($number) == PhoneNumberType::MOBILE) {
957
            // For example Argentinian mobile numbers, when formatted in the international format, are in
958
            // the form of +54 9 NDC XXXX.... As a result, we take the length of the third group (NDC) and
959
            // add the length of the second group (which is the mobile token), which also forms part of
960
            // the national significant number. This assumes that the mobile token is always formatted
961
            // separately from the rest of the phone number.
962
963
            $mobileToken = static::getCountryMobileToken($number->getCountryCode());
964 1
            if ($mobileToken !== "") {
965
                return mb_strlen($numberGroups[2]) + mb_strlen($numberGroups[3]);
966
            }
967
        }
968
        return mb_strlen($numberGroups[2]);
969
    }
970
971
    /**
972
     * Formats a phone number in the specified format using default rules. Note that this does not
973
     * promise to produce a phone number that the user can dial from where they are - although we do
974
     * format in either 'national' or 'international' format depending on what the client asks for, we
975
     * do not currently support a more abbreviated format, such as for users in the same "area" who
976
     * could potentially dial the number without area code. Note that if the phone number has a
977
     * country calling code of 0 or an otherwise invalid country calling code, we cannot work out
978
     * which formatting rules to apply so we return the national significant number with no formatting
979
     * applied.
980
     *
981
     * @param PhoneNumber $number the phone number to be formatted
982
     * @param int $numberFormat the PhoneNumberFormat the phone number should be formatted into
983
     * @return string the formatted phone number
984
     */
985 260
    public function format(PhoneNumber $number, $numberFormat)
986
    {
987
        if ($number->getNationalNumber() == 0 && $number->hasRawInput()) {
988
            // Unparseable numbers that kept their raw input just use that.
989
            // This is the only case where a number can be formatted as E164 without a
990
            // leading '+' symbol (but the original number wasn't parseable anyway).
991
            // TODO: Consider removing the 'if' above so that unparseable
992
            // strings without raw input format to the empty string instead of "+00"
993
            $rawInput = $number->getRawInput();
994
            if (mb_strlen($rawInput) > 0) {
995 1
                return $rawInput;
996
            }
997
        }
998 260
        $metadata = null;
999 260
        $formattedNumber = "";
1000
        $countryCallingCode = $number->getCountryCode();
1001
        $nationalSignificantNumber = $this->getNationalSignificantNumber($number);
1002 260
        if ($numberFormat == PhoneNumberFormat::E164) {
1003
            // Early exit for E164 case (even if the country calling code is invalid) since no formatting
1004
            // of the national number needs to be applied. Extensions are not formatted.
1005 259
            $formattedNumber .= $nationalSignificantNumber;
1006
            $this->prefixNumberWithCountryCallingCode($countryCallingCode, PhoneNumberFormat::E164, $formattedNumber);
1007
        } elseif (!$this->hasValidCountryCallingCode($countryCallingCode)) {
1008 1
            $formattedNumber .= $nationalSignificantNumber;
1009
        } else {
1010
            // Note getRegionCodeForCountryCode() is used because formatting information for regions which
1011
            // share a country calling code is contained by only one region for performance reasons. For
1012
            // example, for NANPA regions it will be contained in the metadata for US.
1013
            $regionCode = $this->getRegionCodeForCountryCode($countryCallingCode);
1014
            // Metadata cannot be null because the country calling code is valid (which means that the
1015
            // region code cannot be ZZ and must be one of our supported region codes).
1016
            $metadata = $this->getMetadataForRegionOrCallingCode($countryCallingCode, $regionCode);
1017
            $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 1016 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...
1018
            $this->prefixNumberWithCountryCallingCode($countryCallingCode, $numberFormat, $formattedNumber);
1019 260
        }
1020
        $this->maybeAppendFormattedExtension($number, $metadata, $numberFormat, $formattedNumber);
1021 260
        return $formattedNumber;
1022 260
    }
1023
1024
    /**
1025
     * A helper function that is used by format and formatByPattern.
1026
     * @param int $countryCallingCode
1027
     * @param int $numberFormat PhoneNumberFormat
1028
     * @param string $formattedNumber
1029
     */
1030 259
    protected function prefixNumberWithCountryCallingCode($countryCallingCode, $numberFormat, &$formattedNumber)
1031
    {
1032
        switch ($numberFormat) {
1033 259
            case PhoneNumberFormat::E164:
1034 259
                $formattedNumber = static::PLUS_SIGN . $countryCallingCode . $formattedNumber;
1035 259
                return;
1036 20
            case PhoneNumberFormat::INTERNATIONAL:
1037 5
                $formattedNumber = static::PLUS_SIGN . $countryCallingCode . " " . $formattedNumber;
1038 5
                return;
1039 25
            case PhoneNumberFormat::RFC3966:
1040 4
                $formattedNumber = static::RFC3966_PREFIX . static::PLUS_SIGN . $countryCallingCode . "-" . $formattedNumber;
1041 4
                return;
1042 25
            case PhoneNumberFormat::NATIONAL:
1043
            default:
1044 25
                return;
1045
        }
1046
    }
1047
1048
    /**
1049
     * Helper function to check the country calling code is valid.
1050
     * @param int $countryCallingCode
1051
     * @return bool
1052
     */
1053 21
    protected function hasValidCountryCallingCode($countryCallingCode)
1054
    {
1055 21
        return isset($this->countryCallingCodeToRegionCodeMap[$countryCallingCode]);
1056
    }
1057
1058
    /**
1059
     * Returns the region code that matches the specific country calling code. In the case of no
1060
     * region code being found, ZZ will be returned. In the case of multiple regions, the one
1061
     * designated in the metadata as the "main" region for this calling code will be returned. If the
1062
     * countryCallingCode entered is valid but doesn't match a specific region (such as in the case of
1063
     * non-geographical calling codes like 800) the value "001" will be returned (corresponding to
1064
     * the value for World in the UN M.49 schema).
1065
     *
1066
     * @param int $countryCallingCode
1067
     * @return string
1068
     */
1069 293
    public function getRegionCodeForCountryCode($countryCallingCode)
1070
    {
1071 293
        $regionCodes = isset($this->countryCallingCodeToRegionCodeMap[$countryCallingCode]) ? $this->countryCallingCodeToRegionCodeMap[$countryCallingCode] : null;
1072 293
        return $regionCodes === null ? static::UNKNOWN_REGION : $regionCodes[0];
1073
    }
1074
1075
    /**
1076
     * Note in some regions, the national number can be written in two completely different ways
1077
     * depending on whether it forms part of the NATIONAL format or INTERNATIONAL format. The
1078
     * numberFormat parameter here is used to specify which format to use for those cases. If a
1079
     * carrierCode is specified, this will be inserted into the formatted string to replace $CC.
1080
     * @param string $number
1081
     * @param PhoneMetadata $metadata
1082
     * @param int $numberFormat PhoneNumberFormat
1083
     * @param null|string $carrierCode
1084
     * @return string
1085
     */
1086 23
    protected function formatNsn($number, PhoneMetadata $metadata, $numberFormat, $carrierCode = null)
1087
    {
1088
        $intlNumberFormats = $metadata->intlNumberFormats();
1089
        // When the intlNumberFormats exists, we use that to format national number for the
1090
        // INTERNATIONAL format instead of using the numberDesc.numberFormats.
1091
        $availableFormats = (count($intlNumberFormats) == 0 || $numberFormat == PhoneNumberFormat::NATIONAL)
1092 23
            ? $metadata->numberFormats()
1093 21
            : $metadata->intlNumberFormats();
1094
        $formattingPattern = $this->chooseFormattingPatternForNumber($availableFormats, $number);
1095 21
        return ($formattingPattern === null)
1096
            ? $number
1097
            : $this->formatNsnUsingPattern($number, $formattingPattern, $numberFormat, $carrierCode);
1098 21
    }
1099
1100
    /**
1101
     * @param NumberFormat[] $availableFormats
1102
     * @param string $nationalNumber
1103
     * @return NumberFormat|null
1104
     */
1105 22
    public function chooseFormattingPatternForNumber(array $availableFormats, $nationalNumber)
1106
    {
1107
        foreach ($availableFormats as $numFormat) {
1108 10
            $leadingDigitsPatternMatcher = null;
1109
            $size = $numFormat->leadingDigitsPatternSize();
1110
            // We always use the last leading_digits_pattern, as it is the most detailed.
1111 10
            if ($size > 0) {
1112
                $leadingDigitsPatternMatcher = new Matcher(
1113 9
                    $numFormat->getLeadingDigitsPattern($size - 1),
1114
                    $nationalNumber
1115
                );
1116
            }
1117 1
            if ($size == 0 || $leadingDigitsPatternMatcher->lookingAt()) {
1118
                $m = new Matcher($numFormat->getPattern(), $nationalNumber);
1119
                if ($m->matches() > 0) {
1120 22
                    return $numFormat;
1121
                }
1122
            }
1123 9
        }
1124 3
        return null;
1125 21
    }
1126
1127
    /**
1128
     * Note that carrierCode is optional - if null or an empty string, no carrier code replacement
1129
     * will take place.
1130
     * @param string $nationalNumber
1131
     * @param NumberFormat $formattingPattern
1132
     * @param int $numberFormat PhoneNumberFormat
1133
     * @param null|string $carrierCode
1134
     * @return string
1135
     */
1136 22
    protected function formatNsnUsingPattern(
1137
        $nationalNumber,
1138
        NumberFormat $formattingPattern,
1139
        $numberFormat,
1140
        $carrierCode = null
1141
    ) {
1142
        $numberFormatRule = $formattingPattern->getFormat();
1143
        $m = new Matcher($formattingPattern->getPattern(), $nationalNumber);
1144 22
        if ($numberFormat === PhoneNumberFormat::NATIONAL &&
1145 22
            $carrierCode !== null && mb_strlen($carrierCode) > 0 &&
1146
            mb_strlen($formattingPattern->getDomesticCarrierCodeFormattingRule()) > 0
1147
        ) {
1148
            // Replace the $CC in the formatting rule with the desired carrier code.
1149
            $carrierCodeFormattingRule = $formattingPattern->getDomesticCarrierCodeFormattingRule();
1150
            $ccPatternMatcher = new Matcher(static::CC_PATTERN, $carrierCodeFormattingRule);
1151
            $carrierCodeFormattingRule = $ccPatternMatcher->replaceFirst($carrierCode);
1152
            // Now replace the $FG in the formatting rule with the first group and the carrier code
1153
            // combined in the appropriate way.
1154
            $firstGroupMatcher = new Matcher(static::FIRST_GROUP_PATTERN, $numberFormatRule);
1155
            $numberFormatRule = $firstGroupMatcher->replaceFirst($carrierCodeFormattingRule);
1156
            $formattedNationalNumber = $m->replaceAll($numberFormatRule);
1157
        } else {
1158
            // Use the national prefix formatting rule instead.
1159
            $nationalPrefixFormattingRule = $formattingPattern->getNationalPrefixFormattingRule();
1160 22
            if ($numberFormat == PhoneNumberFormat::NATIONAL &&
1161 22
                $nationalPrefixFormattingRule !== null &&
1162
                mb_strlen($nationalPrefixFormattingRule) > 0
1163
            ) {
1164
                $firstGroupMatcher = new Matcher(static::FIRST_GROUP_PATTERN, $numberFormatRule);
1165
                $formattedNationalNumber = $m->replaceAll(
1166 11
                    $firstGroupMatcher->replaceFirst($nationalPrefixFormattingRule)
1167
                );
1168
            } else {
1169
                $formattedNationalNumber = $m->replaceAll($numberFormatRule);
1170 11
            }
1171 1
        }
1172 22
        if ($numberFormat == PhoneNumberFormat::RFC3966) {
1173
            // Strip any leading punctuation.
1174
            $matcher = new Matcher(static::$SEPARATOR_PATTERN, $formattedNationalNumber);
1175
            if ($matcher->lookingAt()) {
1176
                $formattedNationalNumber = $matcher->replaceFirst("");
1177
            }
1178
            // Replace the rest with a dash between each number group.
1179
            $formattedNationalNumber = $matcher->reset($formattedNationalNumber)->replaceAll("-");
1180
        }
1181 22
        return $formattedNationalNumber;
1182 22
    }
1183
1184
    /**
1185
     * Appends the formatted extension of a phone number to formattedNumber, if the phone number had
1186
     * an extension specified.
1187
     *
1188
     * @param PhoneNumber $number
1189
     * @param PhoneMetadata|null $metadata
1190
     * @param int $numberFormat PhoneNumberFormat
1191
     * @param string $formattedNumber
1192
     */
1193 1
    protected function maybeAppendFormattedExtension(PhoneNumber $number, $metadata, $numberFormat, &$formattedNumber)
1194
    {
1195
        if ($number->hasExtension() && mb_strlen($number->getExtension()) > 0) {
1196
            if ($numberFormat === PhoneNumberFormat::RFC3966) {
1197
                $formattedNumber .= static::RFC3966_EXTN_PREFIX . $number->getExtension();
1198
            } else {
1199
                if (!empty($metadata) && $metadata->hasPreferredExtnPrefix()) {
1200
                    $formattedNumber .= $metadata->getPreferredExtnPrefix() . $number->getExtension();
1201
                } else {
1202
                    $formattedNumber .= static::DEFAULT_EXTN_PREFIX . $number->getExtension();
1203 1
                }
1204 1
            }
1205
        }
1206
    }
1207
1208
    /**
1209
     * Returns the mobile token for the provided country calling code if it has one, otherwise
1210
     * returns an empty string. A mobile token is a number inserted before the area code when dialing
1211
     * a mobile number from that country from abroad.
1212
     *
1213
     * @param int $countryCallingCode the country calling code for which we want the mobile token
1214
     * @return string the mobile token, as a string, for the given country calling code
1215
     */
1216 6
    public static function getCountryMobileToken($countryCallingCode)
1217
    {
1218
        if (array_key_exists($countryCallingCode, static::$MOBILE_TOKEN_MAPPINGS)) {
1219 4
            return static::$MOBILE_TOKEN_MAPPINGS[$countryCallingCode];
1220
        }
1221 6
        return "";
1222
    }
1223
1224
    /**
1225
     * Checks if the number is a valid vanity (alpha) number such as 800 MICROSOFT. A valid vanity
1226
     * number will start with at least 3 digits and will have three or more alpha characters. This
1227
     * does not do region-specific checks - to work out if this number is actually valid for a region,
1228
     * it should be parsed and methods such as {@link #isPossibleNumberWithReason} and
1229
     * {@link #isValidNumber} should be used.
1230
     *
1231
     * @param string $number the number that needs to be checked
1232
     * @return bool true if the number is a valid vanity number
1233
     */
1234
    public function isAlphaNumber($number)
1235
    {
1236
        if (!$this->isViablePhoneNumber($number)) {
1237
            // Number is too short, or doesn't match the basic phone number pattern.
1238
            return false;
1239
        }
1240
        $this->maybeStripExtension($number);
1241
        return (bool)preg_match('/' . static::VALID_ALPHA_PHONE_PATTERN . '/' . static::REGEX_FLAGS, $number);
1242
    }
1243
1244
    /**
1245
     * Checks to see if the string of characters could possibly be a phone number at all. At the
1246
     * moment, checks to see that the string begins with at least 2 digits, ignoring any punctuation
1247
     * commonly found in phone numbers.
1248
     * This method does not require the number to be normalized in advance - but does assume that
1249
     * leading non-number symbols have been removed, such as by the method extractPossibleNumber.
1250
     *
1251
     * @param string $number to be checked for viability as a phone number
1252
     * @return boolean true if the number could be a phone number of some sort, otherwise false
1253
     */
1254 2208
    public static function isViablePhoneNumber($number)
1255
    {
1256
        if (mb_strlen($number) < static::MIN_LENGTH_FOR_NSN) {
1257 2
            return false;
1258
        }
1259
1260
        $validPhoneNumberPattern = static::getValidPhoneNumberPattern();
1261
1262
        $m = preg_match($validPhoneNumberPattern, $number);
1263 2208
        return $m > 0;
1264
    }
1265
1266
    /**
1267
     * We append optionally the extension pattern to the end here, as a valid phone number may
1268
     * have an extension prefix appended, followed by 1 or more digits.
1269
     * @return string
1270
     */
1271 2208
    protected static function getValidPhoneNumberPattern()
1272
    {
1273 2208
        return static::$VALID_PHONE_NUMBER_PATTERN;
1274
    }
1275
1276
    /**
1277
     * Strips any extension (as in, the part of the number dialled after the call is connected,
1278
     * usually indicated with extn, ext, x or similar) from the end of the number, and returns it.
1279
     *
1280
     * @param string $number the non-normalized telephone number that we wish to strip the extension from
1281
     * @return string the phone extension
1282
     */
1283 2207
    protected function maybeStripExtension(&$number)
1284
    {
1285 2207
        $matches = array();
1286
        $find = preg_match(static::$EXTN_PATTERN, $number, $matches, PREG_OFFSET_CAPTURE);
1287
        // If we find a potential extension, and the number preceding this is a viable number, we assume
1288
        // it is an extension.
1289 2207
        if ($find > 0 && $this->isViablePhoneNumber(substr($number, 0, $matches[0][1]))) {
1290
            // The numbers are captured into groups in the regular expression.
1291
1292
            for ($i = 1, $length = count($matches); $i <= $length; $i++) {
1293
                if ($matches[$i][0] != "") {
1294
                    // We go through the capturing groups until we find one that captured some digits. If none
1295
                    // did, then we will return the empty string.
1296 1
                    $extension = $matches[$i][0];
1297
                    $number = substr($number, 0, $matches[0][1]);
1298 1
                    return $extension;
1299
                }
1300
            }
1301
        }
1302 2207
        return "";
1303
    }
1304
1305
    /**
1306
     * Parses a string and returns it in proto buffer format. This method differs from {@link #parse}
1307
     * in that it always populates the raw_input field of the protocol buffer with numberToParse as
1308
     * well as the country_code_source field.
1309
     *
1310
     * @param string $numberToParse number that we are attempting to parse. This can contain formatting
1311
     *                                  such as +, ( and -, as well as a phone number extension. It can also
1312
     *                                  be provided in RFC3966 format.
1313
     * @param string $defaultRegion region that we are expecting the number to be from. This is only used
1314
     *                                  if the number being parsed is not written in international format.
1315
     *                                  The country calling code for the number in this case would be stored
1316
     *                                  as that of the default region supplied.
1317
     * @param PhoneNumber $phoneNumber
1318
     * @return PhoneNumber              a phone number proto buffer filled with the parsed number
1319
     */
1320
    public function parseAndKeepRawInput($numberToParse, $defaultRegion, PhoneNumber $phoneNumber = null)
1321
    {
1322
        if ($phoneNumber === null) {
1323
            $phoneNumber = new PhoneNumber();
1324
        }
1325
        $this->parseHelper($numberToParse, $defaultRegion, true, true, $phoneNumber);
1326
        return $phoneNumber;
1327
    }
1328
1329
    /**
1330
     * A helper function to set the values related to leading zeros in a PhoneNumber.
1331
     * @param string $nationalNumber
1332
     * @param PhoneNumber $phoneNumber
1333
     */
1334 31
    public static function setItalianLeadingZerosForPhoneNumber($nationalNumber, PhoneNumber $phoneNumber)
1335
    {
1336
        if (strlen($nationalNumber) > 1 && substr($nationalNumber, 0, 1) == '0') {
1337
            $phoneNumber->setItalianLeadingZero(true);
1338 31
            $numberOfLeadingZeros = 1;
1339
            // Note that if the national number is all "0"s, the last "0" is not counted as a leading
1340
            // zero.
1341
            while ($numberOfLeadingZeros < (strlen($nationalNumber) - 1) &&
1342
                substr($nationalNumber, $numberOfLeadingZeros, 1) == '0') {
1343 3
                $numberOfLeadingZeros++;
1344
            }
1345
1346 31
            if ($numberOfLeadingZeros != 1) {
1347
                $phoneNumber->setNumberOfLeadingZeros($numberOfLeadingZeros);
1348
            }
1349
        }
1350
    }
1351
1352
    /**
1353
     * Parses a string and fills up the phoneNumber. This method is the same as the public
1354
     * parse() method, with the exception that it allows the default region to be null, for use by
1355
     * isNumberMatch(). checkRegion should be set to false if it is permitted for the default region
1356
     * to be null or unknown ("ZZ").
1357
     * @param string $numberToParse
1358
     * @param string $defaultRegion
1359
     * @param bool $keepRawInput
1360
     * @param bool $checkRegion
1361
     * @param PhoneNumber $phoneNumber
1362
     * @throws NumberParseException
1363
     */
1364 2428
    protected function parseHelper($numberToParse, $defaultRegion, $keepRawInput, $checkRegion, PhoneNumber $phoneNumber)
1365
    {
1366 2209
        if ($numberToParse === null) {
1367
            throw new NumberParseException(NumberParseException::NOT_A_NUMBER, "The phone number supplied was null.");
1368
        }
1369
1370
        $numberToParse = trim($numberToParse);
1371
1372
        if (mb_strlen($numberToParse) > static::MAX_INPUT_STRING_LENGTH) {
1373
            throw new NumberParseException(
1374
                NumberParseException::TOO_LONG,
1375
                "The string supplied was too long to parse."
1376
            );
1377
        }
1378
1379 2208
        $nationalNumber = '';
1380
        $this->buildNationalNumberForParsing($numberToParse, $nationalNumber);
1381
1382
        if (!$this->isViablePhoneNumber($nationalNumber)) {
1383
            throw new NumberParseException(
1384 2
                NumberParseException::NOT_A_NUMBER,
1385 2
                "The string supplied did not seem to be a phone number."
1386
            );
1387
        }
1388
1389
        // Check the region supplied is valid, or that the extracted number starts with some sort of +
1390
        // sign so the number's region can be determined.
1391
        if ($checkRegion && !$this->checkRegionForParsing($nationalNumber, $defaultRegion)) {
1392
            throw new NumberParseException(
1393 1
                NumberParseException::INVALID_COUNTRY_CODE,
1394 1
                "Missing or invalid default region."
1395
            );
1396
        }
1397
1398 2207
        if ($keepRawInput) {
1399
            $phoneNumber->setRawInput($numberToParse);
1400
        }
1401
        // Attempt to parse extension first, since it doesn't require region-specific data and we want
1402
        // to have the non-normalised number here.
1403
        $extension = $this->maybeStripExtension($nationalNumber);
1404
        if (mb_strlen($extension) > 0) {
1405
            $phoneNumber->setExtension($extension);
1406
        }
1407
1408
        $regionMetadata = $this->getMetadataForRegion($defaultRegion);
1409
        // Check to see if the number is given in international format so we know whether this number is
1410
        // from the default region or not.
1411 2207
        $normalizedNationalNumber = "";
1412
        try {
1413
            // TODO: This method should really just take in the string buffer that has already
1414
            // been created, and just remove the prefix, rather than taking in a string and then
1415
            // outputting a string buffer.
1416 2207
            $countryCode = $this->maybeExtractCountryCode(
1417
                $nationalNumber,
1418
                $regionMetadata,
1419
                $normalizedNationalNumber,
1420
                $keepRawInput,
1421
                $phoneNumber
1422
            );
1423
        } catch (NumberParseException $e) {
1424
            $matcher = new Matcher(static::$PLUS_CHARS_PATTERN, $nationalNumber);
1425
            if ($e->getErrorType() == NumberParseException::INVALID_COUNTRY_CODE && $matcher->lookingAt()) {
1426
                // Strip the plus-char, and try again.
1427
                $countryCode = $this->maybeExtractCountryCode(
1428
                    substr($nationalNumber, $matcher->end()),
1429
                    $regionMetadata,
1430
                    $normalizedNationalNumber,
1431
                    $keepRawInput,
1432
                    $phoneNumber
1433
                );
1434 1
                if ($countryCode == 0) {
1435
                    throw new NumberParseException(
1436 1
                        NumberParseException::INVALID_COUNTRY_CODE,
1437 1
                        "Could not interpret numbers after plus-sign."
1438
                    );
1439
                }
1440
            } else {
1441
                throw new NumberParseException($e->getErrorType(), $e->getMessage(), $e);
1442
            }
1443 2207
        }
1444 2207
        if ($countryCode !== 0) {
1445
            $phoneNumberRegion = $this->getRegionCodeForCountryCode($countryCode);
1446 271
            if ($phoneNumberRegion != $defaultRegion) {
1447
                // Metadata cannot be null because the country calling code is valid.
1448
                $regionMetadata = $this->getMetadataForRegionOrCallingCode($countryCode, $phoneNumberRegion);
1449
            }
1450
        } else {
1451
            // If no extracted country calling code, use the region supplied instead. The national number
1452
            // is just the normalized version of the number we were given to parse.
1453
1454
            $normalizedNationalNumber .= $this->normalize($nationalNumber);
1455 2428
            if ($defaultRegion !== null) {
1456
                $countryCode = $regionMetadata->getCountryCode();
1457
                $phoneNumber->setCountryCode($countryCode);
1458
            } elseif ($keepRawInput) {
1459
                $phoneNumber->clearCountryCodeSource();
1460 2428
            }
1461 271
        }
1462
        if (mb_strlen($normalizedNationalNumber) < static::MIN_LENGTH_FOR_NSN) {
1463
            throw new NumberParseException(
1464 2
                NumberParseException::TOO_SHORT_NSN,
1465 2
                "The string supplied is too short to be a phone number."
1466
            );
1467
        }
1468 2207
        if ($regionMetadata !== null) {
1469 2207
            $carrierCode = "";
1470 2207
            $potentialNationalNumber = $normalizedNationalNumber;
1471
            $this->maybeStripNationalPrefixAndCarrierCode($potentialNationalNumber, $regionMetadata, $carrierCode);
1472
            // We require that the NSN remaining after stripping the national prefix and carrier code be
1473
            // of a possible length for the region. Otherwise, we don't do the stripping, since the
1474
            // original number could be a valid short number.
1475
            if (!$this->isShorterThanPossibleNormalNumber($regionMetadata, $potentialNationalNumber)) {
1476 1794
                $normalizedNationalNumber = $potentialNationalNumber;
1477 1794
                if ($keepRawInput) {
1478
                    $phoneNumber->setPreferredDomesticCarrierCode($carrierCode);
1479
                }
1480
            }
1481
        }
1482
        $lengthOfNationalNumber = mb_strlen($normalizedNationalNumber);
1483 2207
        if ($lengthOfNationalNumber < static::MIN_LENGTH_FOR_NSN) {
1484
            throw new NumberParseException(
1485
                NumberParseException::TOO_SHORT_NSN,
1486
                "The string supplied is too short to be a phone number."
1487
            );
1488
        }
1489 2207
        if ($lengthOfNationalNumber > static::MAX_LENGTH_FOR_NSN) {
1490
            throw new NumberParseException(
1491 1
                NumberParseException::TOO_LONG,
1492 1
                "The string supplied is too long to be a phone number."
1493
            );
1494
        }
1495
        $this->setItalianLeadingZerosForPhoneNumber($normalizedNationalNumber, $phoneNumber);
1496
1497
1498
        /*
1499
         * We have to store the National Number as a string instead of a "long" as Google do
1500
         *
1501
         * Since PHP doesn't always support 64 bit INTs, this was a float, but that had issues
1502
         * with long numbers.
1503
         *
1504
         * We have to remove the leading zeroes ourself though
1505
         */
1506 2206
        if ((int)$normalizedNationalNumber == 0) {
1507 1
            $normalizedNationalNumber = "0";
1508
        } else {
1509
            $normalizedNationalNumber = ltrim($normalizedNationalNumber, '0');
1510 1
        }
1511
1512
        $phoneNumber->setNationalNumber($normalizedNationalNumber);
1513 3
    }
1514
1515
    /**
1516
     * Converts numberToParse to a form that we can parse and write it to nationalNumber if it is
1517
     * written in RFC3966; otherwise extract a possible number out of it and write to nationalNumber.
1518
     * @param string $numberToParse
1519
     * @param string $nationalNumber
1520
     */
1521 2208
    protected function buildNationalNumberForParsing($numberToParse, &$nationalNumber)
1522
    {
1523
        $indexOfPhoneContext = strpos($numberToParse, static::RFC3966_PHONE_CONTEXT);
1524 2208
        if ($indexOfPhoneContext > 0) {
1525
            $phoneContextStart = $indexOfPhoneContext + mb_strlen(static::RFC3966_PHONE_CONTEXT);
1526
            // If the phone context contains a phone number prefix, we need to capture it, whereas domains
1527
            // will be ignored.
1528
            if (substr($numberToParse, $phoneContextStart, 1) == static::PLUS_SIGN) {
1529
                // Additional parameters might follow the phone context. If so, we will remove them here
1530
                // because the parameters after phone context are not important for parsing the
1531
                // phone number.
1532
                $phoneContextEnd = strpos($numberToParse, ';', $phoneContextStart);
1533 1
                if ($phoneContextEnd > 0) {
1534
                    $nationalNumber .= substr($numberToParse, $phoneContextStart, $phoneContextEnd - $phoneContextStart);
1535
                } else {
1536
                    $nationalNumber .= substr($numberToParse, $phoneContextStart);
1537 1
                }
1538
            }
1539
1540
            // Now append everything between the "tel:" prefix and the phone-context. This should include
1541
            // the national number, an optional extension or isdn-subaddress component. Note we also
1542
            // handle the case when "tel:" is missing, as we have seen in some of the phone number inputs.
1543
            // In that case, we append everything from the beginning.
1544
1545
            $indexOfRfc3966Prefix = strpos($numberToParse, static::RFC3966_PREFIX);
1546
            $indexOfNationalNumber = ($indexOfRfc3966Prefix !== false) ? $indexOfRfc3966Prefix + strlen(static::RFC3966_PREFIX) : 0;
1547
            $nationalNumber .= substr($numberToParse, $indexOfNationalNumber, ($indexOfPhoneContext - $indexOfNationalNumber));
1548
        } else {
1549
            // Extract a possible number from the string passed in (this strips leading characters that
1550
            // could not be the start of a phone number.)
1551
            $nationalNumber .= $this->extractPossibleNumber($numberToParse);
1552 1
        }
1553
1554
        // Delete the isdn-subaddress and everything after it if it is present. Note extension won't
1555
        // appear at the same time with isdn-subaddress according to paragraph 5.3 of the RFC3966 spec,
1556
        $indexOfIsdn = strpos($nationalNumber, static::RFC3966_ISDN_SUBADDRESS);
1557 2208
        if ($indexOfIsdn > 0) {
1558
            $nationalNumber = substr($nationalNumber, 0, $indexOfIsdn);
1559
        }
1560
        // If both phone context and isdn-subaddress are absent but other parameters are present, the
1561
        // parameters are left in nationalNumber. This is because we are concerned about deleting
1562
        // content from a potential number string when there is no strong evidence that the number is
1563
        // actually written in RFC3966.
1564 2208
    }
1565
1566
    /**
1567
     * Attempts to extract a possible number from the string passed in. This currently strips all
1568
     * leading characters that cannot be used to start a phone number. Characters that can be used to
1569
     * start a phone number are defined in the VALID_START_CHAR_PATTERN. If none of these characters
1570
     * are found in the number passed in, an empty string is returned. This function also attempts to
1571
     * strip off any alternative extensions or endings if two or more are present, such as in the case
1572
     * of: (530) 583-6985 x302/x2303. The second extension here makes this actually two phone numbers,
1573
     * (530) 583-6985 x302 and (530) 583-6985 x2303. We remove the second extension so that the first
1574
     * number is parsed correctly.
1575
     *
1576
     * @param int $number the string that might contain a phone number
1577
     * @return string the number, stripped of any non-phone-number prefix (such as "Tel:") or an empty
1578
     *                string if no character used to start phone numbers (such as + or any digit) is
1579
     *                found in the number
1580
     */
1581 1974
    public static function extractPossibleNumber($number)
1582
    {
1583 1974
        $matches = array();
1584
        $match = preg_match('/' . static::$VALID_START_CHAR_PATTERN . '/ui', $number, $matches, PREG_OFFSET_CAPTURE);
1585 1974
        if ($match > 0) {
1586
            $number = substr($number, $matches[0][1]);
1587
            // Remove trailing non-alpha non-numerical characters.
1588
            $trailingCharsMatcher = new Matcher(static::$UNWANTED_END_CHAR_PATTERN, $number);
1589
            if ($trailingCharsMatcher->find() && $trailingCharsMatcher->start() > 0) {
1590
                $number = substr($number, 0, $trailingCharsMatcher->start());
1591
            }
1592
1593
            // Check for extra numbers at the end.
1594
            $match = preg_match('%' . static::$SECOND_NUMBER_START_PATTERN . '%', $number, $matches, PREG_OFFSET_CAPTURE);
1595 1974
            if ($match > 0) {
1596
                $number = substr($number, 0, $matches[0][1]);
1597
            }
1598
1599 1974
            return $number;
1600
        } else {
1601 3
            return "";
1602
        }
1603
    }
1604
1605
    /**
1606
     * Checks to see that the region code used is valid, or if it is not valid, that the number to
1607
     * parse starts with a + symbol so that we can attempt to infer the region from the number.
1608
     * Returns false if it cannot use the region provided and the region cannot be inferred.
1609
     * @param string $numberToParse
1610
     * @param string $defaultRegion
1611
     * @return bool
1612
     */
1613 2207
    protected function checkRegionForParsing($numberToParse, $defaultRegion)
1614
    {
1615
        if (!$this->isValidRegionCode($defaultRegion)) {
1616
            // If the number is null or empty, we can't infer the region.
1617
            $plusCharsPatternMatcher = new Matcher(static::$PLUS_CHARS_PATTERN, $numberToParse);
1618
            if ($numberToParse === null || mb_strlen($numberToParse) == 0 || !$plusCharsPatternMatcher->lookingAt()) {
1619 1
                return false;
1620
            }
1621
        }
1622 2207
        return true;
1623
    }
1624
1625
    /**
1626
     * Tries to extract a country calling code from a number. This method will return zero if no
1627
     * country calling code is considered to be present. Country calling codes are extracted in the
1628
     * following ways:
1629
     * <ul>
1630
     *  <li> by stripping the international dialing prefix of the region the person is dialing from,
1631
     *       if this is present in the number, and looking at the next digits
1632
     *  <li> by stripping the '+' sign if present and then looking at the next digits
1633
     *  <li> by comparing the start of the number and the country calling code of the default region.
1634
     *       If the number is not considered possible for the numbering plan of the default region
1635
     *       initially, but starts with the country calling code of this region, validation will be
1636
     *       reattempted after stripping this country calling code. If this number is considered a
1637
     *       possible number, then the first digits will be considered the country calling code and
1638
     *       removed as such.
1639
     * </ul>
1640
     * It will throw a NumberParseException if the number starts with a '+' but the country calling
1641
     * code supplied after this does not match that of any known region.
1642
     *
1643
     * @param string $number non-normalized telephone number that we wish to extract a country calling
1644
     *     code from - may begin with '+'
1645
     * @param PhoneMetadata $defaultRegionMetadata metadata about the region this number may be from
1646
     * @param string $nationalNumber a string buffer to store the national significant number in, in the case
1647
     *     that a country calling code was extracted. The number is appended to any existing contents.
1648
     *     If no country calling code was extracted, this will be left unchanged.
1649
     * @param bool $keepRawInput true if the country_code_source and preferred_carrier_code fields of
1650
     *     phoneNumber should be populated.
1651
     * @param PhoneNumber $phoneNumber the PhoneNumber object where the country_code and country_code_source need
1652
     *     to be populated. Note the country_code is always populated, whereas country_code_source is
1653
     *     only populated when keepCountryCodeSource is true.
1654
     * @return int the country calling code extracted or 0 if none could be extracted
1655
     * @throws NumberParseException
1656
     */
1657 2432
    public function maybeExtractCountryCode(
1658
        $number,
1659
        PhoneMetadata $defaultRegionMetadata = null,
1660
        &$nationalNumber,
1661
        $keepRawInput,
1662
        PhoneNumber $phoneNumber
1663
    ) {
1664
        if (mb_strlen($number) == 0) {
1665
            return 0;
1666
        }
1667 2207
        $fullNumber = $number;
1668
        // Set the default prefix to be something that will never match.
1669 2207
        $possibleCountryIddPrefix = "NonMatch";
1670 2207
        if ($defaultRegionMetadata !== null) {
1671
            $possibleCountryIddPrefix = $defaultRegionMetadata->getInternationalPrefix();
1672
        }
1673
        $countryCodeSource = $this->maybeStripInternationalPrefixAndNormalize($fullNumber, $possibleCountryIddPrefix);
1674
1675 2207
        if ($keepRawInput) {
1676
            $phoneNumber->setCountryCodeSource($countryCodeSource);
1677
        }
1678 2207
        if ($countryCodeSource != CountryCodeSource::FROM_DEFAULT_COUNTRY) {
1679
            if (mb_strlen($fullNumber) <= static::MIN_LENGTH_FOR_NSN) {
1680
                throw new NumberParseException(
1681
                    NumberParseException::TOO_SHORT_AFTER_IDD,
1682
                    "Phone number had an IDD, but after this was not long enough to be a viable phone number."
1683
                );
1684
            }
1685
            $potentialCountryCode = $this->extractCountryCode($fullNumber, $nationalNumber);
1686
1687 266
            if ($potentialCountryCode != 0) {
1688
                $phoneNumber->setCountryCode($potentialCountryCode);
1689 267
                return $potentialCountryCode;
1690
            }
1691
1692
            // If this fails, they must be using a strange country calling code that we don't recognize,
1693
            // or that doesn't exist.
1694
            throw new NumberParseException(
1695 1
                NumberParseException::INVALID_COUNTRY_CODE,
1696 1
                "Country calling code supplied was not recognised."
1697
            );
1698 2432
        } elseif ($defaultRegionMetadata !== null) {
1699
            // Check to see if the number starts with the country calling code for the default region. If
1700
            // so, we remove the country calling code, and do some checks on the validity of the number
1701
            // before and after.
1702
            $defaultCountryCode = $defaultRegionMetadata->getCountryCode();
1703 2432
            $defaultCountryCodeString = (string)$defaultCountryCode;
1704 2432
            $normalizedNumber = (string)$fullNumber;
1705
            if (strpos($normalizedNumber, $defaultCountryCodeString) === 0) {
1706
                $potentialNationalNumber = substr($normalizedNumber, mb_strlen($defaultCountryCodeString));
1707
                $generalDesc = $defaultRegionMetadata->getGeneralDesc();
1708
                $validNumberPattern = $generalDesc->getNationalNumberPattern();
1709
                // Don't need the carrier code.
1710 50
                $carriercode = null;
1711 50
                $this->maybeStripNationalPrefixAndCarrierCode(
1712
                    $potentialNationalNumber,
1713
                    $defaultRegionMetadata,
1714
                    $carriercode
1715
                );
1716
                $possibleNumberPattern = $generalDesc->getPossibleNumberPattern();
1717
                // If the number was not valid before but is valid now, or if it was too long before, we
1718
                // consider the number with the country calling code stripped to be a better result and
1719
                // keep that instead.
1720
                if ((preg_match('/^(' . $validNumberPattern . ')$/x', $fullNumber) == 0 &&
1721
                        preg_match('/^(' . $validNumberPattern . ')$/x', $potentialNationalNumber) > 0) ||
1722 45
                    $this->testNumberLengthAgainstPattern($possibleNumberPattern, (string)$fullNumber)
1723 45
                    == ValidationResult::TOO_LONG
1724
                ) {
1725 7
                    $nationalNumber .= $potentialNationalNumber;
1726 7
                    if ($keepRawInput) {
1727
                        $phoneNumber->setCountryCodeSource(CountryCodeSource::FROM_NUMBER_WITHOUT_PLUS_SIGN);
1728
                    }
1729
                    $phoneNumber->setCountryCode($defaultCountryCode);
1730 7
                    return $defaultCountryCode;
1731
                }
1732
            }
1733
        }
1734
        // No country calling code present.
1735
        $phoneNumber->setCountryCode(0);
1736 2427
        return 0;
1737 2207
    }
1738
1739
    /**
1740
     * Strips any international prefix (such as +, 00, 011) present in the number provided, normalizes
1741
     * the resulting number, and indicates if an international prefix was present.
1742
     *
1743
     * @param string $number the non-normalized telephone number that we wish to strip any international
1744
     *     dialing prefix from.
1745
     * @param string $possibleIddPrefix string the international direct dialing prefix from the region we
1746
     *     think this number may be dialed in
1747
     * @return int the corresponding CountryCodeSource if an international dialing prefix could be
1748
     *     removed from the number, otherwise CountryCodeSource.FROM_DEFAULT_COUNTRY if the number did
1749
     *     not seem to be in international format.
1750
     */
1751 2432
    public function maybeStripInternationalPrefixAndNormalize(&$number, $possibleIddPrefix)
1752
    {
1753
        if (mb_strlen($number) == 0) {
1754
            return CountryCodeSource::FROM_DEFAULT_COUNTRY;
1755
        }
1756 2207
        $matches = array();
1757
        // Check to see if the number begins with one or more plus signs.
1758
        $match = preg_match('/^' . static::$PLUS_CHARS_PATTERN . '/' . static::REGEX_FLAGS, $number, $matches, PREG_OFFSET_CAPTURE);
1759 2207
        if ($match > 0) {
1760
            $number = mb_substr($number, $matches[0][1] + mb_strlen($matches[0][0]));
1761
            // Can now normalize the rest of the number since we've consumed the "+" sign at the start.
1762
            $number = $this->normalize($number);
1763 265
            return CountryCodeSource::FROM_NUMBER_WITH_PLUS_SIGN;
1764
        }
1765
        // Attempt to parse the first digits as an international prefix.
1766 2432
        $iddPattern = $possibleIddPrefix;
1767
        $number = $this->normalize($number);
1768
        return $this->parsePrefixAsIdd($iddPattern, $number)
1769 3
            ? CountryCodeSource::FROM_NUMBER_WITH_IDD
1770 2432
            : CountryCodeSource::FROM_DEFAULT_COUNTRY;
1771
    }
1772
1773
    /**
1774
     * Normalizes a string of characters representing a phone number. This performs
1775
     * the following conversions:
1776
     *   Punctuation is stripped.
1777
     *   For ALPHA/VANITY numbers:
1778
     *   Letters are converted to their numeric representation on a telephone
1779
     *       keypad. The keypad used here is the one defined in ITU Recommendation
1780
     *       E.161. This is only done if there are 3 or more letters in the number,
1781
     *       to lessen the risk that such letters are typos.
1782
     *   For other numbers:
1783
     *   Wide-ascii digits are converted to normal ASCII (European) digits.
1784
     *   Arabic-Indic numerals are converted to European numerals.
1785
     *   Spurious alpha characters are stripped.
1786
     *
1787
     * @param string $number a string of characters representing a phone number.
1788
     * @return string the normalized string version of the phone number.
1789
     */
1790
    public static function normalize(&$number)
1791
    {
1792
        $m = new Matcher(static::VALID_ALPHA_PHONE_PATTERN, $number);
1793
        if ($m->matches()) {
1794
            return static::normalizeHelper($number, static::$ALPHA_PHONE_MAPPINGS, true);
1795
        } else {
1796
            return static::normalizeDigitsOnly($number);
1797
        }
1798
    }
1799
1800
    /**
1801
     * Normalizes a string of characters representing a phone number. This converts wide-ascii and
1802
     * arabic-indic numerals to European numerals, and strips punctuation and alpha characters.
1803
     *
1804
     * @param $number string  a string of characters representing a phone number
1805
     * @return string the normalized string version of the phone number
1806
     */
1807
    public static function normalizeDigitsOnly($number)
1808
    {
1809
        return static::normalizeDigits($number, false /* strip non-digits */);
1810
    }
1811
1812
    /**
1813
     * @param string $number
1814
     * @param bool $keepNonDigits
1815
     * @return string
1816
     */
1817 28
    public static function normalizeDigits($number, $keepNonDigits)
1818
    {
1819 28
        $normalizedDigits = "";
1820
        $numberAsArray = preg_split('/(?<!^)(?!$)/u', $number);
1821
        foreach ($numberAsArray as $character) {
1822
            if (is_numeric($character)) {
1823
                $normalizedDigits .= $character;
1824
            } elseif ($keepNonDigits) {
1825
                $normalizedDigits .= $character;
1826
            }
1827
            // If neither of the above are true, we remove this character.
1828
1829
            // Check if we are in the unicode number range
1830
            if (array_key_exists($character, static::$numericCharacters)) {
1831
                $normalizedDigits .= static::$numericCharacters[$character];
1832
            }
1833
        }
1834 28
        return $normalizedDigits;
1835
    }
1836
1837
    /**
1838
     * Strips the IDD from the start of the number if present. Helper function used by
1839
     * maybeStripInternationalPrefixAndNormalize.
1840
     * @param string $iddPattern
1841
     * @param string $number
1842
     * @return bool
1843
     */
1844 2431
    protected function parsePrefixAsIdd($iddPattern, &$number)
1845
    {
1846
        $m = new Matcher($iddPattern, $number);
1847
        if ($m->lookingAt()) {
1848
            $matchEnd = $m->end();
1849
            // Only strip this if the first digit after the match is not a 0, since country calling codes
1850
            // cannot begin with 0.
1851
            $digitMatcher = new Matcher(static::$CAPTURING_DIGIT_PATTERN, substr($number, $matchEnd));
1852
            if ($digitMatcher->find()) {
1853
                $normalizedGroup = $this->normalizeDigitsOnly($digitMatcher->group(1));
1854 4
                if ($normalizedGroup == "0") {
1855 2
                    return false;
1856
                }
1857
            }
1858
            $number = substr($number, $matchEnd);
1859 3
            return true;
1860
        }
1861 2431
        return false;
1862
    }
1863
1864
    /**
1865
     * Extracts country calling code from fullNumber, returns it and places the remaining number in  nationalNumber.
1866
     * It assumes that the leading plus sign or IDD has already been removed.
1867
     * Returns 0 if fullNumber doesn't start with a valid country calling code, and leaves nationalNumber unmodified.
1868
     * @param string $fullNumber
1869
     * @param string $nationalNumber
1870
     * @return int
1871
     */
1872 267
    protected function extractCountryCode(&$fullNumber, &$nationalNumber)
1873
    {
1874
        if ((mb_strlen($fullNumber) == 0) || ($fullNumber[0] == '0')) {
1875
            // Country codes do not begin with a '0'.
1876 1
            return 0;
1877
        }
1878
        $numberLength = mb_strlen($fullNumber);
1879
        for ($i = 1; $i <= static::MAX_LENGTH_COUNTRY_CODE && $i <= $numberLength; $i++) {
1880
            $potentialCountryCode = (int)substr($fullNumber, 0, $i);
1881 27
            if (isset($this->countryCallingCodeToRegionCodeMap[$potentialCountryCode])) {
1882
                $nationalNumber .= substr($fullNumber, $i);
1883 267
                return $potentialCountryCode;
1884
            }
1885 27
        }
1886 1
        return 0;
1887
    }
1888
1889
    /**
1890
     * Strips any national prefix (such as 0, 1) present in the number provided.
1891
     *
1892
     * @param string $number the normalized telephone number that we wish to strip any national
1893
     *     dialing prefix from
1894
     * @param PhoneMetadata $metadata the metadata for the region that we think this number is from
1895
     * @param string $carrierCode a place to insert the carrier code if one is extracted
1896
     * @return bool true if a national prefix or carrier code (or both) could be extracted.
1897
     */
1898 2167
    public function maybeStripNationalPrefixAndCarrierCode(&$number, PhoneMetadata $metadata, &$carrierCode)
1899
    {
1900
        $numberLength = mb_strlen($number);
1901
        $possibleNationalPrefix = $metadata->getNationalPrefixForParsing();
1902 778
        if ($numberLength == 0 || $possibleNationalPrefix === null || mb_strlen($possibleNationalPrefix) == 0) {
1903
            // Early return for numbers of zero length.
1904 781
            return false;
1905
        }
1906
1907
        // Attempt to parse the first digits as a national prefix.
1908
        $prefixMatcher = new Matcher($possibleNationalPrefix, $number);
1909
        if ($prefixMatcher->lookingAt()) {
1910
            $nationalNumberRule = $metadata->getGeneralDesc()->getNationalNumberPattern();
1911
            // Check if the original number is viable.
1912
            $nationalNumberRuleMatcher = new Matcher($nationalNumberRule, $number);
1913
            $isViableOriginalNumber = $nationalNumberRuleMatcher->matches();
1914
            // $prefixMatcher->group($numOfGroups) === null implies nothing was captured by the capturing
1915
            // groups in $possibleNationalPrefix; therefore, no transformation is necessary, and we just
1916
            // remove the national prefix
1917
            $numOfGroups = $prefixMatcher->groupCount();
1918
            $transformRule = $metadata->getNationalPrefixTransformRule();
1919 48
            if ($transformRule === null
1920
                || mb_strlen($transformRule) == 0
1921
                || $prefixMatcher->group($numOfGroups - 1) === null
1922
            ) {
1923
                // If the original number was viable, and the resultant number is not, we return.
1924
                $matcher = new Matcher($nationalNumberRule, substr($number, $prefixMatcher->end()));
1925 18
                if ($isViableOriginalNumber && !$matcher->matches()) {
1926 13
                    return false;
1927
                }
1928 34
                if ($carrierCode !== null && $numOfGroups > 0 && $prefixMatcher->group($numOfGroups) !== null) {
1929
                    $carrierCode .= $prefixMatcher->group(1);
1930
                }
1931
1932
                $number = substr($number, $prefixMatcher->end());
1933 35
                return true;
1934
            } else {
1935
                // Check that the resultant number is still viable. If not, return. Check this by copying
1936
                // the string and making the transformation on the copy first.
1937 5
                $transformedNumber = $number;
1938
                $transformedNumber = substr_replace(
1939
                    $transformedNumber,
1940 5
                    $prefixMatcher->replaceFirst($transformRule),
1941 5
                    0,
1942
                    $numberLength
1943
                );
1944
                $matcher = new Matcher($nationalNumberRule, $transformedNumber);
1945 1
                if ($isViableOriginalNumber && !$matcher->matches()) {
1946
                    return false;
1947
                }
1948 5
                if ($carrierCode !== null && $numOfGroups > 1) {
1949
                    $carrierCode .= $prefixMatcher->group(1);
1950
                }
1951
                $number = substr_replace($number, $transformedNumber, 0, mb_strlen($number));
1952 5
                return true;
1953
            }
1954
        }
1955 1349
        return false;
1956 2167
    }
1957
1958
    /**
1959
     * Helper method to check a number against a particular pattern and determine whether it matches,
1960
     * or is too short or too long. Currently, if a number pattern suggests that numbers of length 7
1961
     * and 10 are possible, and a number in between these possible lengths is entered, such as of
1962
     * length 8, this will return TOO_LONG.
1963
     * @param string $numberPattern
1964
     * @param string $number
1965
     * @return int ValidationResult
1966
     */
1967 1733
    protected function testNumberLengthAgainstPattern($numberPattern, $number)
1968
    {
1969
        $numberMatcher = new Matcher($numberPattern, $number);
1970
        if ($numberMatcher->matches()) {
1971 1733
            return ValidationResult::IS_POSSIBLE;
1972
        }
1973
        if ($numberMatcher->lookingAt()) {
1974 34
            return ValidationResult::TOO_LONG;
1975
        } else {
1976 411
            return ValidationResult::TOO_SHORT;
1977
        }
1978
    }
1979
1980
    /**
1981
     * Returns a list with the region codes that match the specific country calling code. For
1982
     * non-geographical country calling codes, the region code 001 is returned. Also, in the case
1983
     * of no region code being found, an empty list is returned.
1984
     * @param int $countryCallingCode
1985
     * @return array
1986
     */
1987 8
    public function getRegionCodesForCountryCode($countryCallingCode)
1988
    {
1989 8
        $regionCodes = isset($this->countryCallingCodeToRegionCodeMap[$countryCallingCode]) ? $this->countryCallingCodeToRegionCodeMap[$countryCallingCode] : null;
1990 8
        return $regionCodes === null ? array() : $regionCodes;
1991
    }
1992
1993
    /**
1994
     * Returns the country calling code for a specific region. For example, this would be 1 for the
1995
     * United States, and 64 for New Zealand. Assumes the region is already valid.
1996
     *
1997
     * @param string $regionCode the region that we want to get the country calling code for
1998
     * @return int the country calling code for the region denoted by regionCode
1999
     */
2000
    public function getCountryCodeForRegion($regionCode)
2001
    {
2002
        if (!$this->isValidRegionCode($regionCode)) {
2003
            return 0;
2004
        }
2005
        return $this->getCountryCodeForValidRegion($regionCode);
2006
    }
2007
2008
    /**
2009
     * Returns the country calling code for a specific region. For example, this would be 1 for the
2010
     * United States, and 64 for New Zealand. Assumes the region is already valid.
2011
     *
2012
     * @param string $regionCode the region that we want to get the country calling code for
2013
     * @return int the country calling code for the region denoted by regionCode
2014
     * @throws \InvalidArgumentException if the region is invalid
2015
     */
2016 1546
    protected function getCountryCodeForValidRegion($regionCode)
2017
    {
2018
        $metadata = $this->getMetadataForRegion($regionCode);
2019 1546
        if ($metadata === null) {
2020
            throw new \InvalidArgumentException("Invalid region code: " . $regionCode);
2021
        }
2022
        return $metadata->getCountryCode();
2023
    }
2024
2025
    /**
2026
     * Returns a number formatted in such a way that it can be dialed from a mobile phone in a
2027
     * specific region. If the number cannot be reached from the region (e.g. some countries block
2028
     * toll-free numbers from being called outside of the country), the method returns an empty
2029
     * string.
2030
     *
2031
     * @param PhoneNumber $number the phone number to be formatted
2032
     * @param string $regionCallingFrom the region where the call is being placed
2033
     * @param boolean $withFormatting whether the number should be returned with formatting symbols, such as
2034
     *     spaces and dashes.
2035
     * @return string the formatted phone number
2036
     */
2037 1
    public function formatNumberForMobileDialing(PhoneNumber $number, $regionCallingFrom, $withFormatting)
2038
    {
2039
        $countryCallingCode = $number->getCountryCode();
2040
        if (!$this->hasValidCountryCallingCode($countryCallingCode)) {
2041
            return $number->hasRawInput() ? $number->getRawInput() : "";
2042
        }
2043
2044
        $formattedNumber = "";
2045
        // Clear the extension, as that part cannot normally be dialed together with the main number.
2046
        $numberNoExt = new PhoneNumber();
2047
        $numberNoExt->mergeFrom($number)->clearExtension();
2048
        $regionCode = $this->getRegionCodeForCountryCode($countryCallingCode);
2049
        $numberType = $this->getNumberType($numberNoExt);
2050
        $isValidNumber = ($numberType !== PhoneNumberType::UNKNOWN);
2051
        if ($regionCallingFrom == $regionCode) {
2052
            $isFixedLineOrMobile = ($numberType == PhoneNumberType::FIXED_LINE) || ($numberType == PhoneNumberType::MOBILE) || ($numberType == PhoneNumberType::FIXED_LINE_OR_MOBILE);
2053
            // Carrier codes may be needed in some countries. We handle this here.
2054
            if ($regionCode == "CO" && $numberType == PhoneNumberType::FIXED_LINE) {
2055
                $formattedNumber = $this->formatNationalNumberWithCarrierCode(
2056
                    $numberNoExt,
2057
                    static::COLOMBIA_MOBILE_TO_FIXED_LINE_PREFIX
2058
                );
2059
            } elseif ($regionCode == "BR" && $isFixedLineOrMobile) {
2060
                // Brazilian fixed line and mobile numbers need to be dialed with a carrier code when
2061
                // called within Brazil. Without that, most of the carriers won't connect the call.
2062
                // Because of that, we return an empty string here.
2063
                $formattedNumber = $numberNoExt->hasPreferredDomesticCarrierCode(
2064
                ) ? $this->formatNationalNumberWithCarrierCode($numberNoExt, "") : "";
2065
            } elseif ($isValidNumber && $regionCode == "HU") {
2066
                // The national format for HU numbers doesn't contain the national prefix, because that is
2067
                // how numbers are normally written down. However, the national prefix is obligatory when
2068
                // dialing from a mobile phone, except for short numbers. As a result, we add it back here
2069
                // if it is a valid regular length phone number.
2070 1
                $formattedNumber = $this->getNddPrefixForRegion(
2071
                        $regionCode,
2072 1
                        true /* strip non-digits */
2073
                    ) . " " . $this->format($numberNoExt, PhoneNumberFormat::NATIONAL);
2074
            } elseif ($countryCallingCode === static::NANPA_COUNTRY_CODE) {
2075
                // For NANPA countries, we output international format for numbers that can be dialed
2076
                // internationally, since that always works, except for numbers which might potentially be
2077
                // short numbers, which are always dialled in national format.
2078
                $regionMetadata = $this->getMetadataForRegion($regionCallingFrom);
2079
                if ($this->canBeInternationallyDialled($numberNoExt) &&
2080
                    !$this->isShorterThanPossibleNormalNumber(
2081
                        $regionMetadata,
0 ignored issues
show
Bug introduced by
It seems like $regionMetadata defined by $this->getMetadataForRegion($regionCallingFrom) on line 2078 can be null; however, libphonenumber\PhoneNumb...nPossibleNormalNumber() 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...
2082
                        $this->getNationalSignificantNumber($numberNoExt)
2083
                    )
2084
                ) {
2085
                    $formattedNumber = $this->format($numberNoExt, PhoneNumberFormat::INTERNATIONAL);
2086
                } else {
2087
                    $formattedNumber = $this->format($numberNoExt, PhoneNumberFormat::NATIONAL);
2088
                }
2089
            } else {
2090
                // For non-geographical countries, Mexican and Chilean fixed line and mobile numbers, we
2091
                // output international format for numbers that can be dialed internationally as that always
2092
                // works.
2093
                if (($regionCode == static::REGION_CODE_FOR_NON_GEO_ENTITY ||
2094
                        // MX fixed line and mobile numbers should always be formatted in international format,
2095
                        // even when dialed within MX. For national format to work, a carrier code needs to be
2096
                        // used, and the correct carrier code depends on if the caller and callee are from the
2097
                        // same local area. It is trickier to get that to work correctly than using
2098
                        // international format, which is tested to work fine on all carriers.
2099
                        // CL fixed line numbers need the national prefix when dialing in the national format,
2100
                        // but don't have it when used for display. The reverse is true for mobile numbers.
2101
                        // As a result, we output them in the international format to make it work.
2102
                        (($regionCode == "MX" || $regionCode == "CL") && $isFixedLineOrMobile)) && $this->canBeInternationallyDialled(
2103
                        $numberNoExt
2104
                    )
2105
                ) {
2106
                    $formattedNumber = $this->format($numberNoExt, PhoneNumberFormat::INTERNATIONAL);
2107
                } else {
2108
                    $formattedNumber = $this->format($numberNoExt, PhoneNumberFormat::NATIONAL);
2109
                }
2110
            }
2111
        } elseif ($isValidNumber && $this->canBeInternationallyDialled($numberNoExt)) {
2112
            // We assume that short numbers are not diallable from outside their region, so if a number
2113
            // is not a valid regular length phone number, we treat it as if it cannot be internationally
2114
            // dialled.
2115
            return $withFormatting ?
2116 1
                $this->format($numberNoExt, PhoneNumberFormat::INTERNATIONAL) :
2117
                $this->format($numberNoExt, PhoneNumberFormat::E164);
2118
        }
2119
        return $withFormatting ? $formattedNumber : $this->normalizeDiallableCharsOnly($formattedNumber);
2120
    }
2121
2122
    /**
2123
     * Formats a phone number in national format for dialing using the carrier as specified in the
2124
     * {@code carrierCode}. The {@code carrierCode} will always be used regardless of whether the
2125
     * phone number already has a preferred domestic carrier code stored. If {@code carrierCode}
2126
     * contains an empty string, returns the number in national format without any carrier code.
2127
     *
2128
     * @param PhoneNumber $number the phone number to be formatted
2129
     * @param string $carrierCode the carrier selection code to be used
2130
     * @return string the formatted phone number in national format for dialing using the carrier as
2131
     * specified in the {@code carrierCode}
2132
     */
2133 1
    public function formatNationalNumberWithCarrierCode(PhoneNumber $number, $carrierCode)
2134
    {
2135
        $countryCallingCode = $number->getCountryCode();
2136
        $nationalSignificantNumber = $this->getNationalSignificantNumber($number);
2137
        if (!$this->hasValidCountryCallingCode($countryCallingCode)) {
2138 1
            return $nationalSignificantNumber;
2139
        }
2140
2141
        // Note getRegionCodeForCountryCode() is used because formatting information for regions which
2142
        // share a country calling code is contained by only one region for performance reasons. For
2143
        // example, for NANPA regions it will be contained in the metadata for US.
2144
        $regionCode = $this->getRegionCodeForCountryCode($countryCallingCode);
2145
        // Metadata cannot be null because the country calling code is valid.
2146
        $metadata = $this->getMetadataForRegionOrCallingCode($countryCallingCode, $regionCode);
2147
2148
        $formattedNumber = $this->formatNsn(
2149
            $nationalSignificantNumber,
2150
            $metadata,
0 ignored issues
show
Bug introduced by
It seems like $metadata defined by $this->getMetadataForReg...llingCode, $regionCode) on line 2146 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...
2151
            PhoneNumberFormat::NATIONAL,
2152
            $carrierCode
2153
        );
2154
        $this->maybeAppendFormattedExtension($number, $metadata, PhoneNumberFormat::NATIONAL, $formattedNumber);
2155
        $this->prefixNumberWithCountryCallingCode(
2156
            $countryCallingCode,
2157
            PhoneNumberFormat::NATIONAL,
2158
            $formattedNumber
2159
        );
2160
        return $formattedNumber;
2161
    }
2162
2163
    /**
2164
     * Formats a phone number in national format for dialing using the carrier as specified in the
2165
     * preferredDomesticCarrierCode field of the PhoneNumber object passed in. If that is missing,
2166
     * use the {@code fallbackCarrierCode} passed in instead. If there is no
2167
     * {@code preferredDomesticCarrierCode}, and the {@code fallbackCarrierCode} contains an empty
2168
     * string, return the number in national format without any carrier code.
2169
     *
2170
     * <p>Use {@link #formatNationalNumberWithCarrierCode} instead if the carrier code passed in
2171
     * should take precedence over the number's {@code preferredDomesticCarrierCode} when formatting.
2172
     *
2173
     * @param PhoneNumber $number the phone number to be formatted
2174
     * @param string $fallbackCarrierCode the carrier selection code to be used, if none is found in the
2175
     *     phone number itself
2176
     * @return string the formatted phone number in national format for dialing using the number's
2177
     *     {@code preferredDomesticCarrierCode}, or the {@code fallbackCarrierCode} passed in if
2178
     *     none is found
2179
     */
2180
    public function formatNationalNumberWithPreferredCarrierCode(PhoneNumber $number, $fallbackCarrierCode)
2181
    {
2182
        return $this->formatNationalNumberWithCarrierCode(
2183
            $number,
2184
            $number->hasPreferredDomesticCarrierCode()
2185
                ? $number->getPreferredDomesticCarrierCode()
2186
                : $fallbackCarrierCode
2187
        );
2188
    }
2189
2190
    /**
2191
     * Returns true if the number can be dialled from outside the region, or unknown. If the number
2192
     * can only be dialled from within the region, returns false. Does not check the number is a valid
2193
     * number.
2194
     * TODO: Make this method public when we have enough metadata to make it worthwhile.
2195
     *
2196
     * @param PhoneNumber $number the phone-number for which we want to know whether it is diallable from outside the region
2197
     * @return bool
2198
     */
2199 29
    public function canBeInternationallyDialled(PhoneNumber $number)
2200
    {
2201
        $metadata = $this->getMetadataForRegion($this->getRegionCodeForNumber($number));
2202 29
        if ($metadata === null) {
2203
            // Note numbers belonging to non-geographical entities (e.g. +800 numbers) are always
2204
            // internationally diallable, and will be caught here.
2205
            return true;
2206
        }
2207
        $nationalSignificantNumber = $this->getNationalSignificantNumber($number);
2208
        return !$this->isNumberMatchingDesc($nationalSignificantNumber, $metadata->getNoInternationalDialling());
2209 29
    }
2210
2211
    /**
2212
     * Normalizes a string of characters representing a phone number. This strips all characters which
2213
     * are not diallable on a mobile phone keypad (including all non-ASCII digits).
2214
     *
2215
     * @param string $number a string of characters representing a phone number
2216
     * @return string the normalized string version of the phone number
2217
     */
2218
    public static function normalizeDiallableCharsOnly($number)
2219
    {
2220
        return static::normalizeHelper($number, static::$DIALLABLE_CHAR_MAPPINGS, true /* remove non matches */);
2221
    }
2222
2223
    /**
2224
     * Formats a phone number for out-of-country dialing purposes.
2225
     *
2226
     * Note that in this version, if the number was entered originally using alpha characters and
2227
     * this version of the number is stored in raw_input, this representation of the number will be
2228
     * used rather than the digit representation. Grouping information, as specified by characters
2229
     * such as "-" and " ", will be retained.
2230
     *
2231
     * <p><b>Caveats:</b></p>
2232
     * <ul>
2233
     *  <li> This will not produce good results if the country calling code is both present in the raw
2234
     *       input _and_ is the start of the national number. This is not a problem in the regions
2235
     *       which typically use alpha numbers.
2236
     *  <li> This will also not produce good results if the raw input has any grouping information
2237
     *       within the first three digits of the national number, and if the function needs to strip
2238
     *       preceding digits/words in the raw input before these digits. Normally people group the
2239
     *       first three digits together so this is not a huge problem - and will be fixed if it
2240
     *       proves to be so.
2241
     * </ul>
2242
     *
2243
     * @param PhoneNumber $number the phone number that needs to be formatted
2244
     * @param String $regionCallingFrom the region where the call is being placed
2245
     * @return String the formatted phone number
2246
     */
2247 1
    public function formatOutOfCountryKeepingAlphaChars(PhoneNumber $number, $regionCallingFrom)
2248
    {
2249
        $rawInput = $number->getRawInput();
2250
        // If there is no raw input, then we can't keep alpha characters because there aren't any.
2251
        // In this case, we return formatOutOfCountryCallingNumber.
2252
        if (mb_strlen($rawInput) == 0) {
2253
            return $this->formatOutOfCountryCallingNumber($number, $regionCallingFrom);
2254
        }
2255
        $countryCode = $number->getCountryCode();
2256
        if (!$this->hasValidCountryCallingCode($countryCode)) {
2257 1
            return $rawInput;
2258
        }
2259
        // Strip any prefix such as country calling code, IDD, that was present. We do this by comparing
2260
        // the number in raw_input with the parsed number.
2261
        // To do this, first we normalize punctuation. We retain number grouping symbols such as " "
2262
        // only.
2263
        $rawInput = $this->normalizeHelper($rawInput, static::$ALL_PLUS_NUMBER_GROUPING_SYMBOLS, true);
2264
        // Now we trim everything before the first three digits in the parsed number. We choose three
2265
        // because all valid alpha numbers have 3 digits at the start - if it does not, then we don't
2266
        // trim anything at all. Similarly, if the national number was less than three digits, we don't
2267
        // trim anything at all.
2268
        $nationalNumber = $this->getNationalSignificantNumber($number);
2269
        if (mb_strlen($nationalNumber) > 3) {
2270
            $firstNationalNumberDigit = strpos($rawInput, substr($nationalNumber, 0, 3));
2271
            if ($firstNationalNumberDigit !== false) {
2272
                $rawInput = substr($rawInput, $firstNationalNumberDigit);
2273
            }
2274
        }
2275
        $metadataForRegionCallingFrom = $this->getMetadataForRegion($regionCallingFrom);
2276
        if ($countryCode == static::NANPA_COUNTRY_CODE) {
2277
            if ($this->isNANPACountry($regionCallingFrom)) {
2278
                return $countryCode . " " . $rawInput;
2279
            }
2280
        } elseif ($metadataForRegionCallingFrom !== null &&
2281
            $countryCode == $this->getCountryCodeForValidRegion($regionCallingFrom)
2282
        ) {
2283
            $formattingPattern =
2284
                $this->chooseFormattingPatternForNumber(
2285
                    $metadataForRegionCallingFrom->numberFormats(),
2286
                    $nationalNumber
2287
                );
2288
            if ($formattingPattern === null) {
2289
                // If no pattern above is matched, we format the original input.
2290 1
                return $rawInput;
2291
            }
2292
            $newFormat = new NumberFormat();
2293
            $newFormat->mergeFrom($formattingPattern);
2294
            // The first group is the first group of digits that the user wrote together.
2295
            $newFormat->setPattern("(\\d+)(.*)");
2296
            // Here we just concatenate them back together after the national prefix has been fixed.
2297
            $newFormat->setFormat("$1$2");
2298
            // Now we format using this pattern instead of the default pattern, but with the national
2299
            // prefix prefixed if necessary.
2300
            // This will not work in the cases where the pattern (and not the leading digits) decide
2301
            // whether a national prefix needs to be used, since we have overridden the pattern to match
2302
            // anything, but that is not the case in the metadata to date.
2303
            return $this->formatNsnUsingPattern($rawInput, $newFormat, PhoneNumberFormat::NATIONAL);
2304
        }
2305
        $internationalPrefixForFormatting = "";
2306
        // If an unsupported region-calling-from is entered, or a country with multiple international
2307
        // prefixes, the international format of the number is returned, unless there is a preferred
2308
        // international prefix.
2309
        if ($metadataForRegionCallingFrom !== null) {
2310
            $internationalPrefix = $metadataForRegionCallingFrom->getInternationalPrefix();
2311
            $uniqueInternationalPrefixMatcher = new Matcher(static::UNIQUE_INTERNATIONAL_PREFIX, $internationalPrefix);
2312
            $internationalPrefixForFormatting =
2313
                $uniqueInternationalPrefixMatcher->matches()
2314
                    ? $internationalPrefix
2315
                    : $metadataForRegionCallingFrom->getPreferredInternationalPrefix();
2316
        }
2317
        $formattedNumber = $rawInput;
2318
        $regionCode = $this->getRegionCodeForCountryCode($countryCode);
2319
        // Metadata cannot be null because the country calling code is valid.
2320
        $metadataForRegion = $this->getMetadataForRegionOrCallingCode($countryCode, $regionCode);
2321
        $this->maybeAppendFormattedExtension(
2322
            $number,
2323
            $metadataForRegion,
2324
            PhoneNumberFormat::INTERNATIONAL,
2325
            $formattedNumber
2326
        );
2327
        if (mb_strlen($internationalPrefixForFormatting) > 0) {
2328
            $formattedNumber = $internationalPrefixForFormatting . " " . $countryCode . " " . $formattedNumber;
2329
        } else {
2330
            // Invalid region entered as country-calling-from (so no metadata was found for it) or the
2331
            // region chosen has multiple international dialling prefixes.
2332
            $this->prefixNumberWithCountryCallingCode(
2333
                $countryCode,
2334
                PhoneNumberFormat::INTERNATIONAL,
2335
                $formattedNumber
2336
            );
2337
        }
2338
        return $formattedNumber;
2339
    }
2340
2341
    /**
2342
     * Formats a phone number for out-of-country dialing purposes. If no regionCallingFrom is
2343
     * supplied, we format the number in its INTERNATIONAL format. If the country calling code is the
2344
     * same as that of the region where the number is from, then NATIONAL formatting will be applied.
2345
     *
2346
     * <p>If the number itself has a country calling code of zero or an otherwise invalid country
2347
     * calling code, then we return the number with no formatting applied.
2348
     *
2349
     * <p>Note this function takes care of the case for calling inside of NANPA and between Russia and
2350
     * Kazakhstan (who share the same country calling code). In those cases, no international prefix
2351
     * is used. For regions which have multiple international prefixes, the number in its
2352
     * INTERNATIONAL format will be returned instead.
2353
     *
2354
     * @param PhoneNumber $number the phone number to be formatted
2355
     * @param string $regionCallingFrom the region where the call is being placed
2356
     * @return string  the formatted phone number
2357
     */
2358 3
    public function formatOutOfCountryCallingNumber(PhoneNumber $number, $regionCallingFrom)
2359
    {
2360
        if (!$this->isValidRegionCode($regionCallingFrom)) {
2361
            return $this->format($number, PhoneNumberFormat::INTERNATIONAL);
2362
        }
2363
        $countryCallingCode = $number->getCountryCode();
2364
        $nationalSignificantNumber = $this->getNationalSignificantNumber($number);
2365
        if (!$this->hasValidCountryCallingCode($countryCallingCode)) {
2366
            return $nationalSignificantNumber;
2367
        }
2368 2
        if ($countryCallingCode == static::NANPA_COUNTRY_CODE) {
2369
            if ($this->isNANPACountry($regionCallingFrom)) {
2370
                // For NANPA regions, return the national format for these regions but prefix it with the
2371
                // country calling code.
2372
                return $countryCallingCode . " " . $this->format($number, PhoneNumberFormat::NATIONAL);
2373
            }
2374
        } elseif ($countryCallingCode == $this->getCountryCodeForValidRegion($regionCallingFrom)) {
2375
            // If regions share a country calling code, the country calling code need not be dialled.
2376
            // This also applies when dialling within a region, so this if clause covers both these cases.
2377
            // Technically this is the case for dialling from La Reunion to other overseas departments of
2378
            // France (French Guiana, Martinique, Guadeloupe), but not vice versa - so we don't cover this
2379
            // edge case for now and for those cases return the version including country calling code.
2380
            // Details here: http://www.petitfute.com/voyage/225-info-pratiques-reunion
2381
            return $this->format($number, PhoneNumberFormat::NATIONAL);
2382 2
        }
2383
        // Metadata cannot be null because we checked 'isValidRegionCode()' above.
2384
        $metadataForRegionCallingFrom = $this->getMetadataForRegion($regionCallingFrom);
2385
2386
        $internationalPrefix = $metadataForRegionCallingFrom->getInternationalPrefix();
2387
2388
        // For regions that have multiple international prefixes, the international format of the
2389
        // number is returned, unless there is a preferred international prefix.
2390 3
        $internationalPrefixForFormatting = "";
2391
        $uniqueInternationalPrefixMatcher = new Matcher(static::UNIQUE_INTERNATIONAL_PREFIX, $internationalPrefix);
2392
2393
        if ($uniqueInternationalPrefixMatcher->matches()) {
2394 2
            $internationalPrefixForFormatting = $internationalPrefix;
2395
        } elseif ($metadataForRegionCallingFrom->hasPreferredInternationalPrefix()) {
2396
            $internationalPrefixForFormatting = $metadataForRegionCallingFrom->getPreferredInternationalPrefix();
2397 2
        }
2398
2399
        $regionCode = $this->getRegionCodeForCountryCode($countryCallingCode);
2400
        // Metadata cannot be null because the country calling code is valid.
2401
        $metadataForRegion = $this->getMetadataForRegionOrCallingCode($countryCallingCode, $regionCode);
2402 3
        $formattedNationalNumber = $this->formatNsn(
2403
            $nationalSignificantNumber,
2404
            $metadataForRegion,
0 ignored issues
show
Bug introduced by
It seems like $metadataForRegion defined by $this->getMetadataForReg...llingCode, $regionCode) on line 2401 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...
2405 3
            PhoneNumberFormat::INTERNATIONAL
2406
        );
2407 3
        $formattedNumber = $formattedNationalNumber;
2408 3
        $this->maybeAppendFormattedExtension(
2409
            $number,
2410
            $metadataForRegion,
2411 3
            PhoneNumberFormat::INTERNATIONAL,
2412
            $formattedNumber
2413
        );
2414
        if (mb_strlen($internationalPrefixForFormatting) > 0) {
2415 3
            $formattedNumber = $internationalPrefixForFormatting . " " . $countryCallingCode . " " . $formattedNumber;
2416
        } else {
2417 1
            $this->prefixNumberWithCountryCallingCode(
2418
                $countryCallingCode,
2419 1
                PhoneNumberFormat::INTERNATIONAL,
2420
                $formattedNumber
2421
            );
2422 3
        }
2423 3
        return $formattedNumber;
2424 2
    }
2425
2426
    /**
2427
     * Checks if this is a region under the North American Numbering Plan Administration (NANPA).
2428
     * @param string $regionCode
2429
     * @return boolean true if regionCode is one of the regions under NANPA
2430
     */
2431
    public function isNANPACountry($regionCode)
2432
    {
2433
        return in_array($regionCode, $this->nanpaRegions);
2434
    }
2435
2436
    /**
2437
     * Formats a phone number using the original phone number format that the number is parsed from.
2438
     * The original format is embedded in the country_code_source field of the PhoneNumber object
2439
     * passed in. If such information is missing, the number will be formatted into the NATIONAL
2440
     * format by default. When the number contains a leading zero and this is unexpected for this
2441
     * country, or we don't have a formatting pattern for the number, the method returns the raw input
2442
     * when it is available.
2443
     *
2444
     * Note this method guarantees no digit will be inserted, removed or modified as a result of
2445
     * formatting.
2446
     *
2447
     * @param PhoneNumber $number the phone number that needs to be formatted in its original number format
2448
     * @param string $regionCallingFrom the region whose IDD needs to be prefixed if the original number
2449
     *     has one
2450
     * @return string the formatted phone number in its original number format
2451
     */
2452 1
    public function formatInOriginalFormat(PhoneNumber $number, $regionCallingFrom)
2453
    {
2454
        if ($number->hasRawInput() &&
2455
            ($this->hasUnexpectedItalianLeadingZero($number) || !$this->hasFormattingPatternForNumber($number))
2456
        ) {
2457
            // We check if we have the formatting pattern because without that, we might format the number
2458
            // as a group without national prefix.
2459
            return $number->getRawInput();
2460
        }
2461
        if (!$number->hasCountryCodeSource()) {
2462
            return $this->format($number, PhoneNumberFormat::NATIONAL);
2463
        }
2464
        switch ($number->getCountryCodeSource()) {
2465
            case CountryCodeSource::FROM_NUMBER_WITH_PLUS_SIGN:
2466
                $formattedNumber = $this->format($number, PhoneNumberFormat::INTERNATIONAL);
2467
                break;
2468
            case CountryCodeSource::FROM_NUMBER_WITH_IDD:
2469
                $formattedNumber = $this->formatOutOfCountryCallingNumber($number, $regionCallingFrom);
2470
                break;
2471
            case CountryCodeSource::FROM_NUMBER_WITHOUT_PLUS_SIGN:
2472
                $formattedNumber = substr($this->format($number, PhoneNumberFormat::INTERNATIONAL), 1);
2473
                break;
2474
            case CountryCodeSource::FROM_DEFAULT_COUNTRY:
2475
                // Fall-through to default case.
2476
            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...
2477
2478
                $regionCode = $this->getRegionCodeForCountryCode($number->getCountryCode());
2479
                // We strip non-digits from the NDD here, and from the raw input later, so that we can
2480
                // compare them easily.
2481
                $nationalPrefix = $this->getNddPrefixForRegion($regionCode, true /* strip non-digits */);
2482
                $nationalFormat = $this->format($number, PhoneNumberFormat::NATIONAL);
2483
                if ($nationalPrefix === null || mb_strlen($nationalPrefix) == 0) {
2484
                    // If the region doesn't have a national prefix at all, we can safely return the national
2485
                    // format without worrying about a national prefix being added.
2486 1
                    $formattedNumber = $nationalFormat;
2487 1
                    break;
2488
                }
2489
                // Otherwise, we check if the original number was entered with a national prefix.
2490
                if ($this->rawInputContainsNationalPrefix(
2491
                    $number->getRawInput(),
2492
                    $nationalPrefix,
2493
                    $regionCode
2494
                )
2495
                ) {
2496
                    // If so, we can safely return the national format.
2497
                    $formattedNumber = $nationalFormat;
2498
                    break;
2499
                }
2500
                // Metadata cannot be null here because getNddPrefixForRegion() (above) returns null if
2501
                // there is no metadata for the region.
2502
                $metadata = $this->getMetadataForRegion($regionCode);
2503
                $nationalNumber = $this->getNationalSignificantNumber($number);
2504
                $formatRule = $this->chooseFormattingPatternForNumber($metadata->numberFormats(), $nationalNumber);
2505
                // The format rule could still be null here if the national number was 0 and there was no
2506
                // raw input (this should not be possible for numbers generated by the phonenumber library
2507
                // as they would also not have a country calling code and we would have exited earlier).
2508
                if ($formatRule === null) {
2509
                    $formattedNumber = $nationalFormat;
2510
                    break;
2511
                }
2512
                // When the format we apply to this number doesn't contain national prefix, we can just
2513
                // return the national format.
2514
                // TODO: Refactor the code below with the code in isNationalPrefixPresentIfRequired.
2515
                $candidateNationalPrefixRule = $formatRule->getNationalPrefixFormattingRule();
2516
                // We assume that the first-group symbol will never be _before_ the national prefix.
2517
                $indexOfFirstGroup = strpos($candidateNationalPrefixRule, '$1');
2518
                if ($indexOfFirstGroup <= 0) {
2519
                    $formattedNumber = $nationalFormat;
2520
                    break;
2521
                }
2522
                $candidateNationalPrefixRule = substr($candidateNationalPrefixRule, 0, $indexOfFirstGroup);
2523
                $candidateNationalPrefixRule = $this->normalizeDigitsOnly($candidateNationalPrefixRule);
2524
                if (mb_strlen($candidateNationalPrefixRule) == 0) {
2525
                    // National prefix not used when formatting this number.
2526
                    $formattedNumber = $nationalFormat;
2527
                    break;
2528
                }
2529
                // Otherwise, we need to remove the national prefix from our output.
2530
                $numFormatCopy = new NumberFormat();
2531
                $numFormatCopy->mergeFrom($formatRule);
2532
                $numFormatCopy->clearNationalPrefixFormattingRule();
2533
                $numberFormats = array();
2534
                $numberFormats[] = $numFormatCopy;
2535
                $formattedNumber = $this->formatByPattern($number, PhoneNumberFormat::NATIONAL, $numberFormats);
2536
                break;
2537
        }
2538
        $rawInput = $number->getRawInput();
2539
        // If no digit is inserted/removed/modified as a result of our formatting, we return the
2540
        // formatted phone number; otherwise we return the raw input the user entered.
2541
        if ($formattedNumber !== null && mb_strlen($rawInput) > 0) {
2542
            $normalizedFormattedNumber = $this->normalizeDiallableCharsOnly($formattedNumber);
2543
            $normalizedRawInput = $this->normalizeDiallableCharsOnly($rawInput);
2544
            if ($normalizedFormattedNumber != $normalizedRawInput) {
2545
                $formattedNumber = $rawInput;
2546
            }
2547
        }
2548
        return $formattedNumber;
2549
    }
2550
2551
    /**
2552
     * Returns true if a number is from a region whose national significant number couldn't contain a
2553
     * leading zero, but has the italian_leading_zero field set to true.
2554
     * @param PhoneNumber $number
2555
     * @return bool
2556
     */
2557
    protected function hasUnexpectedItalianLeadingZero(PhoneNumber $number)
2558
    {
2559
        return $number->isItalianLeadingZero() && !$this->isLeadingZeroPossible($number->getCountryCode());
2560
    }
2561
2562
    /**
2563
     * Checks whether the country calling code is from a region whose national significant number
2564
     * could contain a leading zero. An example of such a region is Italy. Returns false if no
2565
     * metadata for the country is found.
2566
     * @param int $countryCallingCode
2567
     * @return bool
2568
     */
2569 1
    public function isLeadingZeroPossible($countryCallingCode)
2570
    {
2571
        $mainMetadataForCallingCode = $this->getMetadataForRegionOrCallingCode(
2572
            $countryCallingCode,
2573
            $this->getRegionCodeForCountryCode($countryCallingCode)
2574
        );
2575
        if ($mainMetadataForCallingCode === null) {
2576 1
            return false;
2577
        }
2578
        return (bool)$mainMetadataForCallingCode->isLeadingZeroPossible();
2579
    }
2580
2581
    /**
2582
     * @param PhoneNumber $number
2583
     * @return bool
2584
     */
2585
    protected function hasFormattingPatternForNumber(PhoneNumber $number)
2586
    {
2587
        $countryCallingCode = $number->getCountryCode();
2588
        $phoneNumberRegion = $this->getRegionCodeForCountryCode($countryCallingCode);
2589
        $metadata = $this->getMetadataForRegionOrCallingCode($countryCallingCode, $phoneNumberRegion);
2590
        if ($metadata === null) {
2591
            return false;
2592
        }
2593
        $nationalNumber = $this->getNationalSignificantNumber($number);
2594
        $formatRule = $this->chooseFormattingPatternForNumber($metadata->numberFormats(), $nationalNumber);
2595
        return $formatRule !== null;
2596
    }
2597
2598
    /**
2599
     * Returns the national dialling prefix for a specific region. For example, this would be 1 for
2600
     * the United States, and 0 for New Zealand. Set stripNonDigits to true to strip symbols like "~"
2601
     * (which indicates a wait for a dialling tone) from the prefix returned. If no national prefix is
2602
     * present, we return null.
2603
     *
2604
     * <p>Warning: Do not use this method for do-your-own formatting - for some regions, the
2605
     * national dialling prefix is used only for certain types of numbers. Use the library's
2606
     * formatting functions to prefix the national prefix when required.
2607
     *
2608
     * @param string $regionCode the region that we want to get the dialling prefix for
2609
     * @param boolean $stripNonDigits true to strip non-digits from the national dialling prefix
2610
     * @return string the dialling prefix for the region denoted by regionCode
2611
     */
2612 1
    public function getNddPrefixForRegion($regionCode, $stripNonDigits)
2613
    {
2614
        $metadata = $this->getMetadataForRegion($regionCode);
2615 1
        if ($metadata === null) {
2616
            return null;
2617
        }
2618
        $nationalPrefix = $metadata->getNationalPrefix();
2619
        // If no national prefix was found, we return null.
2620
        if (mb_strlen($nationalPrefix) == 0) {
2621 1
            return null;
2622
        }
2623 1
        if ($stripNonDigits) {
2624
            // Note: if any other non-numeric symbols are ever used in national prefixes, these would have
2625
            // to be removed here as well.
2626
            $nationalPrefix = str_replace("~", "", $nationalPrefix);
2627
        }
2628 1
        return $nationalPrefix;
2629
    }
2630
2631
    /**
2632
     * Check if rawInput, which is assumed to be in the national format, has a national prefix. The
2633
     * national prefix is assumed to be in digits-only form.
2634
     * @param string $rawInput
2635
     * @param string $nationalPrefix
2636
     * @param string $regionCode
2637
     * @return bool
2638
     */
2639
    protected function rawInputContainsNationalPrefix($rawInput, $nationalPrefix, $regionCode)
2640
    {
2641
        $normalizedNationalNumber = $this->normalizeDigitsOnly($rawInput);
2642
        if (strpos($normalizedNationalNumber, $nationalPrefix) === 0) {
2643
            try {
2644
                // Some Japanese numbers (e.g. 00777123) might be mistaken to contain the national prefix
2645
                // when written without it (e.g. 0777123) if we just do prefix matching. To tackle that, we
2646
                // check the validity of the number if the assumed national prefix is removed (777123 won't
2647
                // be valid in Japan).
2648
                return $this->isValidNumber(
2649
                    $this->parse(substr($normalizedNationalNumber, mb_strlen($nationalPrefix)), $regionCode)
2650
                );
2651
            } catch (NumberParseException $e) {
2652
                return false;
2653
            }
2654
        }
2655
        return false;
2656
    }
2657
2658
    /**
2659
     * Tests whether a phone number matches a valid pattern. Note this doesn't verify the number
2660
     * is actually in use, which is impossible to tell by just looking at a number itself.
2661
     *
2662
     * @param PhoneNumber $number the phone number that we want to validate
2663
     * @return boolean that indicates whether the number is of a valid pattern
2664
     */
2665 1819
    public function isValidNumber(PhoneNumber $number)
2666
    {
2667
        $regionCode = $this->getRegionCodeForNumber($number);
2668
        return $this->isValidNumberForRegion($number, $regionCode);
2669 1819
    }
2670
2671
    /**
2672
     * Tests whether a phone number is valid for a certain region. Note this doesn't verify the number
2673
     * is actually in use, which is impossible to tell by just looking at a number itself. If the
2674
     * country calling code is not the same as the country calling code for the region, this
2675
     * immediately exits with false. After this, the specific number pattern rules for the region are
2676
     * examined. This is useful for determining for example whether a particular number is valid for
2677
     * Canada, rather than just a valid NANPA number.
2678
     * Warning: In most cases, you want to use {@link #isValidNumber} instead. For example, this
2679
     * method will mark numbers from British Crown dependencies such as the Isle of Man as invalid for
2680
     * the region "GB" (United Kingdom), since it has its own region code, "IM", which may be
2681
     * undesirable.
2682
     *
2683
     * @param PhoneNumber $number the phone number that we want to validate
2684
     * @param string $regionCode the region that we want to validate the phone number for
2685
     * @return boolean that indicates whether the number is of a valid pattern
2686
     */
2687 1578
    public function isValidNumberForRegion(PhoneNumber $number, $regionCode)
2688
    {
2689
        $countryCode = $number->getCountryCode();
2690
        $metadata = $this->getMetadataForRegionOrCallingCode($countryCode, $regionCode);
2691 1578
        if (($metadata === null) ||
2692 1555
            (static::REGION_CODE_FOR_NON_GEO_ENTITY !== $regionCode &&
2693
                $countryCode !== $this->getCountryCodeForValidRegion($regionCode))
2694
        ) {
2695
            // Either the region code was invalid, or the country calling code for this number does not
2696
            // match that of the region code.
2697 28
            return false;
2698
        }
2699
        $nationalSignificantNumber = $this->getNationalSignificantNumber($number);
2700
2701
        return $this->getNumberTypeHelper($nationalSignificantNumber, $metadata) != PhoneNumberType::UNKNOWN;
2702 1578
    }
2703
2704
    /**
2705
     * Parses a string and returns it as a phone number in proto buffer format. The method is quite
2706
     * lenient and looks for a number in the input text (raw input) and does not check whether the
2707
     * string is definitely only a phone number. To do this, it ignores punctuation and white-space,
2708
     * as well as any text before the number (e.g. a leading “Tel: ”) and trims the non-number bits.
2709
     * It will accept a number in any format (E164, national, international etc), assuming it can
2710
     * interpreted with the defaultRegion supplied. It also attempts to convert any alpha characters
2711
     * into digits if it thinks this is a vanity number of the type "1800 MICROSOFT".
2712
     *
2713
     * <p> This method will throw a {@link NumberParseException} if the number is not considered to
2714
     * be a possible number. Note that validation of whether the number is actually a valid number
2715
     * for a particular region is not performed. This can be done separately with {@link #isValidnumber}.
2716
     *
2717
     * @param string $numberToParse number that we are attempting to parse. This can contain formatting
2718
     *                          such as +, ( and -, as well as a phone number extension.
2719
     * @param string $defaultRegion region that we are expecting the number to be from. This is only used
2720
     *                          if the number being parsed is not written in international format.
2721
     *                          The country_code for the number in this case would be stored as that
2722
     *                          of the default region supplied. If the number is guaranteed to
2723
     *                          start with a '+' followed by the country calling code, then
2724
     *                          "ZZ" or null can be supplied.
2725
     * @param PhoneNumber|null $phoneNumber
2726
     * @param bool $keepRawInput
2727
     * @return PhoneNumber a phone number proto buffer filled with the parsed number
2728
     * @throws NumberParseException  if the string is not considered to be a viable phone number (e.g.
2729
     *                               too few or too many digits) or if no default region was supplied
2730
     *                               and the number is not in international format (does not start
2731
     *                               with +)
2732
     */
2733 2209
    public function parse($numberToParse, $defaultRegion, PhoneNumber $phoneNumber = null, $keepRawInput = false)
2734
    {
2735 2209
        if ($phoneNumber === null) {
2736
            $phoneNumber = new PhoneNumber();
2737
        }
2738 3
        $this->parseHelper($numberToParse, $defaultRegion, $keepRawInput, true, $phoneNumber);
2739 2206
        return $phoneNumber;
2740
    }
2741
2742
    /**
2743
     * Formats a phone number in the specified format using client-defined formatting rules. Note that
2744
     * if the phone number has a country calling code of zero or an otherwise invalid country calling
2745
     * code, we cannot work out things like whether there should be a national prefix applied, or how
2746
     * to format extensions, so we return the national significant number with no formatting applied.
2747
     *
2748
     * @param PhoneNumber $number the phone number to be formatted
2749
     * @param int $numberFormat the format the phone number should be formatted into
2750
     * @param array $userDefinedFormats formatting rules specified by clients
2751
     * @return String the formatted phone number
2752
     */
2753
    public function formatByPattern(PhoneNumber $number, $numberFormat, array $userDefinedFormats)
2754
    {
2755
        $countryCallingCode = $number->getCountryCode();
2756
        $nationalSignificantNumber = $this->getNationalSignificantNumber($number);
2757
        if (!$this->hasValidCountryCallingCode($countryCallingCode)) {
2758
            return $nationalSignificantNumber;
2759
        }
2760
        // Note getRegionCodeForCountryCode() is used because formatting information for regions which
2761
        // share a country calling code is contained by only one region for performance reasons. For
2762
        // example, for NANPA regions it will be contained in the metadata for US.
2763
        $regionCode = $this->getRegionCodeForCountryCode($countryCallingCode);
2764
        // Metadata cannot be null because the country calling code is valid
2765
        $metadata = $this->getMetadataForRegionOrCallingCode($countryCallingCode, $regionCode);
2766
2767
        $formattedNumber = "";
2768
2769
        $formattingPattern = $this->chooseFormattingPatternForNumber($userDefinedFormats, $nationalSignificantNumber);
2770
        if ($formattingPattern === null) {
2771
            // If no pattern above is matched, we format the number as a whole.
2772
            $formattedNumber .= $nationalSignificantNumber;
2773
        } else {
2774
            $numFormatCopy = new NumberFormat();
2775
            // Before we do a replacement of the national prefix pattern $NP with the national prefix, we
2776
            // need to copy the rule so that subsequent replacements for different numbers have the
2777
            // appropriate national prefix.
2778
            $numFormatCopy->mergeFrom($formattingPattern);
2779
            $nationalPrefixFormattingRule = $formattingPattern->getNationalPrefixFormattingRule();
2780
            if (mb_strlen($nationalPrefixFormattingRule) > 0) {
2781
                $nationalPrefix = $metadata->getNationalPrefix();
2782
                if (mb_strlen($nationalPrefix) > 0) {
2783
                    // Replace $NP with national prefix and $FG with the first group ($1).
2784
                    $npPatternMatcher = new Matcher(static::NP_PATTERN, $nationalPrefixFormattingRule);
2785
                    $nationalPrefixFormattingRule = $npPatternMatcher->replaceFirst($nationalPrefix);
2786
                    $fgPatternMatcher = new Matcher(static::FG_PATTERN, $nationalPrefixFormattingRule);
2787
                    $nationalPrefixFormattingRule = $fgPatternMatcher->replaceFirst("\\$1");
2788
                    $numFormatCopy->setNationalPrefixFormattingRule($nationalPrefixFormattingRule);
2789
                } else {
2790
                    // We don't want to have a rule for how to format the national prefix if there isn't one.
2791
                    $numFormatCopy->clearNationalPrefixFormattingRule();
2792
                }
2793
            }
2794
            $formattedNumber .= $this->formatNsnUsingPattern($nationalSignificantNumber, $numFormatCopy, $numberFormat);
2795
        }
2796
        $this->maybeAppendFormattedExtension($number, $metadata, $numberFormat, $formattedNumber);
2797
        $this->prefixNumberWithCountryCallingCode($countryCallingCode, $numberFormat, $formattedNumber);
2798
        return $formattedNumber;
2799
    }
2800
2801
    /**
2802
     * Gets a valid number for the specified region.
2803
     *
2804
     * @param string regionCode  the region for which an example number is needed
2805
     * @return PhoneNumber a valid fixed-line number for the specified region. Returns null when the metadata
2806
     *    does not contain such information, or the region 001 is passed in. For 001 (representing
2807
     *    non-geographical numbers), call {@link #getExampleNumberForNonGeoEntity} instead.
2808
     */
2809
    public function getExampleNumber($regionCode)
2810
    {
2811
        return $this->getExampleNumberForType($regionCode, PhoneNumberType::FIXED_LINE);
2812
    }
2813
2814
    /**
2815
     * Gets an invalid number for the specified region. This is useful for unit-testing purposes,
2816
     * where you want to test what will happen with an invalid number. Note that the number that is
2817
     * returned will always be able to be parsed and will have the correct country code. It may also
2818
     * be a valid *short* number/code for this region. Validity checking such numbers is handled with
2819
     * {@link ShortNumberInfo}.
2820
     *
2821
     * @param string $regionCode The region for which an example number is needed
2822
     * @return PhoneNumber|null An invalid number for the specified region. Returns null when an unsupported region
2823
     * or the region 001 (Earth) is passed in.
2824
     */
2825 244
    public function getInvalidExampleNumber($regionCode)
2826
    {
2827
        if (!$this->isValidRegionCode($regionCode)) {
2828
            return null;
2829
        }
2830
2831
        // We start off with a valid fixed-line number since every country supports this. Alternatively
2832
        // we could start with a different number type, since fixed-line numbers typically have a wide
2833
        // breadth of valid number lengths and we may have to make it very short before we get an
2834
        // invalid number.
2835
2836
        $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...
2837
2838
        if ($desc->getExampleNumber() == '') {
2839
            // This shouldn't happen; we have a test for this.
2840
            return null;
2841
        }
2842
2843
        $exampleNumber = $desc->getExampleNumber();
2844
2845
        // Try and make the number invalid. We do this by changing the length. We try reducing the
2846
        // length of the number, since currently no region has a number that is the same length as
2847
        // MIN_LENGTH_FOR_NSN. This is probably quicker than making the number longer, which is another
2848
        // alternative. We could also use the possible number pattern to extract the possible lengths of
2849
        // the number to make this faster, but this method is only for unit-testing so simplicity is
2850
        // preferred to performance.  We don't want to return a number that can't be parsed, so we check
2851
        // the number is long enough. We try all possible lengths because phone number plans often have
2852
        // overlapping prefixes so the number 123456 might be valid as a fixed-line number, and 12345 as
2853
        // a mobile number. It would be faster to loop in a different order, but we prefer numbers that
2854
        // look closer to real numbers (and it gives us a variety of different lengths for the resulting
2855
        // phone numbers - otherwise they would all be MIN_LENGTH_FOR_NSN digits long.)
2856
        for ($phoneNumberLength = mb_strlen($exampleNumber) - 1; $phoneNumberLength >= static::MIN_LENGTH_FOR_NSN; $phoneNumberLength--) {
2857
            $numberToTry = mb_substr($exampleNumber, 0, $phoneNumberLength);
2858
            try {
2859
                $possiblyValidNumber = $this->parse($numberToTry, $regionCode);
2860
                if (!$this->isValidNumber($possiblyValidNumber)) {
2861 244
                    return $possiblyValidNumber;
2862
                }
2863
            } catch (NumberParseException $e) {
2864
                // Shouldn't happen: we have already checked the length, we know example numbers have
2865
                // only valid digits, and we know the region code is fine.
2866 6
            }
2867 229
        }
2868
        // We have a test to check that this doesn't happen for any of our supported regions.
2869
        return null;
2870
    }
2871
2872
    /**
2873
     * Gets a valid number for the specified region and number type.
2874
     *
2875
     * @param string $regionCodeOrType the region for which an example number is needed
2876
     * @param int $type the PhoneNumberType of number that is needed
2877
     * @return PhoneNumber a valid number for the specified region and type. Returns null when the metadata
2878
     *     does not contain such information or if an invalid region or region 001 was entered.
2879
     *     For 001 (representing non-geographical numbers), call
2880
     *     {@link #getExampleNumberForNonGeoEntity} instead.
2881
     *
2882
     * If $regionCodeOrType is the only parameter supplied, then a valid number for the specified number type
2883
     * will be returned that may belong to any country.
2884
     */
2885 3163
    public function getExampleNumberForType($regionCodeOrType, $type = null)
2886
    {
2887 3163
        if ($regionCodeOrType !== null && $type === null) {
2888
            /*
2889
             * Gets a valid number for the specified number type (it may belong to any country).
2890
             */
2891 15
            foreach ($this->getSupportedRegions() as $regionCode) {
2892
                $exampleNumber = $this->getExampleNumberForType($regionCode, $regionCodeOrType);
2893 6
                if ($exampleNumber !== null) {
2894 11
                    return $exampleNumber;
2895
                }
2896 6
            }
2897
2898
            // If there wasn't an example number for a region, try the non-geographical entities
2899 4
            foreach ($this->getSupportedGlobalNetworkCallingCodes() as $countryCallingCode) {
2900
                $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...
2901
                try {
2902
                    if ($desc->getExampleNumber() != '') {
2903
                        return $this->parse("+" . $countryCallingCode . $desc->getExampleNumber(), static::UNKNOWN_REGION);
2904
                    }
2905
                } catch (NumberParseException $e) {
0 ignored issues
show
Coding Style Comprehensibility introduced by
Consider adding a comment why this CATCH block is empty.
Loading history...
2906
                }
2907 4
            }
2908
            // There are no example numbers of this type for any country in the library.
2909
            return null;
2910
        }
2911
2912
        // Check the region code is valid.
2913
        if (!$this->isValidRegionCode($regionCodeOrType)) {
2914
            return null;
2915
        }
2916
        $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...
2917
        try {
2918
            if ($desc->hasExampleNumber()) {
2919
                return $this->parse($desc->getExampleNumber(), $regionCodeOrType);
2920
            }
2921
        } catch (NumberParseException $e) {
0 ignored issues
show
Coding Style Comprehensibility introduced by
Consider adding a comment why this CATCH block is empty.
Loading history...
2922 1375
        }
2923 1375
        return null;
2924 15
    }
2925
2926
    /**
2927
     * @param PhoneMetadata $metadata
2928
     * @param int $type PhoneNumberType
2929
     * @return PhoneNumberDesc
2930
     */
2931 3413
    protected function getNumberDescByType(PhoneMetadata $metadata, $type)
2932
    {
2933
        switch ($type) {
2934 3413
            case PhoneNumberType::PREMIUM_RATE:
2935
                return $metadata->getPremiumRate();
2936 3168
            case PhoneNumberType::TOLL_FREE:
2937
                return $metadata->getTollFree();
2938 2923
            case PhoneNumberType::MOBILE:
2939
                return $metadata->getMobile();
2940 2678
            case PhoneNumberType::FIXED_LINE:
2941 1943
            case PhoneNumberType::FIXED_LINE_OR_MOBILE:
2942
                return $metadata->getFixedLine();
2943 1465
            case PhoneNumberType::SHARED_COST:
2944
                return $metadata->getSharedCost();
2945 1221
            case PhoneNumberType::VOIP:
2946
                return $metadata->getVoip();
2947 977
            case PhoneNumberType::PERSONAL_NUMBER:
2948
                return $metadata->getPersonalNumber();
2949 732
            case PhoneNumberType::PAGER:
2950
                return $metadata->getPager();
2951 488
            case PhoneNumberType::UAN:
2952
                return $metadata->getUan();
2953 244
            case PhoneNumberType::VOICEMAIL:
2954
                return $metadata->getVoicemail();
2955
            default:
2956
                return $metadata->getGeneralDesc();
2957
        }
2958 3413
    }
2959
2960
    /**
2961
     * Gets a valid number for the specified country calling code for a non-geographical entity.
2962
     *
2963
     * @param int $countryCallingCode the country calling code for a non-geographical entity
2964
     * @return PhoneNumber a valid number for the non-geographical entity. Returns null when the metadata
2965
     *    does not contain such information, or the country calling code passed in does not belong
2966
     *    to a non-geographical entity.
2967
     */
2968 9
    public function getExampleNumberForNonGeoEntity($countryCallingCode)
2969
    {
2970
        $metadata = $this->getMetadataForNonGeographicalRegion($countryCallingCode);
2971 9
        if ($metadata !== null) {
2972
            $desc = $metadata->getGeneralDesc();
2973
            try {
2974
                if ($desc->hasExampleNumber()) {
2975
                    return $this->parse("+" . $countryCallingCode . $desc->getExampleNumber(), static::UNKNOWN_REGION);
2976
                }
2977
            } catch (NumberParseException $e) {
0 ignored issues
show
Coding Style Comprehensibility introduced by
Consider adding a comment why this CATCH block is empty.
Loading history...
2978
            }
2979
        }
2980
        return null;
2981
    }
2982
2983
2984
    /**
2985
     * Takes two phone numbers and compares them for equality.
2986
     *
2987
     * <p>Returns EXACT_MATCH if the country_code, NSN, presence of a leading zero
2988
     * for Italian numbers and any extension present are the same. Returns NSN_MATCH
2989
     * if either or both has no region specified, and the NSNs and extensions are
2990
     * the same. Returns SHORT_NSN_MATCH if either or both has no region specified,
2991
     * or the region specified is the same, and one NSN could be a shorter version
2992
     * of the other number. This includes the case where one has an extension
2993
     * specified, and the other does not. Returns NO_MATCH otherwise. For example,
2994
     * the numbers +1 345 657 1234 and 657 1234 are a SHORT_NSN_MATCH. The numbers
2995
     * +1 345 657 1234 and 345 657 are a NO_MATCH.
2996
     *
2997
     * @param $firstNumberIn PhoneNumber|string First number to compare. If it is a
2998
     * string it can contain formatting, and can have country calling code specified
2999
     * with + at the start.
3000
     * @param $secondNumberIn PhoneNumber|string Second number to compare. If it is a
3001
     * string it can contain formatting, and can have country calling code specified
3002
     * with + at the start.
3003
     * @throws \InvalidArgumentException
3004
     * @return int {MatchType} NOT_A_NUMBER, NO_MATCH,
3005
     */
3006 2
    public function isNumberMatch($firstNumberIn, $secondNumberIn)
3007
    {
3008
        if (is_string($firstNumberIn) && is_string($secondNumberIn)) {
3009
            try {
3010
                $firstNumberAsProto = $this->parse($firstNumberIn, static::UNKNOWN_REGION);
3011
                return $this->isNumberMatch($firstNumberAsProto, $secondNumberIn);
3012
            } catch (NumberParseException $e) {
3013
                if ($e->getErrorType() === NumberParseException::INVALID_COUNTRY_CODE) {
3014
                    try {
3015 1
                        $secondNumberAsProto = $this->parse($secondNumberIn, static::UNKNOWN_REGION);
3016
                        return $this->isNumberMatch($secondNumberAsProto, $firstNumberIn);
3017
                    } catch (NumberParseException $e2) {
3018
                        if ($e2->getErrorType() === NumberParseException::INVALID_COUNTRY_CODE) {
3019
                            try {
3020
                                $firstNumberProto = new PhoneNumber();
3021
                                $secondNumberProto = new PhoneNumber();
3022
                                $this->parseHelper($firstNumberIn, null, false, false, $firstNumberProto);
3023
                                $this->parseHelper($secondNumberIn, null, false, false, $secondNumberProto);
3024
                                return $this->isNumberMatch($firstNumberProto, $secondNumberProto);
3025
                            } catch (NumberParseException $e3) {
3026
                                // Fall through and return MatchType::NOT_A_NUMBER
3027
                            }
3028
                        }
3029 2
                    }
3030
                }
3031
            }
3032
            return MatchType::NOT_A_NUMBER;
3033
        }
3034
        if ($firstNumberIn instanceof PhoneNumber && is_string($secondNumberIn)) {
3035
            // First see if the second number has an implicit country calling code, by attempting to parse
3036
            // it.
3037
            try {
3038
                $secondNumberAsProto = $this->parse($secondNumberIn, static::UNKNOWN_REGION);
3039
                return $this->isNumberMatch($firstNumberIn, $secondNumberAsProto);
3040
            } catch (NumberParseException $e) {
3041
                if ($e->getErrorType() === NumberParseException::INVALID_COUNTRY_CODE) {
3042
                    // The second number has no country calling code. EXACT_MATCH is no longer possible.
3043
                    // We parse it as if the region was the same as that for the first number, and if
3044
                    // EXACT_MATCH is returned, we replace this with NSN_MATCH.
3045
                    $firstNumberRegion = $this->getRegionCodeForCountryCode($firstNumberIn->getCountryCode());
3046
                    try {
3047
                        if ($firstNumberRegion != static::UNKNOWN_REGION) {
3048
                            $secondNumberWithFirstNumberRegion = $this->parse($secondNumberIn, $firstNumberRegion);
3049
                            $match = $this->isNumberMatch($firstNumberIn, $secondNumberWithFirstNumberRegion);
3050
                            if ($match === MatchType::EXACT_MATCH) {
3051
                                return MatchType::NSN_MATCH;
3052
                            }
3053
                            return $match;
3054
                        } else {
3055
                            // If the first number didn't have a valid country calling code, then we parse the
3056
                            // second number without one as well.
3057
                            $secondNumberProto = new PhoneNumber();
3058
                            $this->parseHelper($secondNumberIn, null, false, false, $secondNumberProto);
3059
                            return $this->isNumberMatch($firstNumberIn, $secondNumberProto);
3060
                        }
3061
                    } catch (NumberParseException $e2) {
3062
                        // Fall-through to return NOT_A_NUMBER.
3063
                    }
3064
                }
3065
            }
3066
        }
3067
        if ($firstNumberIn instanceof PhoneNumber && $secondNumberIn instanceof PhoneNumber) {
3068
            // Make copies of the phone number so that the numbers passed in are not edited.
3069
            $firstNumber = new PhoneNumber();
3070
            $firstNumber->mergeFrom($firstNumberIn);
3071
            $secondNumber = new PhoneNumber();
3072
            $secondNumber->mergeFrom($secondNumberIn);
3073
3074
            // First clear raw_input, country_code_source and preferred_domestic_carrier_code fields and any
3075
            // empty-string extensions so that we can use the proto-buffer equality method.
3076
            $firstNumber->clearRawInput();
3077
            $firstNumber->clearCountryCodeSource();
3078
            $firstNumber->clearPreferredDomesticCarrierCode();
3079
            $secondNumber->clearRawInput();
3080
            $secondNumber->clearCountryCodeSource();
3081
            $secondNumber->clearPreferredDomesticCarrierCode();
3082
            if ($firstNumber->hasExtension() && mb_strlen($firstNumber->getExtension()) === 0) {
3083
                $firstNumber->clearExtension();
3084
            }
3085
3086
            if ($secondNumber->hasExtension() && mb_strlen($secondNumber->getExtension()) === 0) {
3087
                $secondNumber->clearExtension();
3088
            }
3089
3090
            // Early exit if both had extensions and these are different.
3091
            if ($firstNumber->hasExtension() && $secondNumber->hasExtension() &&
3092
                $firstNumber->getExtension() != $secondNumber->getExtension()
3093
            ) {
3094
                return MatchType::NO_MATCH;
3095
            }
3096
3097
            $firstNumberCountryCode = $firstNumber->getCountryCode();
3098
            $secondNumberCountryCode = $secondNumber->getCountryCode();
3099
            // Both had country_code specified.
3100
            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...
3101
                if ($firstNumber->equals($secondNumber)) {
3102
                    return MatchType::EXACT_MATCH;
3103
                } elseif ($firstNumberCountryCode == $secondNumberCountryCode &&
3104
                    $this->isNationalNumberSuffixOfTheOther($firstNumber, $secondNumber)
3105
                ) {
3106
                    // A SHORT_NSN_MATCH occurs if there is a difference because of the presence or absence of
3107
                    // an 'Italian leading zero', the presence or absence of an extension, or one NSN being a
3108
                    // shorter variant of the other.
3109
                    return MatchType::SHORT_NSN_MATCH;
3110
                }
3111
                // This is not a match.
3112
                return MatchType::NO_MATCH;
3113
            }
3114
            // Checks cases where one or both country_code fields were not specified. To make equality
3115
            // checks easier, we first set the country_code fields to be equal.
3116
            $firstNumber->setCountryCode($secondNumberCountryCode);
3117
            // If all else was the same, then this is an NSN_MATCH.
3118
            if ($firstNumber->equals($secondNumber)) {
3119 1
                return MatchType::NSN_MATCH;
3120
            }
3121
            if ($this->isNationalNumberSuffixOfTheOther($firstNumber, $secondNumber)) {
3122 1
                return MatchType::SHORT_NSN_MATCH;
3123
            }
3124 1
            return MatchType::NO_MATCH;
3125
        }
3126
        return MatchType::NOT_A_NUMBER;
3127
    }
3128
3129
    /**
3130
     * Returns true when one national number is the suffix of the other or both are the same.
3131
     * @param PhoneNumber $firstNumber
3132
     * @param PhoneNumber $secondNumber
3133
     * @return bool
3134
     */
3135 2
    protected function isNationalNumberSuffixOfTheOther(PhoneNumber $firstNumber, PhoneNumber $secondNumber)
3136
    {
3137
        $firstNumberNationalNumber = trim((string)$firstNumber->getNationalNumber());
3138
        $secondNumberNationalNumber = trim((string)$secondNumber->getNationalNumber());
3139
        return $this->stringEndsWithString($firstNumberNationalNumber, $secondNumberNationalNumber) ||
3140
        $this->stringEndsWithString($secondNumberNationalNumber, $firstNumberNationalNumber);
3141 2
    }
3142
3143
    protected function stringEndsWithString($hayStack, $needle)
3144
    {
3145
        $revNeedle = strrev($needle);
3146
        $revHayStack = strrev($hayStack);
3147
        return strpos($revHayStack, $revNeedle) === 0;
3148
    }
3149
3150
    /**
3151
     * Returns true if the supplied region supports mobile number portability. Returns false for
3152
     * invalid, unknown or regions that don't support mobile number portability.
3153
     *
3154
     * @param string $regionCode the region for which we want to know whether it supports mobile number
3155
     *                    portability or not.
3156
     * @return bool
3157
     */
3158 2
    public function isMobileNumberPortableRegion($regionCode)
3159
    {
3160
        $metadata = $this->getMetadataForRegion($regionCode);
3161 2
        if ($metadata === null) {
3162
            return false;
3163
        }
3164
3165
        return $metadata->isMobileNumberPortableRegion();
3166
    }
3167
3168
    /**
3169
     * Check whether a phone number is a possible number given a number in the form of a string, and
3170
     * the region where the number could be dialed from. It provides a more lenient check than
3171
     * {@link #isValidNumber}. See {@link #isPossibleNumber(PhoneNumber)} for details.
3172
     *
3173
     * <p>This method first parses the number, then invokes {@link #isPossibleNumber(PhoneNumber)}
3174
     * with the resultant PhoneNumber object.
3175
     *
3176
     * @param PhoneNumber|string $number the number that needs to be checked, in the form of a string
3177
     * @param string $regionDialingFrom the region that we are expecting the number to be dialed from.
3178
     *     Note this is different from the region where the number belongs.  For example, the number
3179
     *     +1 650 253 0000 is a number that belongs to US. When written in this form, it can be
3180
     *     dialed from any region. When it is written as 00 1 650 253 0000, it can be dialed from any
3181
     *     region which uses an international dialling prefix of 00. When it is written as
3182
     *     650 253 0000, it can only be dialed from within the US, and when written as 253 0000, it
3183
     *     can only be dialed from within a smaller area in the US (Mountain View, CA, to be more
3184
     *     specific).
3185
     * @return boolean true if the number is possible
3186
     */
3187 1
    public function isPossibleNumber($number, $regionDialingFrom = null)
3188
    {
3189
        if ($regionDialingFrom !== null && is_string($number)) {
3190
            try {
3191
                return $this->isPossibleNumberWithReason(
3192
                    $this->parse($number, $regionDialingFrom)
3193
                ) === ValidationResult::IS_POSSIBLE;
3194
            } catch (NumberParseException $e) {
3195 1
                return false;
3196 1
            }
3197
        } else {
3198
            return $this->isPossibleNumberWithReason($number) === ValidationResult::IS_POSSIBLE;
0 ignored issues
show
Bug introduced by
It seems like $number defined by parameter $number on line 3187 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...
3199
        }
3200
    }
3201
3202
3203
    /**
3204
     * Check whether a phone number is a possible number. It provides a more lenient check than
3205
     * {@link #isValidNumber} in the following sense:
3206
     * <ol>
3207
     * <li> It only checks the length of phone numbers. In particular, it doesn't check starting
3208
     *      digits of the number.
3209
     * <li> It doesn't attempt to figure out the type of the number, but uses general rules which
3210
     *      applies to all types of phone numbers in a region. Therefore, it is much faster than
3211
     *      isValidNumber.
3212
     * <li> For fixed line numbers, many regions have the concept of area code, which together with
3213
     *      subscriber number constitute the national significant number. It is sometimes okay to dial
3214
     *      the subscriber number only when dialing in the same area. This function will return
3215
     *      true if the subscriber-number-only version is passed in. On the other hand, because
3216
     *      isValidNumber validates using information on both starting digits (for fixed line
3217
     *      numbers, that would most likely be area codes) and length (obviously includes the
3218
     *      length of area codes for fixed line numbers), it will return false for the
3219
     *      subscriber-number-only version.
3220
     * </ol>
3221
     * @param PhoneNumber $number the number that needs to be checked
3222
     * @return int a ValidationResult object which indicates whether the number is possible
3223
     */
3224 1
    public function isPossibleNumberWithReason(PhoneNumber $number)
3225
    {
3226
        $nationalNumber = $this->getNationalSignificantNumber($number);
3227
        $countryCode = $number->getCountryCode();
3228
        // Note: For Russian Fed and NANPA numbers, we just use the rules from the default region (US or
3229
        // Russia) since the getRegionCodeForNumber will not work if the number is possible but not
3230
        // valid. This would need to be revisited if the possible number pattern ever differed between
3231
        // various regions within those plans.
3232
        if (!$this->hasValidCountryCallingCode($countryCode)) {
3233 1
            return ValidationResult::INVALID_COUNTRY_CODE;
3234
        }
3235
3236
        $regionCode = $this->getRegionCodeForCountryCode($countryCode);
3237
        // Metadata cannot be null because the country calling code is valid.
3238
        $metadata = $this->getMetadataForRegionOrCallingCode($countryCode, $regionCode);
3239
3240
        $possibleNumberPattern = $metadata->getGeneralDesc()->getPossibleNumberPattern();
3241
        return $this->testNumberLengthAgainstPattern($possibleNumberPattern, $nationalNumber);
3242
    }
3243
3244
    /**
3245
     * Attempts to extract a valid number from a phone number that is too long to be valid, and resets
3246
     * the PhoneNumber object passed in to that valid version. If no valid number could be extracted,
3247
     * the PhoneNumber object passed in will not be modified.
3248
     * @param PhoneNumber $number a PhoneNumber object which contains a number that is too long to be valid.
3249
     * @return boolean true if a valid phone number can be successfully extracted.
3250
     */
3251 1
    public function truncateTooLongNumber(PhoneNumber $number)
3252
    {
3253
        if ($this->isValidNumber($number)) {
3254 1
            return true;
3255
        }
3256
        $numberCopy = new PhoneNumber();
3257
        $numberCopy->mergeFrom($number);
3258
        $nationalNumber = $number->getNationalNumber();
3259
        do {
3260
            $nationalNumber = floor($nationalNumber / 10);
3261
            $numberCopy->setNationalNumber($nationalNumber);
3262
            if ($this->isPossibleNumberWithReason($numberCopy) == ValidationResult::TOO_SHORT || $nationalNumber == 0) {
3263
                return false;
3264
            }
3265
        } while (!$this->isValidNumber($numberCopy));
3266
        $number->setNationalNumber($nationalNumber);
3267
        return true;
3268
    }
3269
}
3270