Completed
Push — locale ( b2b284...e3784a )
by Joshua
41:04 queued 24:21
created

PhoneNumberUtil::parseHelper()   F

Complexity

Conditions 23
Paths 692

Size

Total Lines 150
Code Lines 85

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 87
CRAP Score 23.0845

Importance

Changes 7
Bugs 2 Features 2
Metric Value
c 7
b 2
f 2
dl 0
loc 150
ccs 87
cts 92
cp 0.9457
rs 2.2656
cc 23
eloc 85
nc 692
nop 5
crap 23.0845

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 calling codes that have geographically assigned mobile numbers. This may not be
161
     * complete; we add calling codes case by case, as we find geographical mobile numbers or hear
162
     * from user reports.
163
     *
164
     * @var array
165
     */
166
    protected static $GEO_MOBILE_COUNTRIES;
167
168
    /**
169
     * For performance reasons, amalgamate both into one map.
170
     * @var array
171
     */
172
    protected static $ALPHA_PHONE_MAPPINGS;
173
174
    /**
175
     * Separate map of all symbols that we wish to retain when formatting alpha numbers. This
176
     * includes digits, ASCII letters and number grouping symbols such as "-" and " ".
177
     * @var array
178
     */
179
    protected static $ALL_PLUS_NUMBER_GROUPING_SYMBOLS;
180
181
    /**
182
     * Simple ASCII digits map used to populate ALPHA_PHONE_MAPPINGS and
183
     * ALL_PLUS_NUMBER_GROUPING_SYMBOLS.
184
     * @var array
185
     */
186
    protected static $asciiDigitMappings = array(
187
        '0' => '0',
188
        '1' => '1',
189
        '2' => '2',
190
        '3' => '3',
191
        '4' => '4',
192
        '5' => '5',
193
        '6' => '6',
194
        '7' => '7',
195
        '8' => '8',
196
        '9' => '9',
197
    );
198
199
    /**
200
     * Regexp of all possible ways to write extensions, for use when parsing. This will be run as a
201
     * case-insensitive regexp match. Wide character versions are also provided after each ASCII
202
     * version.
203
     * @var String
204
     */
205
    protected static $EXTN_PATTERNS_FOR_PARSING;
206
    protected static $EXTN_PATTERN = null;
207
    protected static $VALID_PHONE_NUMBER_PATTERN;
208
    protected static $MIN_LENGTH_PHONE_NUMBER_PATTERN;
209
    /**
210
     *  Regular expression of viable phone numbers. This is location independent. Checks we have at
211
     * least three leading digits, and only valid punctuation, alpha characters and
212
     * digits in the phone number. Does not include extension data.
213
     * The symbol 'x' is allowed here as valid punctuation since it is often used as a placeholder for
214
     * carrier codes, for example in Brazilian phone numbers. We also allow multiple "+" characters at
215
     * the start.
216
     * Corresponds to the following:
217
     * [digits]{minLengthNsn}|
218
     * plus_sign*(([punctuation]|[star])*[digits]){3,}([punctuation]|[star]|[digits]|[alpha])*
219
     *
220
     * The first reg-ex is to allow short numbers (two digits long) to be parsed if they are entered
221
     * as "15" etc, but only if there is no punctuation in them. The second expression restricts the
222
     * number of digits to three or more, but then allows them to be in international form, and to
223
     * have alpha-characters and punctuation.
224
     *
225
     * Note VALID_PUNCTUATION starts with a -, so must be the first in the range.
226
     * @var string
227
     */
228
    protected static $VALID_PHONE_NUMBER;
229
    protected static $numericCharacters = array(
230
        "\xef\xbc\x90" => 0,
231
        "\xef\xbc\x91" => 1,
232
        "\xef\xbc\x92" => 2,
233
        "\xef\xbc\x93" => 3,
234
        "\xef\xbc\x94" => 4,
235
        "\xef\xbc\x95" => 5,
236
        "\xef\xbc\x96" => 6,
237
        "\xef\xbc\x97" => 7,
238
        "\xef\xbc\x98" => 8,
239
        "\xef\xbc\x99" => 9,
240
241
        "\xd9\xa0" => 0,
242
        "\xd9\xa1" => 1,
243
        "\xd9\xa2" => 2,
244
        "\xd9\xa3" => 3,
245
        "\xd9\xa4" => 4,
246
        "\xd9\xa5" => 5,
247
        "\xd9\xa6" => 6,
248
        "\xd9\xa7" => 7,
249
        "\xd9\xa8" => 8,
250
        "\xd9\xa9" => 9,
251
252
        "\xdb\xb0" => 0,
253
        "\xdb\xb1" => 1,
254
        "\xdb\xb2" => 2,
255
        "\xdb\xb3" => 3,
256
        "\xdb\xb4" => 4,
257
        "\xdb\xb5" => 5,
258
        "\xdb\xb6" => 6,
259
        "\xdb\xb7" => 7,
260
        "\xdb\xb8" => 8,
261
        "\xdb\xb9" => 9,
262
263
        "\xe1\xa0\x90" => 0,
264
        "\xe1\xa0\x91" => 1,
265
        "\xe1\xa0\x92" => 2,
266
        "\xe1\xa0\x93" => 3,
267
        "\xe1\xa0\x94" => 4,
268
        "\xe1\xa0\x95" => 5,
269
        "\xe1\xa0\x96" => 6,
270
        "\xe1\xa0\x97" => 7,
271
        "\xe1\xa0\x98" => 8,
272
        "\xe1\xa0\x99" => 9,
273
    );
274
275
    /**
276
     * The set of county calling codes that map to the non-geo entity region ("001").
277
     * @var array
278
     */
279
    protected $countryCodesForNonGeographicalRegion = array();
280
    /**
281
     * The set of regions the library supports.
282
     * @var array
283
     */
284
    protected $supportedRegions = array();
285
286
    /**
287
     * A mapping from a country calling code to the region codes which denote the region represented
288
     * by that country calling code. In the case of multiple regions sharing a calling code, such as
289
     * the NANPA regions, the one indicated with "isMainCountryForCode" in the metadata should be
290
     * first.
291
     * @var array
292
     */
293
    protected $countryCallingCodeToRegionCodeMap = array();
294
    /**
295
     * The set of regions that share country calling code 1.
296
     * @var array
297
     */
298
    protected $nanpaRegions = array();
299
300
    /**
301
     * @var MetadataSourceInterface
302
     */
303
    protected $metadataSource;
304
305
    /**
306
     * This class implements a singleton, so the only constructor is protected.
307
     * @param MetadataSourceInterface $metadataSource
308
     * @param $countryCallingCodeToRegionCodeMap
309
     */
310 402
    protected function __construct(MetadataSourceInterface $metadataSource, $countryCallingCodeToRegionCodeMap)
311
    {
312 402
        $this->metadataSource = $metadataSource;
313 402
        $this->countryCallingCodeToRegionCodeMap = $countryCallingCodeToRegionCodeMap;
314 402
        $this->init();
315 402
        static::initCapturingExtnDigits();
316 402
        static::initExtnPatterns();
317 402
        static::initExtnPattern();
318 402
        static::$PLUS_CHARS_PATTERN = "[" . static::PLUS_CHARS . "]+";
319 402
        static::$SEPARATOR_PATTERN = "[" . static::VALID_PUNCTUATION . "]+";
320 402
        static::$CAPTURING_DIGIT_PATTERN = "(" . static::DIGITS . ")";
321 402
        static::$VALID_START_CHAR_PATTERN = "[" . static::PLUS_CHARS . static::DIGITS . "]";
322
323 402
        static::$ALPHA_PHONE_MAPPINGS = static::$ALPHA_MAPPINGS + static::$asciiDigitMappings;
324
325 402
        static::$DIALLABLE_CHAR_MAPPINGS = static::$asciiDigitMappings;
326 402
        static::$DIALLABLE_CHAR_MAPPINGS[static::PLUS_SIGN] = static::PLUS_SIGN;
327 402
        static::$DIALLABLE_CHAR_MAPPINGS['*'] = '*';
328
329 402
        static::$ALL_PLUS_NUMBER_GROUPING_SYMBOLS = array();
330
        // Put (lower letter -> upper letter) and (upper letter -> upper letter) mappings.
331 402
        foreach (static::$ALPHA_MAPPINGS as $c => $value) {
332 402
            static::$ALL_PLUS_NUMBER_GROUPING_SYMBOLS[strtolower($c)] = $c;
333 402
            static::$ALL_PLUS_NUMBER_GROUPING_SYMBOLS[$c] = $c;
334 402
        }
335 402
        static::$ALL_PLUS_NUMBER_GROUPING_SYMBOLS += static::$asciiDigitMappings;
336 402
        static::$ALL_PLUS_NUMBER_GROUPING_SYMBOLS["-"] = '-';
337 402
        static::$ALL_PLUS_NUMBER_GROUPING_SYMBOLS["\xEF\xBC\x8D"] = '-';
338 402
        static::$ALL_PLUS_NUMBER_GROUPING_SYMBOLS["\xE2\x80\x90"] = '-';
339 402
        static::$ALL_PLUS_NUMBER_GROUPING_SYMBOLS["\xE2\x80\x91"] = '-';
340 402
        static::$ALL_PLUS_NUMBER_GROUPING_SYMBOLS["\xE2\x80\x92"] = '-';
341 402
        static::$ALL_PLUS_NUMBER_GROUPING_SYMBOLS["\xE2\x80\x93"] = '-';
342 402
        static::$ALL_PLUS_NUMBER_GROUPING_SYMBOLS["\xE2\x80\x94"] = '-';
343 402
        static::$ALL_PLUS_NUMBER_GROUPING_SYMBOLS["\xE2\x80\x95"] = '-';
344 402
        static::$ALL_PLUS_NUMBER_GROUPING_SYMBOLS["\xE2\x88\x92"] = '-';
345 402
        static::$ALL_PLUS_NUMBER_GROUPING_SYMBOLS["/"] = "/";
346 402
        static::$ALL_PLUS_NUMBER_GROUPING_SYMBOLS["\xEF\xBC\x8F"] = "/";
347 402
        static::$ALL_PLUS_NUMBER_GROUPING_SYMBOLS[" "] = " ";
348 402
        static::$ALL_PLUS_NUMBER_GROUPING_SYMBOLS["\xE3\x80\x80"] = " ";
349 402
        static::$ALL_PLUS_NUMBER_GROUPING_SYMBOLS["\xE2\x81\xA0"] = " ";
350 402
        static::$ALL_PLUS_NUMBER_GROUPING_SYMBOLS["."] = ".";
351 402
        static::$ALL_PLUS_NUMBER_GROUPING_SYMBOLS["\xEF\xBC\x8E"] = ".";
352
353
354 402
        static::$MIN_LENGTH_PHONE_NUMBER_PATTERN = "[" . static::DIGITS . "]{" . static::MIN_LENGTH_FOR_NSN . "}";
355 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 . "]*";
356 402
        static::$VALID_PHONE_NUMBER_PATTERN = "%^" . static::$MIN_LENGTH_PHONE_NUMBER_PATTERN . "$|^" . static::$VALID_PHONE_NUMBER . "(?:" . static::$EXTN_PATTERNS_FOR_PARSING . ")?$%" . static::REGEX_FLAGS;
357
358 402
        static::$UNWANTED_END_CHAR_PATTERN = "[^" . static::DIGITS . static::VALID_ALPHA . "#]+$";
359
360 402
        static::$MOBILE_TOKEN_MAPPINGS = array();
361 402
        static::$MOBILE_TOKEN_MAPPINGS['52'] = "1";
362 402
        static::$MOBILE_TOKEN_MAPPINGS['54'] = "9";
363
364 402
        static::$GEO_MOBILE_COUNTRIES = array();
365 402
        static::$GEO_MOBILE_COUNTRIES[] = 52; // Mexico
366 402
        static::$GEO_MOBILE_COUNTRIES[] = 54; // Argentina
367 402
        static::$GEO_MOBILE_COUNTRIES[] = 55; // Brazil
368 402
    }
369
370
    /**
371
     * Gets a {@link PhoneNumberUtil} instance to carry out international phone number formatting,
372
     * parsing, or validation. The instance is loaded with phone number metadata for a number of most
373
     * commonly used regions.
374
     *
375
     * <p>The {@link PhoneNumberUtil} is implemented as a singleton. Therefore, calling getInstance
376
     * multiple times will only result in one instance being created.
377
     *
378
     * @param string $baseFileLocation
379
     * @param array|null $countryCallingCodeToRegionCodeMap
380
     * @param MetadataLoaderInterface|null $metadataLoader
381
     * @param MetadataSourceInterface|null $metadataSource
382
     * @return PhoneNumberUtil instance
383
     */
384 5530
    public static function getInstance($baseFileLocation = self::META_DATA_FILE_PREFIX, array $countryCallingCodeToRegionCodeMap = null, MetadataLoaderInterface $metadataLoader = null, MetadataSourceInterface $metadataSource = null)
385
    {
386 5530
        if (static::$instance === null) {
387 402
            if ($countryCallingCodeToRegionCodeMap === null) {
388 267
                $countryCallingCodeToRegionCodeMap = CountryCodeToRegionCodeMap::$countryCodeToRegionCodeMap;
389 267
            }
390
391 402
            if ($metadataLoader === null) {
392 402
                $metadataLoader = new DefaultMetadataLoader();
393 402
            }
394
395 402
            if ($metadataSource === null) {
396 402
                $metadataSource = new MultiFileMetadataSourceImpl($metadataLoader, __DIR__ . '/data/' . $baseFileLocation);
397 402
            }
398
399 402
            static::$instance = new static($metadataSource, $countryCallingCodeToRegionCodeMap);
400 402
        }
401 5530
        return static::$instance;
402
    }
403
404 402
    protected function init()
405
    {
406 402
        foreach ($this->countryCallingCodeToRegionCodeMap as $countryCode => $regionCodes) {
407
            // We can assume that if the country calling code maps to the non-geo entity region code then
408
            // that's the only region code it maps to.
409 402
            if (count($regionCodes) == 1 && static::REGION_CODE_FOR_NON_GEO_ENTITY === $regionCodes[0]) {
410
                // This is the subset of all country codes that map to the non-geo entity region code.
411 402
                $this->countryCodesForNonGeographicalRegion[] = $countryCode;
412 402
            } else {
413
                // The supported regions set does not include the "001" non-geo entity region code.
414 402
                $this->supportedRegions = array_merge($this->supportedRegions, $regionCodes);
415
            }
416 402
        }
417
        // If the non-geo entity still got added to the set of supported regions it must be because
418
        // there are entries that list the non-geo entity alongside normal regions (which is wrong).
419
        // If we discover this, remove the non-geo entity from the set of supported regions and log.
420 402
        $idx_region_code_non_geo_entity = array_search(static::REGION_CODE_FOR_NON_GEO_ENTITY, $this->supportedRegions);
421 402
        if ($idx_region_code_non_geo_entity !== false) {
422
            unset($this->supportedRegions[$idx_region_code_non_geo_entity]);
423
        }
424 402
        $this->nanpaRegions = $this->countryCallingCodeToRegionCodeMap[static::NANPA_COUNTRY_CODE];
425 402
    }
426
427 402
    protected static function initCapturingExtnDigits()
428
    {
429 402
        static::$CAPTURING_EXTN_DIGITS = "(" . static::DIGITS . "{1,7})";
430 402
    }
431
432 402
    protected static function initExtnPatterns()
433
    {
434
        // One-character symbols that can be used to indicate an extension.
435 402
        $singleExtnSymbolsForMatching = "x\xEF\xBD\x98#\xEF\xBC\x83~\xEF\xBD\x9E";
436
        // For parsing, we are slightly more lenient in our interpretation than for matching. Here we
437
        // allow a "comma" as a possible extension indicator. When matching, this is hardly ever used to
438
        // indicate this.
439 402
        $singleExtnSymbolsForParsing = "," . $singleExtnSymbolsForMatching;
440
441 402
        static::$EXTN_PATTERNS_FOR_PARSING = static::createExtnPattern($singleExtnSymbolsForParsing);
442 402
    }
443
444
    // The FIRST_GROUP_PATTERN was originally set to $1 but there are some countries for which the
445
    // first group is not used in the national pattern (e.g. Argentina) so the $1 group does not match
446
    // correctly.  Therefore, we use \d, so that the first group actually used in the pattern will be
447
    // matched.
448
449
    /**
450
     * Helper initialiser method to create the regular-expression pattern to match extensions,
451
     * allowing the one-char extension symbols provided by {@code singleExtnSymbols}.
452
     * @param string $singleExtnSymbols
453
     * @return string
454
     */
455 402
    protected static function createExtnPattern($singleExtnSymbols)
456
    {
457
        // There are three regular expressions here. The first covers RFC 3966 format, where the
458
        // extension is added using ";ext=". The second more generic one starts with optional white
459
        // space and ends with an optional full stop (.), followed by zero or more spaces/tabs and then
460
        // the numbers themselves. The other one covers the special case of American numbers where the
461
        // extension is written with a hash at the end, such as "- 503#".
462
        // Note that the only capturing groups should be around the digits that you want to capture as
463
        // part of the extension, or else parsing will fail!
464
        // Canonical-equivalence doesn't seem to be an option with Android java, so we allow two options
465
        // for representing the accented o - the character itself, and one in the unicode decomposed
466
        // form with the combining acute accent.
467 402
        return (static::RFC3966_EXTN_PREFIX . static::$CAPTURING_EXTN_DIGITS . "|" . "[ \xC2\xA0\\t,]*" .
468 402
            "(?:e?xt(?:ensi(?:o\xCC\x81?|\xC3\xB3))?n?|(?:\xEF\xBD\x85)?\xEF\xBD\x98\xEF\xBD\x94(?:\xEF\xBD\x8E)?|" .
469 402
            "[" . $singleExtnSymbols . "]|int|\xEF\xBD\x89\xEF\xBD\x8E\xEF\xBD\x94|anexo)" .
470 402
            "[:\\.\xEF\xBC\x8E]?[ \xC2\xA0\\t,-]*" . static::$CAPTURING_EXTN_DIGITS . "#?|" .
471 402
            "[- ]+(" . static::DIGITS . "{1,5})#");
472
    }
473
474 402
    protected static function initExtnPattern()
475
    {
476 402
        static::$EXTN_PATTERN = "/(?:" . static::$EXTN_PATTERNS_FOR_PARSING . ")$/" . static::REGEX_FLAGS;
477 402
    }
478
479
    /**
480
     * Used for testing purposes only to reset the PhoneNumberUtil singleton to null.
481
     */
482 402
    public static function resetInstance()
483
    {
484 402
        static::$instance = null;
485 402
    }
486
487
    /**
488
     * Converts all alpha characters in a number to their respective digits on a keypad, but retains
489
     * existing formatting.
490
     * @param string $number
491
     * @return string
492
     */
493 1
    public static function convertAlphaCharactersInNumber($number)
494
    {
495 1
        return static::normalizeHelper($number, static::$ALPHA_PHONE_MAPPINGS, false);
496
    }
497
498
    /**
499
     * Normalizes a string of characters representing a phone number by replacing all characters found
500
     * in the accompanying map with the values therein, and stripping all other characters if
501
     * removeNonMatches is true.
502
     *
503
     * @param string $number a string of characters representing a phone number
504
     * @param array $normalizationReplacements a mapping of characters to what they should be replaced by in
505
     * the normalized version of the phone number
506
     * @param bool $removeNonMatches indicates whether characters that are not able to be replaced
507
     * should be stripped from the number. If this is false, they will be left unchanged in the number.
508
     * @return string the normalized string version of the phone number
509
     */
510 11
    protected static function normalizeHelper($number, array $normalizationReplacements, $removeNonMatches)
511
    {
512 11
        $normalizedNumber = "";
513 11
        $strLength = mb_strlen($number, 'UTF-8');
514 11
        for ($i = 0; $i < $strLength; $i++) {
515 11
            $character = mb_substr($number, $i, 1, 'UTF-8');
516 11
            if (isset($normalizationReplacements[mb_strtoupper($character, 'UTF-8')])) {
517 11
                $normalizedNumber .= $normalizationReplacements[mb_strtoupper($character, 'UTF-8')];
518 11
            } else {
519 11
                if (!$removeNonMatches) {
520 1
                    $normalizedNumber .= $character;
521 1
                }
522
            }
523
            // If neither of the above are true, we remove this character.
524 11
        }
525 11
        return $normalizedNumber;
526
    }
527
528
    /**
529
     * Helper function to check if the national prefix formatting rule has the first group only, i.e.,
530
     * does not start with the national prefix.
531
     * @param string $nationalPrefixFormattingRule
532
     * @return bool
533
     */
534
    public static function formattingRuleHasFirstGroupOnly($nationalPrefixFormattingRule)
535
    {
536
        $m = preg_match(static::FIRST_GROUP_ONLY_PREFIX_PATTERN, $nationalPrefixFormattingRule);
537
        return $m > 0;
538
    }
539
540
    /**
541
     * Convenience method to get a list of what regions the library has metadata for.
542
     * @return array
543
     */
544 249
    public function getSupportedRegions()
545
    {
546 249
        return $this->supportedRegions;
547
    }
548
549
    /**
550
     * Convenience method to get a list of what global network calling codes the library has metadata
551
     * for.
552
     * @return array
553
     */
554 5
    public function getSupportedGlobalNetworkCallingCodes()
555
    {
556 5
        return $this->countryCodesForNonGeographicalRegion;
557
    }
558
559
    /**
560
     * Gets the length of the geographical area code from the {@code nationalNumber} field of the
561
     * PhoneNumber object passed in, so that clients could use it to split a national significant
562
     * number into geographical area code and subscriber number. It works in such a way that the
563
     * resultant subscriber number should be diallable, at least on some devices. An example of how
564
     * this could be used:
565
     *
566
     * <code>
567
     * $phoneUtil = PhoneNumberUtil::getInstance();
568
     * $number = $phoneUtil->parse("16502530000", "US");
569
     * $nationalSignificantNumber = $phoneUtil->getNationalSignificantNumber($number);
570
     *
571
     * $areaCodeLength = $phoneUtil->getLengthOfGeographicalAreaCode($number);
572
     * if ($areaCodeLength > 0)
573
     * {
574
     *     $areaCode = substr($nationalSignificantNumber, 0,$areaCodeLength);
575
     *     $subscriberNumber = substr($nationalSignificantNumber, $areaCodeLength);
576
     * } else {
577
     *     $areaCode = "";
578
     *     $subscriberNumber = $nationalSignificantNumber;
579
     * }
580
     * </code>
581
     *
582
     * N.B.: area code is a very ambiguous concept, so the I18N team generally recommends against
583
     * using it for most purposes, but recommends using the more general {@code nationalNumber}
584
     * instead. Read the following carefully before deciding to use this method:
585
     * <ul>
586
     *  <li> geographical area codes change over time, and this method honors those changes;
587
     *    therefore, it doesn't guarantee the stability of the result it produces.
588
     *  <li> subscriber numbers may not be diallable from all devices (notably mobile devices, which
589
     *    typically requires the full national_number to be dialled in most regions).
590
     *  <li> most non-geographical numbers have no area codes, including numbers from non-geographical
591
     *    entities
592
     *  <li> some geographical numbers have no area codes.
593
     * </ul>
594
     * @param PhoneNumber $number PhoneNumber object for which clients want to know the length of the area code.
595
     * @return int the length of area code of the PhoneNumber object passed in.
596
     */
597 1
    public function getLengthOfGeographicalAreaCode(PhoneNumber $number)
598
    {
599 1
        $metadata = $this->getMetadataForRegion($this->getRegionCodeForNumber($number));
600 1
        if ($metadata === null) {
601 1
            return 0;
602
        }
603
        // If a country doesn't use a national prefix, and this number doesn't have an Italian leading
604
        // zero, we assume it is a closed dialling plan with no area codes.
605 1
        if (!$metadata->hasNationalPrefix() && !$number->isItalianLeadingZero()) {
0 ignored issues
show
Bug Best Practice introduced by
The expression $number->isItalianLeadingZero() of type boolean|null is loosely compared to false; this is ambiguous if the boolean can be false. You might want to explicitly use !== null instead.

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

$a = canBeFalseAndNull();

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

// Better use one of the explicit versions:
if ($a !== null) { }
if ($a !== false) { }
if ($a !== null && $a !== false) { }
Loading history...
606 1
            return 0;
607
        }
608
609 1
        if (!$this->isNumberGeographical($number)) {
610 1
            return 0;
611
        }
612
613 1
        return $this->getLengthOfNationalDestinationCode($number);
614
    }
615
616
    /**
617
     * Returns the metadata for the given region code or {@code null} if the region code is invalid
618
     * or unknown.
619
     * @param string $regionCode
620
     * @return PhoneMetadata
621
     */
622 4386
    public function getMetadataForRegion($regionCode)
623
    {
624 4386
        if (!$this->isValidRegionCode($regionCode)) {
625 311
            return null;
626
        }
627
628 4373
        return $this->metadataSource->getMetadataForRegion($regionCode);
629
    }
630
631
    /**
632
     * Helper function to check region code is not unknown or null.
633
     * @param string $regionCode
634
     * @return bool
635
     */
636 4386
    protected function isValidRegionCode($regionCode)
637
    {
638 4386
        return $regionCode !== null && in_array($regionCode, $this->supportedRegions);
639
    }
640
641
    /**
642
     * Returns the region where a phone number is from. This could be used for geocoding at the region
643
     * level.
644
     *
645
     * @param PhoneNumber $number the phone number whose origin we want to know
646
     * @return null|string  the region where the phone number is from, or null if no region matches this calling
647
     * code
648
     */
649 2140
    public function getRegionCodeForNumber(PhoneNumber $number)
650
    {
651 2140
        $countryCode = $number->getCountryCode();
652 2140
        if (!isset($this->countryCallingCodeToRegionCodeMap[$countryCode])) {
653 4
            return null;
654
        }
655 2139
        $regions = $this->countryCallingCodeToRegionCodeMap[$countryCode];
656 2139
        if (count($regions) == 1) {
657 1642
            return $regions[0];
658
        } else {
659 518
            return $this->getRegionCodeForNumberFromRegionList($number, $regions);
660
        }
661
    }
662
663
    /**
664
     * @param PhoneNumber $number
665
     * @param array $regionCodes
666
     * @return null|string
667
     */
668 518
    protected function getRegionCodeForNumberFromRegionList(PhoneNumber $number, array $regionCodes)
669
    {
670 518
        $nationalNumber = $this->getNationalSignificantNumber($number);
671 518
        foreach ($regionCodes as $regionCode) {
672
            // If leadingDigits is present, use this. Otherwise, do full validation.
673
            // Metadata cannot be null because the region codes come from the country calling code map.
674 518
            $metadata = $this->getMetadataForRegion($regionCode);
675 518
            if ($metadata->hasLeadingDigits()) {
676 173
                $nbMatches = preg_match(
677 173
                    '/' . $metadata->getLeadingDigits() . '/',
678 173
                    $nationalNumber,
679 173
                    $matches,
680
                    PREG_OFFSET_CAPTURE
681 173
                );
682 173
                if ($nbMatches > 0 && $matches[0][1] === 0) {
683 165
                    return $regionCode;
684
                }
685 508
            } 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 674 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...
686 327
                return $regionCode;
687
            }
688 254
        }
689 37
        return null;
690
    }
691
692
    /**
693
     * Gets the national significant number of the a phone number. Note a national significant number
694
     * doesn't contain a national prefix or any formatting.
695
     *
696
     * @param PhoneNumber $number the phone number for which the national significant number is needed
697
     * @return string the national significant number of the PhoneNumber object passed in
698
     */
699 1984
    public function getNationalSignificantNumber(PhoneNumber $number)
700
    {
701
        // If leading zero(s) have been set, we prefix this now. Note this is not a national prefix.
702 1984
        $nationalNumber = '';
703 1984
        if ($number->isItalianLeadingZero()) {
704 43
            $zeros = str_repeat('0', $number->getNumberOfLeadingZeros());
705 43
            $nationalNumber .= $zeros;
706 43
        }
707 1984
        $nationalNumber .= $number->getNationalNumber();
708 1984
        return $nationalNumber;
709
    }
710
711
    /**
712
     * @param string $nationalNumber
713
     * @param PhoneMetadata $metadata
714
     * @return int PhoneNumberType constant
715
     */
716 1925
    protected function getNumberTypeHelper($nationalNumber, PhoneMetadata $metadata)
717
    {
718 1925
        if (!$this->isNumberMatchingDesc($nationalNumber, $metadata->getGeneralDesc())) {
719 237
            return PhoneNumberType::UNKNOWN;
720
        }
721 1730
        if ($this->isNumberMatchingDesc($nationalNumber, $metadata->getPremiumRate())) {
722 148
            return PhoneNumberType::PREMIUM_RATE;
723
        }
724 1583
        if ($this->isNumberMatchingDesc($nationalNumber, $metadata->getTollFree())) {
725 179
            return PhoneNumberType::TOLL_FREE;
726
        }
727
728
729 1413
        if ($this->isNumberMatchingDesc($nationalNumber, $metadata->getSharedCost())) {
730 63
            return PhoneNumberType::SHARED_COST;
731
        }
732 1350
        if ($this->isNumberMatchingDesc($nationalNumber, $metadata->getVoip())) {
733 76
            return PhoneNumberType::VOIP;
734
        }
735 1277
        if ($this->isNumberMatchingDesc($nationalNumber, $metadata->getPersonalNumber())) {
736 63
            return PhoneNumberType::PERSONAL_NUMBER;
737
        }
738 1214
        if ($this->isNumberMatchingDesc($nationalNumber, $metadata->getPager())) {
739 25
            return PhoneNumberType::PAGER;
740
        }
741 1191
        if ($this->isNumberMatchingDesc($nationalNumber, $metadata->getUan())) {
742 57
            return PhoneNumberType::UAN;
743
        }
744 1136
        if ($this->isNumberMatchingDesc($nationalNumber, $metadata->getVoicemail())) {
745 11
            return PhoneNumberType::VOICEMAIL;
746
        }
747 1125
        $isFixedLine = $this->isNumberMatchingDesc($nationalNumber, $metadata->getFixedLine());
748 1125
        if ($isFixedLine) {
749 806
            if ($metadata->isSameMobileAndFixedLinePattern()) {
750
                return PhoneNumberType::FIXED_LINE_OR_MOBILE;
751 806
            } elseif ($this->isNumberMatchingDesc($nationalNumber, $metadata->getMobile())) {
752 57
                return PhoneNumberType::FIXED_LINE_OR_MOBILE;
753
            }
754 758
            return PhoneNumberType::FIXED_LINE;
755
        }
756
        // Otherwise, test to see if the number is mobile. Only do this if certain that the patterns for
757
        // mobile and fixed line aren't the same.
758 448
        if (!$metadata->isSameMobileAndFixedLinePattern() &&
759 448
            $this->isNumberMatchingDesc($nationalNumber, $metadata->getMobile())
760 448
        ) {
761 253
            return PhoneNumberType::MOBILE;
762
        }
763 218
        return PhoneNumberType::UNKNOWN;
764
    }
765
766
    /**
767
     * @param string $nationalNumber
768
     * @param PhoneNumberDesc $numberDesc
769
     * @return bool
770
     */
771 1948
    public function isNumberMatchingDesc($nationalNumber, PhoneNumberDesc $numberDesc)
772
    {
773 1948
        $nationalNumberPatternMatcher = new Matcher($numberDesc->getNationalNumberPattern(), $nationalNumber);
774
775 1948
        return $this->isNumberPossibleForDesc($nationalNumber, $numberDesc) && $nationalNumberPatternMatcher->matches();
776
    }
777
778
    /**
779
     *
780
     * Helper method to check whether a number is too short to be a regular length phone number in a
781
     * region.
782
     *
783
     * @param PhoneMetadata $regionMetadata
784
     * @param string $number
785
     * @return bool
786
     */
787 2729
    protected function isShorterThanPossibleNormalNumber(PhoneMetadata $regionMetadata, $number)
788
    {
789 2729
        $possibleNumberPattern = $regionMetadata->getGeneralDesc()->getPossibleNumberPattern();
790 2729
        return ($this->testNumberLengthAgainstPattern($possibleNumberPattern, $number) === ValidationResult::TOO_SHORT);
791
    }
792
793
    /**
794
     * @param string $nationalNumber
795
     * @param PhoneNumberDesc $numberDesc
796
     * @return bool
797
     */
798 1948
    public function isNumberPossibleForDesc($nationalNumber, PhoneNumberDesc $numberDesc)
799
    {
800 1948
        $possibleNumberPatternMatcher = new Matcher($numberDesc->getPossibleNumberPattern(), $nationalNumber);
801
802 1948
        return $possibleNumberPatternMatcher->matches();
803
    }
804
805
    /**
806
     * Tests whether a phone number has a geographical association. It checks if the number is
807
     * associated to a certain region in the country where it belongs to. Note that this doesn't
808
     * verify if the number is actually in use.
809
     * @param PhoneNumber $phoneNumber
810
     * @return bool
811
     */
812 2
    public function isNumberGeographical(PhoneNumber $phoneNumber)
813
    {
814 2
        $numberType = $this->getNumberType($phoneNumber);
815
816
        return $numberType == PhoneNumberType::FIXED_LINE
817 2
        || $numberType == PhoneNumberType::FIXED_LINE_OR_MOBILE
818 2
        || (in_array($phoneNumber->getCountryCode(), static::$GEO_MOBILE_COUNTRIES)
819 2
            && $numberType == PhoneNumberType::MOBILE);
820
    }
821
822
    /**
823
     * Gets the type of a phone number.
824
     * @param PhoneNumber $number the number the phone number that we want to know the type
825
     * @return int PhoneNumberType the type of the phone number
826
     */
827 1359
    public function getNumberType(PhoneNumber $number)
828
    {
829 1359
        $regionCode = $this->getRegionCodeForNumber($number);
830 1359
        $metadata = $this->getMetadataForRegionOrCallingCode($number->getCountryCode(), $regionCode);
831 1359
        if ($metadata === null) {
832 8
            return PhoneNumberType::UNKNOWN;
833
        }
834 1358
        $nationalSignificantNumber = $this->getNationalSignificantNumber($number);
835 1358
        return $this->getNumberTypeHelper($nationalSignificantNumber, $metadata);
836
    }
837
838
    /**
839
     * @param int $countryCallingCode
840
     * @param string $regionCode
841
     * @return PhoneMetadata
842
     */
843 1916
    protected function getMetadataForRegionOrCallingCode($countryCallingCode, $regionCode)
844
    {
845 1916
        return static::REGION_CODE_FOR_NON_GEO_ENTITY === $regionCode ?
846 1916
            $this->getMetadataForNonGeographicalRegion($countryCallingCode) : $this->getMetadataForRegion($regionCode);
847
    }
848
849
    /**
850
     * @param int $countryCallingCode
851
     * @return PhoneMetadata
852
     */
853 35
    public function getMetadataForNonGeographicalRegion($countryCallingCode)
854
    {
855 35
        if (!isset($this->countryCallingCodeToRegionCodeMap[$countryCallingCode])) {
856 1
            return null;
857
        }
858 35
        return $this->metadataSource->getMetadataForNonGeographicalRegion($countryCallingCode);
859
    }
860
861
    /**
862
     * Gets the length of the national destination code (NDC) from the PhoneNumber object passed in,
863
     * so that clients could use it to split a national significant number into NDC and subscriber
864
     * number. The NDC of a phone number is normally the first group of digit(s) right after the
865
     * country calling code when the number is formatted in the international format, if there is a
866
     * subscriber number part that follows. An example of how this could be used:
867
     *
868
     * <code>
869
     * $phoneUtil = PhoneNumberUtil::getInstance();
870
     * $number = $phoneUtil->parse("18002530000", "US");
871
     * $nationalSignificantNumber = $phoneUtil->getNationalSignificantNumber($number);
872
     *
873
     * $nationalDestinationCodeLength = $phoneUtil->getLengthOfNationalDestinationCode($number);
874
     * if ($nationalDestinationCodeLength > 0) {
875
     *     $nationalDestinationCode = substr($nationalSignificantNumber, 0, $nationalDestinationCodeLength);
876
     *     $subscriberNumber = substr($nationalSignificantNumber, $nationalDestinationCodeLength);
877
     * } else {
878
     *     $nationalDestinationCode = "";
879
     *     $subscriberNumber = $nationalSignificantNumber;
880
     * }
881
     * </code>
882
     *
883
     * Refer to the unit tests to see the difference between this function and
884
     * {@link #getLengthOfGeographicalAreaCode}.
885
     *
886
     * @param PhoneNumber $number the PhoneNumber object for which clients want to know the length of the NDC.
887
     * @return int the length of NDC of the PhoneNumber object passed in.
888
     */
889 2
    public function getLengthOfNationalDestinationCode(PhoneNumber $number)
890
    {
891 2
        if ($number->hasExtension()) {
892
            // We don't want to alter the proto given to us, but we don't want to include the extension
893
            // when we format it, so we copy it and clear the extension here.
894
            $copiedProto = new PhoneNumber();
895
            $copiedProto->mergeFrom($number);
896
            $copiedProto->clearExtension();
897
        } else {
898 2
            $copiedProto = clone $number;
899
        }
900
901 2
        $nationalSignificantNumber = $this->format($copiedProto, PhoneNumberFormat::INTERNATIONAL);
902
903 2
        $numberGroups = preg_split('/' . static::NON_DIGITS_PATTERN . '/', $nationalSignificantNumber);
904
905
        // The pattern will start with "+COUNTRY_CODE " so the first group will always be the empty
906
        // string (before the + symbol) and the second group will be the country calling code. The third
907
        // group will be area code if it is not the last group.
908 2
        if (count($numberGroups) <= 3) {
909 1
            return 0;
910
        }
911
912 2
        if ($this->getNumberType($number) == PhoneNumberType::MOBILE) {
913
            // For example Argentinian mobile numbers, when formatted in the international format, are in
914
            // the form of +54 9 NDC XXXX.... As a result, we take the length of the third group (NDC) and
915
            // add the length of the second group (which is the mobile token), which also forms part of
916
            // the national significant number. This assumes that the mobile token is always formatted
917
            // separately from the rest of the phone number.
918
919 1
            $mobileToken = static::getCountryMobileToken($number->getCountryCode());
920 1
            if ($mobileToken !== "") {
921 1
                return mb_strlen($numberGroups[2]) + mb_strlen($numberGroups[3]);
922
            }
923 1
        }
924 2
        return mb_strlen($numberGroups[2]);
925
    }
926
927
    /**
928
     * Formats a phone number in the specified format using default rules. Note that this does not
929
     * promise to produce a phone number that the user can dial from where they are - although we do
930
     * format in either 'national' or 'international' format depending on what the client asks for, we
931
     * do not currently support a more abbreviated format, such as for users in the same "area" who
932
     * could potentially dial the number without area code. Note that if the phone number has a
933
     * country calling code of 0 or an otherwise invalid country calling code, we cannot work out
934
     * which formatting rules to apply so we return the national significant number with no formatting
935
     * applied.
936
     *
937
     * @param PhoneNumber $number the phone number to be formatted
938
     * @param int $numberFormat the PhoneNumberFormat the phone number should be formatted into
939
     * @return string the formatted phone number
940
     */
941 289
    public function format(PhoneNumber $number, $numberFormat)
942
    {
943 289
        if ($number->getNationalNumber() == 0 && $number->hasRawInput()) {
944
            // Unparseable numbers that kept their raw input just use that.
945
            // This is the only case where a number can be formatted as E164 without a
946
            // leading '+' symbol (but the original number wasn't parseable anyway).
947
            // TODO: Consider removing the 'if' above so that unparseable
948
            // strings without raw input format to the empty string instead of "+00"
949 1
            $rawInput = $number->getRawInput();
950 1
            if (mb_strlen($rawInput) > 0) {
951 1
                return $rawInput;
952
            }
953
        }
954 289
        $metadata = null;
955 289
        $formattedNumber = "";
956 289
        $countryCallingCode = $number->getCountryCode();
957 289
        $nationalSignificantNumber = $this->getNationalSignificantNumber($number);
958 289
        if ($numberFormat == PhoneNumberFormat::E164) {
959
            // Early exit for E164 case (even if the country calling code is invalid) since no formatting
960
            // of the national number needs to be applied. Extensions are not formatted.
961 265
            $formattedNumber .= $nationalSignificantNumber;
962 265
            $this->prefixNumberWithCountryCallingCode($countryCallingCode, PhoneNumberFormat::E164, $formattedNumber);
963 289
        } elseif (!$this->hasValidCountryCallingCode($countryCallingCode)) {
964 1
            $formattedNumber .= $nationalSignificantNumber;
965 1
        } else {
966
            // Note getRegionCodeForCountryCode() is used because formatting information for regions which
967
            // share a country calling code is contained by only one region for performance reasons. For
968
            // example, for NANPA regions it will be contained in the metadata for US.
969 41
            $regionCode = $this->getRegionCodeForCountryCode($countryCallingCode);
970
            // Metadata cannot be null because the country calling code is valid (which means that the
971
            // region code cannot be ZZ and must be one of our supported region codes).
972 41
            $metadata = $this->getMetadataForRegionOrCallingCode($countryCallingCode, $regionCode);
973 41
            $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 972 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...
974 41
            $this->prefixNumberWithCountryCallingCode($countryCallingCode, $numberFormat, $formattedNumber);
975
        }
976 289
        $this->maybeAppendFormattedExtension($number, $metadata, $numberFormat, $formattedNumber);
977 289
        return $formattedNumber;
978
    }
979
980
    /**
981
     * A helper function that is used by format and formatByPattern.
982
     * @param int $countryCallingCode
983
     * @param int $numberFormat PhoneNumberFormat
984
     * @param string $formattedNumber
985
     */
986 290
    protected function prefixNumberWithCountryCallingCode($countryCallingCode, $numberFormat, &$formattedNumber)
987
    {
988
        switch ($numberFormat) {
989 290
            case PhoneNumberFormat::E164:
990 265
                $formattedNumber = static::PLUS_SIGN . $countryCallingCode . $formattedNumber;
991 265
                return;
992 42
            case PhoneNumberFormat::INTERNATIONAL:
993 19
                $formattedNumber = static::PLUS_SIGN . $countryCallingCode . " " . $formattedNumber;
994 19
                return;
995 39
            case PhoneNumberFormat::RFC3966:
996 4
                $formattedNumber = static::RFC3966_PREFIX . static::PLUS_SIGN . $countryCallingCode . "-" . $formattedNumber;
997 4
                return;
998 39
            case PhoneNumberFormat::NATIONAL:
999 39
            default:
1000 39
                return;
1001
        }
1002
    }
1003
1004
    /**
1005
     * Helper function to check the country calling code is valid.
1006
     * @param int $countryCallingCode
1007
     * @return bool
1008
     */
1009 47
    protected function hasValidCountryCallingCode($countryCallingCode)
1010
    {
1011 47
        return isset($this->countryCallingCodeToRegionCodeMap[$countryCallingCode]);
1012
    }
1013
1014
    /**
1015
     * Returns the region code that matches the specific country calling code. In the case of no
1016
     * region code being found, ZZ will be returned. In the case of multiple regions, the one
1017
     * designated in the metadata as the "main" region for this calling code will be returned. If the
1018
     * countryCallingCode entered is valid but doesn't match a specific region (such as in the case of
1019
     * non-geographical calling codes like 800) the value "001" will be returned (corresponding to
1020
     * the value for World in the UN M.49 schema).
1021
     *
1022
     * @param int $countryCallingCode
1023
     * @return string
1024
     */
1025 336
    public function getRegionCodeForCountryCode($countryCallingCode)
1026
    {
1027 336
        $regionCodes = isset($this->countryCallingCodeToRegionCodeMap[$countryCallingCode]) ? $this->countryCallingCodeToRegionCodeMap[$countryCallingCode] : null;
1028 336
        return $regionCodes === null ? static::UNKNOWN_REGION : $regionCodes[0];
1029
    }
1030
1031
    /**
1032
     * Note in some regions, the national number can be written in two completely different ways
1033
     * depending on whether it forms part of the NATIONAL format or INTERNATIONAL format. The
1034
     * numberFormat parameter here is used to specify which format to use for those cases. If a
1035
     * carrierCode is specified, this will be inserted into the formatted string to replace $CC.
1036
     * @param string $number
1037
     * @param PhoneMetadata $metadata
1038
     * @param int $numberFormat PhoneNumberFormat
1039
     * @param null|string $carrierCode
1040
     * @return string
1041
     */
1042 42
    protected function formatNsn($number, PhoneMetadata $metadata, $numberFormat, $carrierCode = null)
1043
    {
1044 42
        $intlNumberFormats = $metadata->intlNumberFormats();
1045
        // When the intlNumberFormats exists, we use that to format national number for the
1046
        // INTERNATIONAL format instead of using the numberDesc.numberFormats.
1047 42
        $availableFormats = (count($intlNumberFormats) == 0 || $numberFormat == PhoneNumberFormat::NATIONAL)
1048 42
            ? $metadata->numberFormats()
1049 42
            : $metadata->intlNumberFormats();
1050 42
        $formattingPattern = $this->chooseFormattingPatternForNumber($availableFormats, $number);
1051 42
        return ($formattingPattern === null)
1052 42
            ? $number
1053 42
            : $this->formatNsnUsingPattern($number, $formattingPattern, $numberFormat, $carrierCode);
1054
    }
1055
1056
    /**
1057
     * @param NumberFormat[] $availableFormats
1058
     * @param string $nationalNumber
1059
     * @return NumberFormat|null
1060
     */
1061 43
    public function chooseFormattingPatternForNumber(array $availableFormats, $nationalNumber)
1062
    {
1063 43
        foreach ($availableFormats as $numFormat) {
1064 43
            $leadingDigitsPatternMatcher = null;
1065 43
            $size = $numFormat->leadingDigitsPatternSize();
1066
            // We always use the last leading_digits_pattern, as it is the most detailed.
1067 43
            if ($size > 0) {
1068 38
                $leadingDigitsPatternMatcher = new Matcher(
1069 38
                    $numFormat->getLeadingDigitsPattern($size - 1),
1070
                    $nationalNumber
1071 38
                );
1072 38
            }
1073 43
            if ($size == 0 || $leadingDigitsPatternMatcher->lookingAt()) {
1074 42
                $m = new Matcher($numFormat->getPattern(), $nationalNumber);
1075 42
                if ($m->matches() > 0) {
1076 42
                    return $numFormat;
1077
                }
1078 12
            }
1079 32
        }
1080 9
        return null;
1081
    }
1082
1083
    /**
1084
     * Note that carrierCode is optional - if null or an empty string, no carrier code replacement
1085
     * will take place.
1086
     * @param string $nationalNumber
1087
     * @param NumberFormat $formattingPattern
1088
     * @param int $numberFormat PhoneNumberFormat
1089
     * @param null|string $carrierCode
1090
     * @return string
1091
     */
1092 42
    protected function formatNsnUsingPattern(
1093
        $nationalNumber,
1094
        NumberFormat $formattingPattern,
1095
        $numberFormat,
1096
        $carrierCode = null
1097
    ) {
1098 42
        $numberFormatRule = $formattingPattern->getFormat();
1099 42
        $m = new Matcher($formattingPattern->getPattern(), $nationalNumber);
1100 42
        if ($numberFormat === PhoneNumberFormat::NATIONAL &&
1101 42
            $carrierCode !== null && mb_strlen($carrierCode) > 0 &&
1102 2
            mb_strlen($formattingPattern->getDomesticCarrierCodeFormattingRule()) > 0
1103 42
        ) {
1104
            // Replace the $CC in the formatting rule with the desired carrier code.
1105 2
            $carrierCodeFormattingRule = $formattingPattern->getDomesticCarrierCodeFormattingRule();
1106 2
            $ccPatternMatcher = new Matcher(static::CC_PATTERN, $carrierCodeFormattingRule);
1107 2
            $carrierCodeFormattingRule = $ccPatternMatcher->replaceFirst($carrierCode);
1108
            // Now replace the $FG in the formatting rule with the first group and the carrier code
1109
            // combined in the appropriate way.
1110 2
            $firstGroupMatcher = new Matcher(static::FIRST_GROUP_PATTERN, $numberFormatRule);
1111 2
            $numberFormatRule = $firstGroupMatcher->replaceFirst($carrierCodeFormattingRule);
1112 2
            $formattedNationalNumber = $m->replaceAll($numberFormatRule);
1113 2
        } else {
1114
            // Use the national prefix formatting rule instead.
1115 42
            $nationalPrefixFormattingRule = $formattingPattern->getNationalPrefixFormattingRule();
1116 42
            if ($numberFormat == PhoneNumberFormat::NATIONAL &&
1117 42
                $nationalPrefixFormattingRule !== null &&
1118 37
                mb_strlen($nationalPrefixFormattingRule) > 0
1119 42
            ) {
1120 22
                $firstGroupMatcher = new Matcher(static::FIRST_GROUP_PATTERN, $numberFormatRule);
1121 22
                $formattedNationalNumber = $m->replaceAll(
1122 22
                    $firstGroupMatcher->replaceFirst($nationalPrefixFormattingRule)
1123 22
                );
1124 22
            } else {
1125 34
                $formattedNationalNumber = $m->replaceAll($numberFormatRule);
1126
            }
1127
        }
1128 42
        if ($numberFormat == PhoneNumberFormat::RFC3966) {
1129
            // Strip any leading punctuation.
1130 4
            $matcher = new Matcher(static::$SEPARATOR_PATTERN, $formattedNationalNumber);
1131 4
            if ($matcher->lookingAt()) {
1132 1
                $formattedNationalNumber = $matcher->replaceFirst("");
1133 1
            }
1134
            // Replace the rest with a dash between each number group.
1135 4
            $formattedNationalNumber = $matcher->reset($formattedNationalNumber)->replaceAll("-");
1136 4
        }
1137 42
        return $formattedNationalNumber;
1138
    }
1139
1140
    /**
1141
     * Appends the formatted extension of a phone number to formattedNumber, if the phone number had
1142
     * an extension specified.
1143
     *
1144
     * @param PhoneNumber $number
1145
     * @param PhoneMetadata|null $metadata
1146
     * @param int $numberFormat PhoneNumberFormat
1147
     * @param string $formattedNumber
1148
     */
1149 291
    protected function maybeAppendFormattedExtension(PhoneNumber $number, $metadata, $numberFormat, &$formattedNumber)
1150
    {
1151 291
        if ($number->hasExtension() && mb_strlen($number->getExtension()) > 0) {
1152 2
            if ($numberFormat === PhoneNumberFormat::RFC3966) {
1153 1
                $formattedNumber .= static::RFC3966_EXTN_PREFIX . $number->getExtension();
1154 1
            } else {
1155 2
                if (!empty($metadata) && $metadata->hasPreferredExtnPrefix()) {
1156 1
                    $formattedNumber .= $metadata->getPreferredExtnPrefix() . $number->getExtension();
1157 1
                } else {
1158 2
                    $formattedNumber .= static::DEFAULT_EXTN_PREFIX . $number->getExtension();
1159
                }
1160
            }
1161 2
        }
1162 291
    }
1163
1164
    /**
1165
     * Returns the mobile token for the provided country calling code if it has one, otherwise
1166
     * returns an empty string. A mobile token is a number inserted before the area code when dialing
1167
     * a mobile number from that country from abroad.
1168
     *
1169
     * @param int $countryCallingCode the country calling code for which we want the mobile token
1170
     * @return string the mobile token, as a string, for the given country calling code
1171
     */
1172 16
    public static function getCountryMobileToken($countryCallingCode)
1173
    {
1174 16
        if (array_key_exists($countryCallingCode, static::$MOBILE_TOKEN_MAPPINGS)) {
1175 3
            return static::$MOBILE_TOKEN_MAPPINGS[$countryCallingCode];
1176
        }
1177 15
        return "";
1178
    }
1179
1180
    /**
1181
     * Checks if the number is a valid vanity (alpha) number such as 800 MICROSOFT. A valid vanity
1182
     * number will start with at least 3 digits and will have three or more alpha characters. This
1183
     * does not do region-specific checks - to work out if this number is actually valid for a region,
1184
     * it should be parsed and methods such as {@link #isPossibleNumberWithReason} and
1185
     * {@link #isValidNumber} should be used.
1186
     *
1187
     * @param string $number the number that needs to be checked
1188
     * @return bool true if the number is a valid vanity number
1189
     */
1190 1
    public function isAlphaNumber($number)
1191
    {
1192 1
        if (!$this->isViablePhoneNumber($number)) {
1193
            // Number is too short, or doesn't match the basic phone number pattern.
1194 1
            return false;
1195
        }
1196 1
        $this->maybeStripExtension($number);
1197 1
        return (bool)preg_match('/' . static::VALID_ALPHA_PHONE_PATTERN . '/' . static::REGEX_FLAGS, $number);
1198
    }
1199
1200
    /**
1201
     * Checks to see if the string of characters could possibly be a phone number at all. At the
1202
     * moment, checks to see that the string begins with at least 2 digits, ignoring any punctuation
1203
     * commonly found in phone numbers.
1204
     * This method does not require the number to be normalized in advance - but does assume that
1205
     * leading non-number symbols have been removed, such as by the method extractPossibleNumber.
1206
     *
1207
     * @param string $number to be checked for viability as a phone number
1208
     * @return boolean true if the number could be a phone number of some sort, otherwise false
1209
     */
1210 2733
    public static function isViablePhoneNumber($number)
1211
    {
1212 2733
        if (mb_strlen($number) < static::MIN_LENGTH_FOR_NSN) {
1213 4
            return false;
1214
        }
1215
1216 2733
        $validPhoneNumberPattern = static::getValidPhoneNumberPattern();
1217
1218 2733
        $m = preg_match($validPhoneNumberPattern, $number);
1219 2733
        return $m > 0;
1220
    }
1221
1222
    /**
1223
     * We append optionally the extension pattern to the end here, as a valid phone number may
1224
     * have an extension prefix appended, followed by 1 or more digits.
1225
     * @return string
1226
     */
1227 2733
    protected static function getValidPhoneNumberPattern()
1228
    {
1229 2733
        return static::$VALID_PHONE_NUMBER_PATTERN;
1230
    }
1231
1232
    /**
1233
     * Strips any extension (as in, the part of the number dialled after the call is connected,
1234
     * usually indicated with extn, ext, x or similar) from the end of the number, and returns it.
1235
     *
1236
     * @param string $number the non-normalized telephone number that we wish to strip the extension from
1237
     * @return string the phone extension
1238
     */
1239 2730
    protected function maybeStripExtension(&$number)
1240
    {
1241 2730
        $matches = array();
1242 2730
        $find = preg_match(static::$EXTN_PATTERN, $number, $matches, PREG_OFFSET_CAPTURE);
1243
        // If we find a potential extension, and the number preceding this is a viable number, we assume
1244
        // it is an extension.
1245 2730
        if ($find > 0 && $this->isViablePhoneNumber(substr($number, 0, $matches[0][1]))) {
1246
            // The numbers are captured into groups in the regular expression.
1247
1248 5
            for ($i = 1, $length = count($matches); $i <= $length; $i++) {
1249 5
                if ($matches[$i][0] != "") {
1250
                    // We go through the capturing groups until we find one that captured some digits. If none
1251
                    // did, then we will return the empty string.
1252 5
                    $extension = $matches[$i][0];
1253 5
                    $number = substr($number, 0, $matches[0][1]);
1254 5
                    return $extension;
1255
                }
1256 5
            }
1257
        }
1258 2730
        return "";
1259
    }
1260
1261
    /**
1262
     * Parses a string and returns it in proto buffer format. This method differs from {@link #parse}
1263
     * in that it always populates the raw_input field of the protocol buffer with numberToParse as
1264
     * well as the country_code_source field.
1265
     *
1266
     * @param string $numberToParse number that we are attempting to parse. This can contain formatting
1267
     *                                  such as +, ( and -, as well as a phone number extension. It can also
1268
     *                                  be provided in RFC3966 format.
1269
     * @param string $defaultRegion region that we are expecting the number to be from. This is only used
1270
     *                                  if the number being parsed is not written in international format.
1271
     *                                  The country calling code for the number in this case would be stored
1272
     *                                  as that of the default region supplied.
1273
     * @param PhoneNumber $phoneNumber
1274
     * @return PhoneNumber              a phone number proto buffer filled with the parsed number
1275
     */
1276 3
    public function parseAndKeepRawInput($numberToParse, $defaultRegion, PhoneNumber $phoneNumber = null)
1277
    {
1278 3
        if ($phoneNumber === null) {
1279 3
            $phoneNumber = new PhoneNumber();
1280 3
        }
1281 3
        $this->parseHelper($numberToParse, $defaultRegion, true, true, $phoneNumber);
1282 3
        return $phoneNumber;
1283
    }
1284
1285
    /**
1286
     * A helper function to set the values related to leading zeros in a PhoneNumber.
1287
     * @param string $nationalNumber
1288
     * @param PhoneNumber $phoneNumber
1289
     */
1290 2727
    public static function setItalianLeadingZerosForPhoneNumber($nationalNumber, PhoneNumber $phoneNumber)
1291
    {
1292 2727
        if (strlen($nationalNumber) > 1 && substr($nationalNumber, 0, 1) == '0') {
1293 48
            $phoneNumber->setItalianLeadingZero(true);
1294 48
            $numberOfLeadingZeros = 1;
1295
            // Note that if the national number is all "0"s, the last "0" is not counted as a leading
1296
            // zero.
1297 48
            while ($numberOfLeadingZeros < (strlen($nationalNumber) - 1) &&
1298 48
                substr($nationalNumber, $numberOfLeadingZeros, 1) == '0') {
1299 5
                $numberOfLeadingZeros++;
1300 5
            }
1301
1302 48
            if ($numberOfLeadingZeros != 1) {
1303 5
                $phoneNumber->setNumberOfLeadingZeros($numberOfLeadingZeros);
1304 5
            }
1305 48
        }
1306 2727
    }
1307
1308
    /**
1309
     * Parses a string and fills up the phoneNumber. This method is the same as the public
1310
     * parse() method, with the exception that it allows the default region to be null, for use by
1311
     * isNumberMatch(). checkRegion should be set to false if it is permitted for the default region
1312
     * to be null or unknown ("ZZ").
1313
     * @param string $numberToParse
1314
     * @param string $defaultRegion
1315
     * @param bool $keepRawInput
1316
     * @param bool $checkRegion
1317
     * @param PhoneNumber $phoneNumber
1318
     * @throws NumberParseException
1319
     */
1320 2732
    protected function parseHelper($numberToParse, $defaultRegion, $keepRawInput, $checkRegion, PhoneNumber $phoneNumber)
1321
    {
1322 2732
        if ($numberToParse === null) {
1323 2
            throw new NumberParseException(NumberParseException::NOT_A_NUMBER, "The phone number supplied was null.");
1324
        }
1325
1326 2731
        $numberToParse = trim($numberToParse);
1327
1328 2731
        if (mb_strlen($numberToParse) > static::MAX_INPUT_STRING_LENGTH) {
1329 1
            throw new NumberParseException(
1330 1
                NumberParseException::TOO_LONG,
1331
                "The string supplied was too long to parse."
1332 1
            );
1333
        }
1334
1335 2730
        $nationalNumber = '';
1336 2730
        $this->buildNationalNumberForParsing($numberToParse, $nationalNumber);
1337
1338 2730
        if (!$this->isViablePhoneNumber($nationalNumber)) {
1339 4
            throw new NumberParseException(
1340 4
                NumberParseException::NOT_A_NUMBER,
1341
                "The string supplied did not seem to be a phone number."
1342 4
            );
1343
        }
1344
1345
        // Check the region supplied is valid, or that the extracted number starts with some sort of +
1346
        // sign so the number's region can be determined.
1347 2729
        if ($checkRegion && !$this->checkRegionForParsing($nationalNumber, $defaultRegion)) {
1348 5
            throw new NumberParseException(
1349 5
                NumberParseException::INVALID_COUNTRY_CODE,
1350
                "Missing or invalid default region."
1351 5
            );
1352
        }
1353
1354 2729
        if ($keepRawInput) {
1355 3
            $phoneNumber->setRawInput($numberToParse);
1356 3
        }
1357
        // Attempt to parse extension first, since it doesn't require region-specific data and we want
1358
        // to have the non-normalised number here.
1359 2729
        $extension = $this->maybeStripExtension($nationalNumber);
1360 2729
        if (mb_strlen($extension) > 0) {
1361 4
            $phoneNumber->setExtension($extension);
1362 4
        }
1363
1364 2729
        $regionMetadata = $this->getMetadataForRegion($defaultRegion);
1365
        // Check to see if the number is given in international format so we know whether this number is
1366
        // from the default region or not.
1367 2729
        $normalizedNationalNumber = "";
1368
        try {
1369
            // TODO: This method should really just take in the string buffer that has already
1370
            // been created, and just remove the prefix, rather than taking in a string and then
1371
            // outputting a string buffer.
1372 2729
            $countryCode = $this->maybeExtractCountryCode(
1373 2729
                $nationalNumber,
1374 2729
                $regionMetadata,
1375 2729
                $normalizedNationalNumber,
1376 2729
                $keepRawInput,
1377
                $phoneNumber
1378 2729
            );
1379 2729
        } catch (NumberParseException $e) {
1380 2
            $matcher = new Matcher(static::$PLUS_CHARS_PATTERN, $nationalNumber);
1381 2
            if ($e->getErrorType() == NumberParseException::INVALID_COUNTRY_CODE && $matcher->lookingAt()) {
1382
                // Strip the plus-char, and try again.
1383 2
                $countryCode = $this->maybeExtractCountryCode(
1384 2
                    substr($nationalNumber, $matcher->end()),
1385 2
                    $regionMetadata,
1386 2
                    $normalizedNationalNumber,
1387 2
                    $keepRawInput,
1388
                    $phoneNumber
1389 2
                );
1390 2
                if ($countryCode == 0) {
1391 1
                    throw new NumberParseException(
1392 1
                        NumberParseException::INVALID_COUNTRY_CODE,
1393
                        "Could not interpret numbers after plus-sign."
1394 1
                    );
1395
                }
1396 1
            } else {
1397 1
                throw new NumberParseException($e->getErrorType(), $e->getMessage(), $e);
1398
            }
1399
        }
1400 2729
        if ($countryCode !== 0) {
1401 288
            $phoneNumberRegion = $this->getRegionCodeForCountryCode($countryCode);
1402 288
            if ($phoneNumberRegion != $defaultRegion) {
1403
                // Metadata cannot be null because the country calling code is valid.
1404 275
                $regionMetadata = $this->getMetadataForRegionOrCallingCode($countryCode, $phoneNumberRegion);
1405 275
            }
1406 288
        } else {
1407
            // If no extracted country calling code, use the region supplied instead. The national number
1408
            // is just the normalized version of the number we were given to parse.
1409
1410 2699
            $normalizedNationalNumber .= $this->normalize($nationalNumber);
1411 2699
            if ($defaultRegion !== null) {
1412 2699
                $countryCode = $regionMetadata->getCountryCode();
1413 2699
                $phoneNumber->setCountryCode($countryCode);
1414 2699
            } elseif ($keepRawInput) {
1415
                $phoneNumber->clearCountryCodeSource();
1416
            }
1417
        }
1418 2729
        if (mb_strlen($normalizedNationalNumber) < static::MIN_LENGTH_FOR_NSN) {
1419 2
            throw new NumberParseException(
1420 2
                NumberParseException::TOO_SHORT_NSN,
1421
                "The string supplied is too short to be a phone number."
1422 2
            );
1423
        }
1424 2728
        if ($regionMetadata !== null) {
1425 2728
            $carrierCode = "";
1426 2728
            $potentialNationalNumber = $normalizedNationalNumber;
1427 2728
            $this->maybeStripNationalPrefixAndCarrierCode($potentialNationalNumber, $regionMetadata, $carrierCode);
1428
            // We require that the NSN remaining after stripping the national prefix and carrier code be
1429
            // of a possible length for the region. Otherwise, we don't do the stripping, since the
1430
            // original number could be a valid short number.
1431 2728
            if (!$this->isShorterThanPossibleNormalNumber($regionMetadata, $potentialNationalNumber)) {
1432 2079
                $normalizedNationalNumber = $potentialNationalNumber;
1433 2079
                if ($keepRawInput) {
1434 3
                    $phoneNumber->setPreferredDomesticCarrierCode($carrierCode);
1435 3
                }
1436 2079
            }
1437 2728
        }
1438 2728
        $lengthOfNationalNumber = mb_strlen($normalizedNationalNumber);
1439 2728
        if ($lengthOfNationalNumber < static::MIN_LENGTH_FOR_NSN) {
1440
            throw new NumberParseException(
1441
                NumberParseException::TOO_SHORT_NSN,
1442
                "The string supplied is too short to be a phone number."
1443
            );
1444
        }
1445 2728
        if ($lengthOfNationalNumber > static::MAX_LENGTH_FOR_NSN) {
1446 1
            throw new NumberParseException(
1447 1
                NumberParseException::TOO_LONG,
1448
                "The string supplied is too long to be a phone number."
1449 1
            );
1450
        }
1451 2727
        $this->setItalianLeadingZerosForPhoneNumber($normalizedNationalNumber, $phoneNumber);
1452
1453
1454
        /*
1455
         * We have to store the National Number as a string instead of a "long" as Google do
1456
         *
1457
         * Since PHP doesn't always support 64 bit INTs, this was a float, but that had issues
1458
         * with long numbers.
1459
         *
1460
         * We have to remove the leading zeroes ourself though
1461
         */
1462 2727
        if ((int)$normalizedNationalNumber == 0) {
1463 3
            $normalizedNationalNumber = "0";
1464 3
        } else {
1465 2725
            $normalizedNationalNumber = ltrim($normalizedNationalNumber, '0');
1466
        }
1467
1468 2727
        $phoneNumber->setNationalNumber($normalizedNationalNumber);
1469 2727
    }
1470
1471
    /**
1472
     * Converts numberToParse to a form that we can parse and write it to nationalNumber if it is
1473
     * written in RFC3966; otherwise extract a possible number out of it and write to nationalNumber.
1474
     * @param string $numberToParse
1475
     * @param string $nationalNumber
1476
     */
1477 2730
    protected function buildNationalNumberForParsing($numberToParse, &$nationalNumber)
1478
    {
1479 2730
        $indexOfPhoneContext = strpos($numberToParse, static::RFC3966_PHONE_CONTEXT);
1480 2730
        if ($indexOfPhoneContext > 0) {
1481 6
            $phoneContextStart = $indexOfPhoneContext + mb_strlen(static::RFC3966_PHONE_CONTEXT);
1482
            // If the phone context contains a phone number prefix, we need to capture it, whereas domains
1483
            // will be ignored.
1484 6
            if (substr($numberToParse, $phoneContextStart, 1) == static::PLUS_SIGN) {
1485
                // Additional parameters might follow the phone context. If so, we will remove them here
1486
                // because the parameters after phone context are not important for parsing the
1487
                // phone number.
1488 3
                $phoneContextEnd = strpos($numberToParse, ';', $phoneContextStart);
1489 3
                if ($phoneContextEnd > 0) {
1490 1
                    $nationalNumber .= substr($numberToParse, $phoneContextStart, $phoneContextEnd - $phoneContextStart);
1491 1
                } else {
1492 3
                    $nationalNumber .= substr($numberToParse, $phoneContextStart);
1493
                }
1494 3
            }
1495
1496
            // Now append everything between the "tel:" prefix and the phone-context. This should include
1497
            // the national number, an optional extension or isdn-subaddress component. Note we also
1498
            // handle the case when "tel:" is missing, as we have seen in some of the phone number inputs.
1499
            // In that case, we append everything from the beginning.
1500
1501 6
            $indexOfRfc3966Prefix = strpos($numberToParse, static::RFC3966_PREFIX);
1502 6
            $indexOfNationalNumber = ($indexOfRfc3966Prefix !== false) ? $indexOfRfc3966Prefix + strlen(static::RFC3966_PREFIX) : 0;
1503 6
            $nationalNumber .= substr($numberToParse, $indexOfNationalNumber, ($indexOfPhoneContext - $indexOfNationalNumber));
1504 6
        } else {
1505
            // Extract a possible number from the string passed in (this strips leading characters that
1506
            // could not be the start of a phone number.)
1507 2730
            $nationalNumber .= $this->extractPossibleNumber($numberToParse);
1508
        }
1509
1510
        // Delete the isdn-subaddress and everything after it if it is present. Note extension won't
1511
        // appear at the same time with isdn-subaddress according to paragraph 5.3 of the RFC3966 spec,
1512 2730
        $indexOfIsdn = strpos($nationalNumber, static::RFC3966_ISDN_SUBADDRESS);
1513 2730
        if ($indexOfIsdn > 0) {
1514 5
            $nationalNumber = substr($nationalNumber, 0, $indexOfIsdn);
1515 5
        }
1516
        // If both phone context and isdn-subaddress are absent but other parameters are present, the
1517
        // parameters are left in nationalNumber. This is because we are concerned about deleting
1518
        // content from a potential number string when there is no strong evidence that the number is
1519
        // actually written in RFC3966.
1520 2730
    }
1521
1522
    /**
1523
     * Attempts to extract a possible number from the string passed in. This currently strips all
1524
     * leading characters that cannot be used to start a phone number. Characters that can be used to
1525
     * start a phone number are defined in the VALID_START_CHAR_PATTERN. If none of these characters
1526
     * are found in the number passed in, an empty string is returned. This function also attempts to
1527
     * strip off any alternative extensions or endings if two or more are present, such as in the case
1528
     * of: (530) 583-6985 x302/x2303. The second extension here makes this actually two phone numbers,
1529
     * (530) 583-6985 x302 and (530) 583-6985 x2303. We remove the second extension so that the first
1530
     * number is parsed correctly.
1531
     *
1532
     * @param int $number the string that might contain a phone number
1533
     * @return string the number, stripped of any non-phone-number prefix (such as "Tel:") or an empty
1534
     *                string if no character used to start phone numbers (such as + or any digit) is
1535
     *                found in the number
1536
     */
1537 2768
    public static function extractPossibleNumber($number)
1538
    {
1539 2768
        $matches = array();
1540 2768
        $match = preg_match('/' . static::$VALID_START_CHAR_PATTERN . '/ui', $number, $matches, PREG_OFFSET_CAPTURE);
1541 2768
        if ($match > 0) {
1542 2768
            $number = substr($number, $matches[0][1]);
1543
            // Remove trailing non-alpha non-numerical characters.
1544 2768
            $trailingCharsMatcher = new Matcher(static::$UNWANTED_END_CHAR_PATTERN, $number);
1545 2768
            if ($trailingCharsMatcher->find() && $trailingCharsMatcher->start() > 0) {
1546 2
                $number = substr($number, 0, $trailingCharsMatcher->start());
1547 2
            }
1548
1549
            // Check for extra numbers at the end.
1550 2768
            $match = preg_match('%' . static::$SECOND_NUMBER_START_PATTERN . '%', $number, $matches, PREG_OFFSET_CAPTURE);
1551 2768
            if ($match > 0) {
1552 1
                $number = substr($number, 0, $matches[0][1]);
1553 1
            }
1554
1555 2768
            return $number;
1556
        } else {
1557 4
            return "";
1558
        }
1559
    }
1560
1561
    /**
1562
     * Checks to see that the region code used is valid, or if it is not valid, that the number to
1563
     * parse starts with a + symbol so that we can attempt to infer the region from the number.
1564
     * Returns false if it cannot use the region provided and the region cannot be inferred.
1565
     * @param string $numberToParse
1566
     * @param string $defaultRegion
1567
     * @return bool
1568
     */
1569 2729
    protected function checkRegionForParsing($numberToParse, $defaultRegion)
1570
    {
1571 2729
        if (!$this->isValidRegionCode($defaultRegion)) {
1572
            // If the number is null or empty, we can't infer the region.
1573 269
            $plusCharsPatternMatcher = new Matcher(static::$PLUS_CHARS_PATTERN, $numberToParse);
1574 269
            if ($numberToParse === null || mb_strlen($numberToParse) == 0 || !$plusCharsPatternMatcher->lookingAt()) {
1575 5
                return false;
1576
            }
1577 267
        }
1578 2729
        return true;
1579
    }
1580
1581
    /**
1582
     * Tries to extract a country calling code from a number. This method will return zero if no
1583
     * country calling code is considered to be present. Country calling codes are extracted in the
1584
     * following ways:
1585
     * <ul>
1586
     *  <li> by stripping the international dialing prefix of the region the person is dialing from,
1587
     *       if this is present in the number, and looking at the next digits
1588
     *  <li> by stripping the '+' sign if present and then looking at the next digits
1589
     *  <li> by comparing the start of the number and the country calling code of the default region.
1590
     *       If the number is not considered possible for the numbering plan of the default region
1591
     *       initially, but starts with the country calling code of this region, validation will be
1592
     *       reattempted after stripping this country calling code. If this number is considered a
1593
     *       possible number, then the first digits will be considered the country calling code and
1594
     *       removed as such.
1595
     * </ul>
1596
     * It will throw a NumberParseException if the number starts with a '+' but the country calling
1597
     * code supplied after this does not match that of any known region.
1598
     *
1599
     * @param string $number non-normalized telephone number that we wish to extract a country calling
1600
     *     code from - may begin with '+'
1601
     * @param PhoneMetadata $defaultRegionMetadata metadata about the region this number may be from
1602
     * @param string $nationalNumber a string buffer to store the national significant number in, in the case
1603
     *     that a country calling code was extracted. The number is appended to any existing contents.
1604
     *     If no country calling code was extracted, this will be left unchanged.
1605
     * @param bool $keepRawInput true if the country_code_source and preferred_carrier_code fields of
1606
     *     phoneNumber should be populated.
1607
     * @param PhoneNumber $phoneNumber the PhoneNumber object where the country_code and country_code_source need
1608
     *     to be populated. Note the country_code is always populated, whereas country_code_source is
1609
     *     only populated when keepCountryCodeSource is true.
1610
     * @return int the country calling code extracted or 0 if none could be extracted
1611
     * @throws NumberParseException
1612
     */
1613 2730
    public function maybeExtractCountryCode(
1614
        $number,
1615
        PhoneMetadata $defaultRegionMetadata = null,
1616
        &$nationalNumber,
1617
        $keepRawInput,
1618
        PhoneNumber $phoneNumber
1619
    ) {
1620 2730
        if (mb_strlen($number) == 0) {
1621
            return 0;
1622
        }
1623 2730
        $fullNumber = $number;
1624
        // Set the default prefix to be something that will never match.
1625 2730
        $possibleCountryIddPrefix = "NonMatch";
1626 2730
        if ($defaultRegionMetadata !== null) {
1627 2713
            $possibleCountryIddPrefix = $defaultRegionMetadata->getInternationalPrefix();
1628 2713
        }
1629 2730
        $countryCodeSource = $this->maybeStripInternationalPrefixAndNormalize($fullNumber, $possibleCountryIddPrefix);
1630
1631 2730
        if ($keepRawInput) {
1632 4
            $phoneNumber->setCountryCodeSource($countryCodeSource);
1633 4
        }
1634 2730
        if ($countryCodeSource != CountryCodeSource::FROM_DEFAULT_COUNTRY) {
1635 285
            if (mb_strlen($fullNumber) <= static::MIN_LENGTH_FOR_NSN) {
1636 1
                throw new NumberParseException(
1637 1
                    NumberParseException::TOO_SHORT_AFTER_IDD,
1638
                    "Phone number had an IDD, but after this was not long enough to be a viable phone number."
1639 1
                );
1640
            }
1641 285
            $potentialCountryCode = $this->extractCountryCode($fullNumber, $nationalNumber);
1642
1643 285
            if ($potentialCountryCode != 0) {
1644 285
                $phoneNumber->setCountryCode($potentialCountryCode);
1645 285
                return $potentialCountryCode;
1646
            }
1647
1648
            // If this fails, they must be using a strange country calling code that we don't recognize,
1649
            // or that doesn't exist.
1650 3
            throw new NumberParseException(
1651 3
                NumberParseException::INVALID_COUNTRY_CODE,
1652
                "Country calling code supplied was not recognised."
1653 3
            );
1654 2706
        } elseif ($defaultRegionMetadata !== null) {
1655
            // Check to see if the number starts with the country calling code for the default region. If
1656
            // so, we remove the country calling code, and do some checks on the validity of the number
1657
            // before and after.
1658 2706
            $defaultCountryCode = $defaultRegionMetadata->getCountryCode();
1659 2706
            $defaultCountryCodeString = (string)$defaultCountryCode;
1660 2706
            $normalizedNumber = (string)$fullNumber;
1661 2706
            if (strpos($normalizedNumber, $defaultCountryCodeString) === 0) {
1662 58
                $potentialNationalNumber = substr($normalizedNumber, mb_strlen($defaultCountryCodeString));
1663 58
                $generalDesc = $defaultRegionMetadata->getGeneralDesc();
1664 58
                $validNumberPattern = $generalDesc->getNationalNumberPattern();
1665
                // Don't need the carrier code.
1666 58
                $carriercode = null;
1667 58
                $this->maybeStripNationalPrefixAndCarrierCode(
1668 58
                    $potentialNationalNumber,
1669 58
                    $defaultRegionMetadata,
1670
                    $carriercode
1671 58
                );
1672 58
                $possibleNumberPattern = $generalDesc->getPossibleNumberPattern();
1673
                // If the number was not valid before but is valid now, or if it was too long before, we
1674
                // consider the number with the country calling code stripped to be a better result and
1675
                // keep that instead.
1676 58
                if ((preg_match('/^(' . $validNumberPattern . ')$/x', $fullNumber) == 0 &&
1677 22
                        preg_match('/^(' . $validNumberPattern . ')$/x', $potentialNationalNumber) > 0) ||
1678 49
                    $this->testNumberLengthAgainstPattern($possibleNumberPattern, (string)$fullNumber)
1679
                    == ValidationResult::TOO_LONG
1680 58
                ) {
1681 12
                    $nationalNumber .= $potentialNationalNumber;
1682 12
                    if ($keepRawInput) {
1683 3
                        $phoneNumber->setCountryCodeSource(CountryCodeSource::FROM_NUMBER_WITHOUT_PLUS_SIGN);
1684 3
                    }
1685 12
                    $phoneNumber->setCountryCode($defaultCountryCode);
1686 12
                    return $defaultCountryCode;
1687
                }
1688 48
            }
1689 2700
        }
1690
        // No country calling code present.
1691 2700
        $phoneNumber->setCountryCode(0);
1692 2700
        return 0;
1693
    }
1694
1695
    /**
1696
     * Strips any international prefix (such as +, 00, 011) present in the number provided, normalizes
1697
     * the resulting number, and indicates if an international prefix was present.
1698
     *
1699
     * @param string $number the non-normalized telephone number that we wish to strip any international
1700
     *     dialing prefix from.
1701
     * @param string $possibleIddPrefix string the international direct dialing prefix from the region we
1702
     *     think this number may be dialed in
1703
     * @return int the corresponding CountryCodeSource if an international dialing prefix could be
1704
     *     removed from the number, otherwise CountryCodeSource.FROM_DEFAULT_COUNTRY if the number did
1705
     *     not seem to be in international format.
1706
     */
1707 2731
    public function maybeStripInternationalPrefixAndNormalize(&$number, $possibleIddPrefix)
1708
    {
1709 2731
        if (mb_strlen($number) == 0) {
1710
            return CountryCodeSource::FROM_DEFAULT_COUNTRY;
1711
        }
1712 2731
        $matches = array();
1713
        // Check to see if the number begins with one or more plus signs.
1714 2731
        $match = preg_match('/^' . static::$PLUS_CHARS_PATTERN . '/' . static::REGEX_FLAGS, $number, $matches, PREG_OFFSET_CAPTURE);
1715 2731
        if ($match > 0) {
1716 284
            $number = mb_substr($number, $matches[0][1] + mb_strlen($matches[0][0]));
1717
            // Can now normalize the rest of the number since we've consumed the "+" sign at the start.
1718 284
            $number = $this->normalize($number);
1719 284
            return CountryCodeSource::FROM_NUMBER_WITH_PLUS_SIGN;
1720
        }
1721
        // Attempt to parse the first digits as an international prefix.
1722 2708
        $iddPattern = $possibleIddPrefix;
1723 2708
        $number = $this->normalize($number);
1724 2708
        return $this->parsePrefixAsIdd($iddPattern, $number)
1725 2708
            ? CountryCodeSource::FROM_NUMBER_WITH_IDD
1726 2708
            : CountryCodeSource::FROM_DEFAULT_COUNTRY;
1727
    }
1728
1729
    /**
1730
     * Normalizes a string of characters representing a phone number. This performs
1731
     * the following conversions:
1732
     *   Punctuation is stripped.
1733
     *   For ALPHA/VANITY numbers:
1734
     *   Letters are converted to their numeric representation on a telephone
1735
     *       keypad. The keypad used here is the one defined in ITU Recommendation
1736
     *       E.161. This is only done if there are 3 or more letters in the number,
1737
     *       to lessen the risk that such letters are typos.
1738
     *   For other numbers:
1739
     *   Wide-ascii digits are converted to normal ASCII (European) digits.
1740
     *   Arabic-Indic numerals are converted to European numerals.
1741
     *   Spurious alpha characters are stripped.
1742
     *
1743
     * @param string $number a string of characters representing a phone number.
1744
     * @return string the normalized string version of the phone number.
1745
     */
1746 2734
    public static function normalize(&$number)
1747
    {
1748 2734
        $m = new Matcher(static::VALID_ALPHA_PHONE_PATTERN, $number);
1749 2734
        if ($m->matches()) {
1750 6
            return static::normalizeHelper($number, static::$ALPHA_PHONE_MAPPINGS, true);
1751
        } else {
1752 2733
            return static::normalizeDigitsOnly($number);
1753
        }
1754
    }
1755
1756
    /**
1757
     * Normalizes a string of characters representing a phone number. This converts wide-ascii and
1758
     * arabic-indic numerals to European numerals, and strips punctuation and alpha characters.
1759
     *
1760
     * @param $number string  a string of characters representing a phone number
1761
     * @return string the normalized string version of the phone number
1762
     */
1763 2767
    public static function normalizeDigitsOnly($number)
1764
    {
1765 2767
        return static::normalizeDigits($number, false /* strip non-digits */);
1766
    }
1767
1768
    /**
1769
     * @param string $number
1770
     * @param bool $keepNonDigits
1771
     * @return string
1772
     */
1773 2767
    public static function normalizeDigits($number, $keepNonDigits)
1774
    {
1775 2767
        $normalizedDigits = "";
1776 2767
        $numberAsArray = preg_split('/(?<!^)(?!$)/u', $number);
1777 2767
        foreach ($numberAsArray as $character) {
1778 2767
            if (is_numeric($character)) {
1779 2767
                $normalizedDigits .= $character;
1780 2767
            } elseif ($keepNonDigits) {
1781
                $normalizedDigits .= $character;
1782
            }
1783
            // If neither of the above are true, we remove this character.
1784
1785
            // Check if we are in the unicode number range
1786 2767
            if (array_key_exists($character, static::$numericCharacters)) {
1787 2
                $normalizedDigits .= static::$numericCharacters[$character];
1788 2
            }
1789 2767
        }
1790 2767
        return $normalizedDigits;
1791
    }
1792
1793
    /**
1794
     * Strips the IDD from the start of the number if present. Helper function used by
1795
     * maybeStripInternationalPrefixAndNormalize.
1796
     * @param string $iddPattern
1797
     * @param string $number
1798
     * @return bool
1799
     */
1800 2708
    protected function parsePrefixAsIdd($iddPattern, &$number)
1801
    {
1802 2708
        $m = new Matcher($iddPattern, $number);
1803 2708
        if ($m->lookingAt()) {
1804 12
            $matchEnd = $m->end();
1805
            // Only strip this if the first digit after the match is not a 0, since country calling codes
1806
            // cannot begin with 0.
1807 12
            $digitMatcher = new Matcher(static::$CAPTURING_DIGIT_PATTERN, substr($number, $matchEnd));
1808 12
            if ($digitMatcher->find()) {
1809 12
                $normalizedGroup = $this->normalizeDigitsOnly($digitMatcher->group(1));
1810 12
                if ($normalizedGroup == "0") {
1811 4
                    return false;
1812
                }
1813 10
            }
1814 10
            $number = substr($number, $matchEnd);
1815 10
            return true;
1816
        }
1817 2705
        return false;
1818
    }
1819
1820
    /**
1821
     * Extracts country calling code from fullNumber, returns it and places the remaining number in  nationalNumber.
1822
     * It assumes that the leading plus sign or IDD has already been removed.
1823
     * Returns 0 if fullNumber doesn't start with a valid country calling code, and leaves nationalNumber unmodified.
1824
     * @param string $fullNumber
1825
     * @param string $nationalNumber
1826
     * @return int
1827
     */
1828 285
    protected function extractCountryCode(&$fullNumber, &$nationalNumber)
1829
    {
1830 285
        if ((mb_strlen($fullNumber) == 0) || ($fullNumber[0] == '0')) {
1831
            // Country codes do not begin with a '0'.
1832 2
            return 0;
1833
        }
1834 285
        $numberLength = mb_strlen($fullNumber);
1835 285
        for ($i = 1; $i <= static::MAX_LENGTH_COUNTRY_CODE && $i <= $numberLength; $i++) {
1836 285
            $potentialCountryCode = (int)substr($fullNumber, 0, $i);
1837 285
            if (isset($this->countryCallingCodeToRegionCodeMap[$potentialCountryCode])) {
1838 285
                $nationalNumber .= substr($fullNumber, $i);
1839 285
                return $potentialCountryCode;
1840
            }
1841 256
        }
1842 2
        return 0;
1843
    }
1844
1845
    /**
1846
     * Strips any national prefix (such as 0, 1) present in the number provided.
1847
     *
1848
     * @param string $number the normalized telephone number that we wish to strip any national
1849
     *     dialing prefix from
1850
     * @param PhoneMetadata $metadata the metadata for the region that we think this number is from
1851
     * @param string $carrierCode a place to insert the carrier code if one is extracted
1852
     * @return bool true if a national prefix or carrier code (or both) could be extracted.
1853
     */
1854 2730
    public function maybeStripNationalPrefixAndCarrierCode(&$number, PhoneMetadata $metadata, &$carrierCode)
1855
    {
1856 2730
        $numberLength = mb_strlen($number);
1857 2730
        $possibleNationalPrefix = $metadata->getNationalPrefixForParsing();
1858 2730
        if ($numberLength == 0 || $possibleNationalPrefix === null || mb_strlen($possibleNationalPrefix) == 0) {
1859
            // Early return for numbers of zero length.
1860 974
            return false;
1861
        }
1862
1863
        // Attempt to parse the first digits as a national prefix.
1864 1765
        $prefixMatcher = new Matcher($possibleNationalPrefix, $number);
1865 1765
        if ($prefixMatcher->lookingAt()) {
1866 70
            $nationalNumberRule = $metadata->getGeneralDesc()->getNationalNumberPattern();
1867
            // Check if the original number is viable.
1868 70
            $nationalNumberRuleMatcher = new Matcher($nationalNumberRule, $number);
1869 70
            $isViableOriginalNumber = $nationalNumberRuleMatcher->matches();
1870
            // $prefixMatcher->group($numOfGroups) === null implies nothing was captured by the capturing
1871
            // groups in $possibleNationalPrefix; therefore, no transformation is necessary, and we just
1872
            // remove the national prefix
1873 70
            $numOfGroups = $prefixMatcher->groupCount();
1874 70
            $transformRule = $metadata->getNationalPrefixTransformRule();
1875
            if ($transformRule === null
1876 70
                || mb_strlen($transformRule) == 0
1877 24
                || $prefixMatcher->group($numOfGroups - 1) === null
1878 70
            ) {
1879
                // If the original number was viable, and the resultant number is not, we return.
1880 65
                $matcher = new Matcher($nationalNumberRule, substr($number, $prefixMatcher->end()));
1881 65
                if ($isViableOriginalNumber && !$matcher->matches()) {
1882 14
                    return false;
1883
                }
1884 54
                if ($carrierCode !== null && $numOfGroups > 0 && $prefixMatcher->group($numOfGroups) !== null) {
1885 2
                    $carrierCode .= $prefixMatcher->group(1);
1886 2
                }
1887
1888 54
                $number = substr($number, $prefixMatcher->end());
1889 54
                return true;
1890
            } else {
1891
                // Check that the resultant number is still viable. If not, return. Check this by copying
1892
                // the string and making the transformation on the copy first.
1893 9
                $transformedNumber = $number;
1894 9
                $transformedNumber = substr_replace(
1895 9
                    $transformedNumber,
1896 9
                    $prefixMatcher->replaceFirst($transformRule),
1897 9
                    0,
1898
                    $numberLength
1899 9
                );
1900 9
                $matcher = new Matcher($nationalNumberRule, $transformedNumber);
1901 9
                if ($isViableOriginalNumber && !$matcher->matches()) {
1902
                    return false;
1903
                }
1904 9
                if ($carrierCode !== null && $numOfGroups > 1) {
1905
                    $carrierCode .= $prefixMatcher->group(1);
1906
                }
1907 9
                $number = substr_replace($number, $transformedNumber, 0, mb_strlen($number));
1908 9
                return true;
1909
            }
1910
        }
1911 1711
        return false;
1912
    }
1913
1914
    /**
1915
     * Helper method to check a number against a particular pattern and determine whether it matches,
1916
     * or is too short or too long. Currently, if a number pattern suggests that numbers of length 7
1917
     * and 10 are possible, and a number in between these possible lengths is entered, such as of
1918
     * length 8, this will return TOO_LONG.
1919
     * @param string $numberPattern
1920
     * @param string $number
1921
     * @return int ValidationResult
1922
     */
1923 2732
    protected function testNumberLengthAgainstPattern($numberPattern, $number)
1924
    {
1925 2732
        $numberMatcher = new Matcher($numberPattern, $number);
1926 2732
        if ($numberMatcher->matches()) {
1927 2045
            return ValidationResult::IS_POSSIBLE;
1928
        }
1929 700
        if ($numberMatcher->lookingAt()) {
1930 46
            return ValidationResult::TOO_LONG;
1931
        } else {
1932 661
            return ValidationResult::TOO_SHORT;
1933
        }
1934
    }
1935
1936
    /**
1937
     * Returns a list with the region codes that match the specific country calling code. For
1938
     * non-geographical country calling codes, the region code 001 is returned. Also, in the case
1939
     * of no region code being found, an empty list is returned.
1940
     * @param int $countryCallingCode
1941
     * @return array
1942
     */
1943 9
    public function getRegionCodesForCountryCode($countryCallingCode)
1944
    {
1945 9
        $regionCodes = isset($this->countryCallingCodeToRegionCodeMap[$countryCallingCode]) ? $this->countryCallingCodeToRegionCodeMap[$countryCallingCode] : null;
1946 9
        return $regionCodes === null ? array() : $regionCodes;
1947
    }
1948
1949
    /**
1950
     * Returns the country calling code for a specific region. For example, this would be 1 for the
1951
     * United States, and 64 for New Zealand. Assumes the region is already valid.
1952
     *
1953
     * @param string $regionCode the region that we want to get the country calling code for
1954
     * @return int the country calling code for the region denoted by regionCode
1955
     */
1956 2
    public function getCountryCodeForRegion($regionCode)
1957
    {
1958 2
        if (!$this->isValidRegionCode($regionCode)) {
1959 1
            return 0;
1960
        }
1961 2
        return $this->getCountryCodeForValidRegion($regionCode);
1962
    }
1963
1964
    /**
1965
     * Returns the country calling code for a specific region. For example, this would be 1 for the
1966
     * United States, and 64 for New Zealand. Assumes the region is already valid.
1967
     *
1968
     * @param string $regionCode the region that we want to get the country calling code for
1969
     * @return int the country calling code for the region denoted by regionCode
1970
     * @throws \InvalidArgumentException if the region is invalid
1971
     */
1972 1816
    protected function getCountryCodeForValidRegion($regionCode)
1973
    {
1974 1816
        $metadata = $this->getMetadataForRegion($regionCode);
1975 1816
        if ($metadata === null) {
1976
            throw new \InvalidArgumentException("Invalid region code: " . $regionCode);
1977
        }
1978 1816
        return $metadata->getCountryCode();
1979
    }
1980
1981
    /**
1982
     * Returns a number formatted in such a way that it can be dialed from a mobile phone in a
1983
     * specific region. If the number cannot be reached from the region (e.g. some countries block
1984
     * toll-free numbers from being called outside of the country), the method returns an empty
1985
     * string.
1986
     *
1987
     * @param PhoneNumber $number the phone number to be formatted
1988
     * @param string $regionCallingFrom the region where the call is being placed
1989
     * @param boolean $withFormatting whether the number should be returned with formatting symbols, such as
1990
     *     spaces and dashes.
1991
     * @return string the formatted phone number
1992
     */
1993 1
    public function formatNumberForMobileDialing(PhoneNumber $number, $regionCallingFrom, $withFormatting)
1994
    {
1995 1
        $countryCallingCode = $number->getCountryCode();
1996 1
        if (!$this->hasValidCountryCallingCode($countryCallingCode)) {
1997
            return $number->hasRawInput() ? $number->getRawInput() : "";
1998
        }
1999
2000 1
        $formattedNumber = "";
2001
        // Clear the extension, as that part cannot normally be dialed together with the main number.
2002 1
        $numberNoExt = new PhoneNumber();
2003 1
        $numberNoExt->mergeFrom($number)->clearExtension();
2004 1
        $regionCode = $this->getRegionCodeForCountryCode($countryCallingCode);
2005 1
        $numberType = $this->getNumberType($numberNoExt);
2006 1
        $isValidNumber = ($numberType !== PhoneNumberType::UNKNOWN);
2007 1
        if ($regionCallingFrom == $regionCode) {
2008 1
            $isFixedLineOrMobile = ($numberType == PhoneNumberType::FIXED_LINE) || ($numberType == PhoneNumberType::MOBILE) || ($numberType == PhoneNumberType::FIXED_LINE_OR_MOBILE);
2009
            // Carrier codes may be needed in some countries. We handle this here.
2010 1
            if ($regionCode == "CO" && $numberType == PhoneNumberType::FIXED_LINE) {
2011
                $formattedNumber = $this->formatNationalNumberWithCarrierCode(
2012
                    $numberNoExt,
2013
                    static::COLOMBIA_MOBILE_TO_FIXED_LINE_PREFIX
2014
                );
2015 1
            } elseif ($regionCode == "BR" && $isFixedLineOrMobile) {
2016
                // Brazilian fixed line and mobile numbers need to be dialed with a carrier code when
2017
                // called within Brazil. Without that, most of the carriers won't connect the call.
2018
                // Because of that, we return an empty string here.
2019
                $formattedNumber = $numberNoExt->hasPreferredDomesticCarrierCode(
2020
                ) ? $this->formatNationalNumberWithCarrierCode($numberNoExt, "") : "";
2021 1
            } elseif ($isValidNumber && $regionCode == "HU") {
2022
                // The national format for HU numbers doesn't contain the national prefix, because that is
2023
                // how numbers are normally written down. However, the national prefix is obligatory when
2024
                // dialing from a mobile phone, except for short numbers. As a result, we add it back here
2025
                // if it is a valid regular length phone number.
2026 1
                $formattedNumber = $this->getNddPrefixForRegion(
2027 1
                        $regionCode,
2028
                        true /* strip non-digits */
2029 1
                    ) . " " . $this->format($numberNoExt, PhoneNumberFormat::NATIONAL);
2030 1
            } elseif ($countryCallingCode === static::NANPA_COUNTRY_CODE) {
2031
                // For NANPA countries, we output international format for numbers that can be dialed
2032
                // internationally, since that always works, except for numbers which might potentially be
2033
                // short numbers, which are always dialled in national format.
2034 1
                $regionMetadata = $this->getMetadataForRegion($regionCallingFrom);
2035 1
                if ($this->canBeInternationallyDialled($numberNoExt) &&
2036 1
                    !$this->isShorterThanPossibleNormalNumber(
2037 1
                        $regionMetadata,
0 ignored issues
show
Bug introduced by
It seems like $regionMetadata defined by $this->getMetadataForRegion($regionCallingFrom) on line 2034 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...
2038 1
                        $this->getNationalSignificantNumber($numberNoExt)
2039 1
                    )
2040 1
                ) {
2041 1
                    $formattedNumber = $this->format($numberNoExt, PhoneNumberFormat::INTERNATIONAL);
2042 1
                } else {
2043 1
                    $formattedNumber = $this->format($numberNoExt, PhoneNumberFormat::NATIONAL);
2044
                }
2045 1
            } else {
2046
                // For non-geographical countries, Mexican and Chilean fixed line and mobile numbers, we
2047
                // output international format for numbers that can be dialed internationally as that always
2048
                // works.
2049 1
                if (($regionCode == static::REGION_CODE_FOR_NON_GEO_ENTITY ||
2050
                        // MX fixed line and mobile numbers should always be formatted in international format,
2051
                        // even when dialed within MX. For national format to work, a carrier code needs to be
2052
                        // used, and the correct carrier code depends on if the caller and callee are from the
2053
                        // same local area. It is trickier to get that to work correctly than using
2054
                        // international format, which is tested to work fine on all carriers.
2055
                        // CL fixed line numbers need the national prefix when dialing in the national format,
2056
                        // but don't have it when used for display. The reverse is true for mobile numbers.
2057
                        // As a result, we output them in the international format to make it work.
2058 1
                        (($regionCode == "MX" || $regionCode == "CL") && $isFixedLineOrMobile)) && $this->canBeInternationallyDialled(
2059
                        $numberNoExt
2060 1
                    )
2061 1
                ) {
2062 1
                    $formattedNumber = $this->format($numberNoExt, PhoneNumberFormat::INTERNATIONAL);
2063 1
                } else {
2064 1
                    $formattedNumber = $this->format($numberNoExt, PhoneNumberFormat::NATIONAL);
2065
                }
2066
            }
2067 1
        } elseif ($isValidNumber && $this->canBeInternationallyDialled($numberNoExt)) {
2068
            // We assume that short numbers are not diallable from outside their region, so if a number
2069
            // is not a valid regular length phone number, we treat it as if it cannot be internationally
2070
            // dialled.
2071
            return $withFormatting ?
2072 1
                $this->format($numberNoExt, PhoneNumberFormat::INTERNATIONAL) :
2073 1
                $this->format($numberNoExt, PhoneNumberFormat::E164);
2074
        }
2075 1
        return $withFormatting ? $formattedNumber : $this->normalizeDiallableCharsOnly($formattedNumber);
2076
    }
2077
2078
    /**
2079
     * Formats a phone number in national format for dialing using the carrier as specified in the
2080
     * {@code carrierCode}. The {@code carrierCode} will always be used regardless of whether the
2081
     * phone number already has a preferred domestic carrier code stored. If {@code carrierCode}
2082
     * contains an empty string, returns the number in national format without any carrier code.
2083
     *
2084
     * @param PhoneNumber $number the phone number to be formatted
2085
     * @param string $carrierCode the carrier selection code to be used
2086
     * @return string the formatted phone number in national format for dialing using the carrier as
2087
     * specified in the {@code carrierCode}
2088
     */
2089 2
    public function formatNationalNumberWithCarrierCode(PhoneNumber $number, $carrierCode)
2090
    {
2091 2
        $countryCallingCode = $number->getCountryCode();
2092 2
        $nationalSignificantNumber = $this->getNationalSignificantNumber($number);
2093 2
        if (!$this->hasValidCountryCallingCode($countryCallingCode)) {
2094 1
            return $nationalSignificantNumber;
2095
        }
2096
2097
        // Note getRegionCodeForCountryCode() is used because formatting information for regions which
2098
        // share a country calling code is contained by only one region for performance reasons. For
2099
        // example, for NANPA regions it will be contained in the metadata for US.
2100 2
        $regionCode = $this->getRegionCodeForCountryCode($countryCallingCode);
2101
        // Metadata cannot be null because the country calling code is valid.
2102 2
        $metadata = $this->getMetadataForRegionOrCallingCode($countryCallingCode, $regionCode);
2103
2104 2
        $formattedNumber = $this->formatNsn(
2105 2
            $nationalSignificantNumber,
2106 2
            $metadata,
0 ignored issues
show
Bug introduced by
It seems like $metadata defined by $this->getMetadataForReg...llingCode, $regionCode) on line 2102 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...
2107 2
            PhoneNumberFormat::NATIONAL,
2108
            $carrierCode
2109 2
        );
2110 2
        $this->maybeAppendFormattedExtension($number, $metadata, PhoneNumberFormat::NATIONAL, $formattedNumber);
2111 2
        $this->prefixNumberWithCountryCallingCode(
2112 2
            $countryCallingCode,
2113 2
            PhoneNumberFormat::NATIONAL,
2114
            $formattedNumber
2115 2
        );
2116 2
        return $formattedNumber;
2117
    }
2118
2119
    /**
2120
     * Formats a phone number in national format for dialing using the carrier as specified in the
2121
     * preferredDomesticCarrierCode field of the PhoneNumber object passed in. If that is missing,
2122
     * use the {@code fallbackCarrierCode} passed in instead. If there is no
2123
     * {@code preferredDomesticCarrierCode}, and the {@code fallbackCarrierCode} contains an empty
2124
     * string, return the number in national format without any carrier code.
2125
     *
2126
     * <p>Use {@link #formatNationalNumberWithCarrierCode} instead if the carrier code passed in
2127
     * should take precedence over the number's {@code preferredDomesticCarrierCode} when formatting.
2128
     *
2129
     * @param PhoneNumber $number the phone number to be formatted
2130
     * @param string $fallbackCarrierCode the carrier selection code to be used, if none is found in the
2131
     *     phone number itself
2132
     * @return string the formatted phone number in national format for dialing using the number's
2133
     *     {@code preferredDomesticCarrierCode}, or the {@code fallbackCarrierCode} passed in if
2134
     *     none is found
2135
     */
2136 1
    public function formatNationalNumberWithPreferredCarrierCode(PhoneNumber $number, $fallbackCarrierCode)
2137
    {
2138 1
        return $this->formatNationalNumberWithCarrierCode(
2139 1
            $number,
2140 1
            $number->hasPreferredDomesticCarrierCode()
2141 1
                ? $number->getPreferredDomesticCarrierCode()
2142 1
                : $fallbackCarrierCode
2143 1
        );
2144
    }
2145
2146
    /**
2147
     * Returns true if the number can be dialled from outside the region, or unknown. If the number
2148
     * can only be dialled from within the region, returns false. Does not check the number is a valid
2149
     * number.
2150
     * TODO: Make this method public when we have enough metadata to make it worthwhile.
2151
     *
2152
     * @param PhoneNumber $number the phone-number for which we want to know whether it is diallable from outside the region
2153
     * @return bool
2154
     */
2155 31
    public function canBeInternationallyDialled(PhoneNumber $number)
2156
    {
2157 31
        $metadata = $this->getMetadataForRegion($this->getRegionCodeForNumber($number));
2158 31
        if ($metadata === null) {
2159
            // Note numbers belonging to non-geographical entities (e.g. +800 numbers) are always
2160
            // internationally diallable, and will be caught here.
2161 2
            return true;
2162
        }
2163 31
        $nationalSignificantNumber = $this->getNationalSignificantNumber($number);
2164 31
        return !$this->isNumberMatchingDesc($nationalSignificantNumber, $metadata->getNoInternationalDialling());
2165
    }
2166
2167
    /**
2168
     * Normalizes a string of characters representing a phone number. This strips all characters which
2169
     * are not diallable on a mobile phone keypad (including all non-ASCII digits).
2170
     *
2171
     * @param string $number a string of characters representing a phone number
2172
     * @return string the normalized string version of the phone number
2173
     */
2174 3
    public static function normalizeDiallableCharsOnly($number)
2175
    {
2176 3
        return static::normalizeHelper($number, static::$DIALLABLE_CHAR_MAPPINGS, true /* remove non matches */);
2177
    }
2178
2179
    /**
2180
     * Formats a phone number for out-of-country dialing purposes.
2181
     *
2182
     * Note that in this version, if the number was entered originally using alpha characters and
2183
     * this version of the number is stored in raw_input, this representation of the number will be
2184
     * used rather than the digit representation. Grouping information, as specified by characters
2185
     * such as "-" and " ", will be retained.
2186
     *
2187
     * <p><b>Caveats:</b></p>
2188
     * <ul>
2189
     *  <li> This will not produce good results if the country calling code is both present in the raw
2190
     *       input _and_ is the start of the national number. This is not a problem in the regions
2191
     *       which typically use alpha numbers.
2192
     *  <li> This will also not produce good results if the raw input has any grouping information
2193
     *       within the first three digits of the national number, and if the function needs to strip
2194
     *       preceding digits/words in the raw input before these digits. Normally people group the
2195
     *       first three digits together so this is not a huge problem - and will be fixed if it
2196
     *       proves to be so.
2197
     * </ul>
2198
     *
2199
     * @param PhoneNumber $number the phone number that needs to be formatted
2200
     * @param String $regionCallingFrom the region where the call is being placed
2201
     * @return String the formatted phone number
2202
     */
2203 1
    public function formatOutOfCountryKeepingAlphaChars(PhoneNumber $number, $regionCallingFrom)
2204
    {
2205 1
        $rawInput = $number->getRawInput();
2206
        // If there is no raw input, then we can't keep alpha characters because there aren't any.
2207
        // In this case, we return formatOutOfCountryCallingNumber.
2208 1
        if (mb_strlen($rawInput) == 0) {
2209 1
            return $this->formatOutOfCountryCallingNumber($number, $regionCallingFrom);
2210
        }
2211 1
        $countryCode = $number->getCountryCode();
2212 1
        if (!$this->hasValidCountryCallingCode($countryCode)) {
2213 1
            return $rawInput;
2214
        }
2215
        // Strip any prefix such as country calling code, IDD, that was present. We do this by comparing
2216
        // the number in raw_input with the parsed number.
2217
        // To do this, first we normalize punctuation. We retain number grouping symbols such as " "
2218
        // only.
2219 1
        $rawInput = $this->normalizeHelper($rawInput, static::$ALL_PLUS_NUMBER_GROUPING_SYMBOLS, true);
2220
        // Now we trim everything before the first three digits in the parsed number. We choose three
2221
        // because all valid alpha numbers have 3 digits at the start - if it does not, then we don't
2222
        // trim anything at all. Similarly, if the national number was less than three digits, we don't
2223
        // trim anything at all.
2224 1
        $nationalNumber = $this->getNationalSignificantNumber($number);
2225 1
        if (mb_strlen($nationalNumber) > 3) {
2226 1
            $firstNationalNumberDigit = strpos($rawInput, substr($nationalNumber, 0, 3));
2227 1
            if ($firstNationalNumberDigit !== false) {
2228 1
                $rawInput = substr($rawInput, $firstNationalNumberDigit);
2229 1
            }
2230 1
        }
2231 1
        $metadataForRegionCallingFrom = $this->getMetadataForRegion($regionCallingFrom);
2232 1
        if ($countryCode == static::NANPA_COUNTRY_CODE) {
2233 1
            if ($this->isNANPACountry($regionCallingFrom)) {
2234 1
                return $countryCode . " " . $rawInput;
2235
            }
2236 1
        } elseif ($metadataForRegionCallingFrom !== null &&
2237 1
            $countryCode == $this->getCountryCodeForValidRegion($regionCallingFrom)
2238 1
        ) {
2239
            $formattingPattern =
2240 1
                $this->chooseFormattingPatternForNumber(
2241 1
                    $metadataForRegionCallingFrom->numberFormats(),
2242
                    $nationalNumber
2243 1
                );
2244 1
            if ($formattingPattern === null) {
2245
                // If no pattern above is matched, we format the original input.
2246 1
                return $rawInput;
2247
            }
2248 1
            $newFormat = new NumberFormat();
2249 1
            $newFormat->mergeFrom($formattingPattern);
2250
            // The first group is the first group of digits that the user wrote together.
2251 1
            $newFormat->setPattern("(\\d+)(.*)");
2252
            // Here we just concatenate them back together after the national prefix has been fixed.
2253 1
            $newFormat->setFormat("$1$2");
2254
            // Now we format using this pattern instead of the default pattern, but with the national
2255
            // prefix prefixed if necessary.
2256
            // This will not work in the cases where the pattern (and not the leading digits) decide
2257
            // whether a national prefix needs to be used, since we have overridden the pattern to match
2258
            // anything, but that is not the case in the metadata to date.
2259 1
            return $this->formatNsnUsingPattern($rawInput, $newFormat, PhoneNumberFormat::NATIONAL);
2260
        }
2261 1
        $internationalPrefixForFormatting = "";
2262
        // If an unsupported region-calling-from is entered, or a country with multiple international
2263
        // prefixes, the international format of the number is returned, unless there is a preferred
2264
        // international prefix.
2265 1
        if ($metadataForRegionCallingFrom !== null) {
2266 1
            $internationalPrefix = $metadataForRegionCallingFrom->getInternationalPrefix();
2267 1
            $uniqueInternationalPrefixMatcher = new Matcher(static::UNIQUE_INTERNATIONAL_PREFIX, $internationalPrefix);
2268
            $internationalPrefixForFormatting =
2269 1
                $uniqueInternationalPrefixMatcher->matches()
2270 1
                    ? $internationalPrefix
2271 1
                    : $metadataForRegionCallingFrom->getPreferredInternationalPrefix();
2272 1
        }
2273 1
        $formattedNumber = $rawInput;
2274 1
        $regionCode = $this->getRegionCodeForCountryCode($countryCode);
2275
        // Metadata cannot be null because the country calling code is valid.
2276 1
        $metadataForRegion = $this->getMetadataForRegionOrCallingCode($countryCode, $regionCode);
2277 1
        $this->maybeAppendFormattedExtension(
2278 1
            $number,
2279 1
            $metadataForRegion,
2280 1
            PhoneNumberFormat::INTERNATIONAL,
2281
            $formattedNumber
2282 1
        );
2283 1
        if (mb_strlen($internationalPrefixForFormatting) > 0) {
2284 1
            $formattedNumber = $internationalPrefixForFormatting . " " . $countryCode . " " . $formattedNumber;
2285 1
        } else {
2286
            // Invalid region entered as country-calling-from (so no metadata was found for it) or the
2287
            // region chosen has multiple international dialling prefixes.
2288 1
            $this->prefixNumberWithCountryCallingCode(
2289 1
                $countryCode,
2290 1
                PhoneNumberFormat::INTERNATIONAL,
2291
                $formattedNumber
2292 1
            );
2293
        }
2294 1
        return $formattedNumber;
2295
    }
2296
2297
    /**
2298
     * Formats a phone number for out-of-country dialing purposes. If no regionCallingFrom is
2299
     * supplied, we format the number in its INTERNATIONAL format. If the country calling code is the
2300
     * same as that of the region where the number is from, then NATIONAL formatting will be applied.
2301
     *
2302
     * <p>If the number itself has a country calling code of zero or an otherwise invalid country
2303
     * calling code, then we return the number with no formatting applied.
2304
     *
2305
     * <p>Note this function takes care of the case for calling inside of NANPA and between Russia and
2306
     * Kazakhstan (who share the same country calling code). In those cases, no international prefix
2307
     * is used. For regions which have multiple international prefixes, the number in its
2308
     * INTERNATIONAL format will be returned instead.
2309
     *
2310
     * @param PhoneNumber $number the phone number to be formatted
2311
     * @param string $regionCallingFrom the region where the call is being placed
2312
     * @return string  the formatted phone number
2313
     */
2314 8
    public function formatOutOfCountryCallingNumber(PhoneNumber $number, $regionCallingFrom)
2315
    {
2316 8
        if (!$this->isValidRegionCode($regionCallingFrom)) {
2317 1
            return $this->format($number, PhoneNumberFormat::INTERNATIONAL);
2318
        }
2319 7
        $countryCallingCode = $number->getCountryCode();
2320 7
        $nationalSignificantNumber = $this->getNationalSignificantNumber($number);
2321 7
        if (!$this->hasValidCountryCallingCode($countryCallingCode)) {
2322
            return $nationalSignificantNumber;
2323
        }
2324 7
        if ($countryCallingCode == static::NANPA_COUNTRY_CODE) {
2325 4
            if ($this->isNANPACountry($regionCallingFrom)) {
2326
                // For NANPA regions, return the national format for these regions but prefix it with the
2327
                // country calling code.
2328 1
                return $countryCallingCode . " " . $this->format($number, PhoneNumberFormat::NATIONAL);
2329
            }
2330 7
        } elseif ($countryCallingCode == $this->getCountryCodeForValidRegion($regionCallingFrom)) {
2331
            // If regions share a country calling code, the country calling code need not be dialled.
2332
            // This also applies when dialling within a region, so this if clause covers both these cases.
2333
            // Technically this is the case for dialling from La Reunion to other overseas departments of
2334
            // France (French Guiana, Martinique, Guadeloupe), but not vice versa - so we don't cover this
2335
            // edge case for now and for those cases return the version including country calling code.
2336
            // Details here: http://www.petitfute.com/voyage/225-info-pratiques-reunion
2337 2
            return $this->format($number, PhoneNumberFormat::NATIONAL);
2338
        }
2339
        // Metadata cannot be null because we checked 'isValidRegionCode()' above.
2340 7
        $metadataForRegionCallingFrom = $this->getMetadataForRegion($regionCallingFrom);
2341
2342 7
        $internationalPrefix = $metadataForRegionCallingFrom->getInternationalPrefix();
2343
2344
        // For regions that have multiple international prefixes, the international format of the
2345
        // number is returned, unless there is a preferred international prefix.
2346 7
        $internationalPrefixForFormatting = "";
2347 7
        $uniqueInternationalPrefixMatcher = new Matcher(static::UNIQUE_INTERNATIONAL_PREFIX, $internationalPrefix);
2348
2349 7
        if ($uniqueInternationalPrefixMatcher->matches()) {
2350 6
            $internationalPrefixForFormatting = $internationalPrefix;
2351 7
        } elseif ($metadataForRegionCallingFrom->hasPreferredInternationalPrefix()) {
2352 3
            $internationalPrefixForFormatting = $metadataForRegionCallingFrom->getPreferredInternationalPrefix();
2353 3
        }
2354
2355 7
        $regionCode = $this->getRegionCodeForCountryCode($countryCallingCode);
2356
        // Metadata cannot be null because the country calling code is valid.
2357 7
        $metadataForRegion = $this->getMetadataForRegionOrCallingCode($countryCallingCode, $regionCode);
2358 7
        $formattedNationalNumber = $this->formatNsn(
2359 7
            $nationalSignificantNumber,
2360 7
            $metadataForRegion,
0 ignored issues
show
Bug introduced by
It seems like $metadataForRegion defined by $this->getMetadataForReg...llingCode, $regionCode) on line 2357 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...
2361
            PhoneNumberFormat::INTERNATIONAL
2362 7
        );
2363 7
        $formattedNumber = $formattedNationalNumber;
2364 7
        $this->maybeAppendFormattedExtension(
2365 7
            $number,
2366 7
            $metadataForRegion,
2367 7
            PhoneNumberFormat::INTERNATIONAL,
2368
            $formattedNumber
2369 7
        );
2370 7
        if (mb_strlen($internationalPrefixForFormatting) > 0) {
2371 7
            $formattedNumber = $internationalPrefixForFormatting . " " . $countryCallingCode . " " . $formattedNumber;
2372 7
        } else {
2373 1
            $this->prefixNumberWithCountryCallingCode(
2374 1
                $countryCallingCode,
2375 1
                PhoneNumberFormat::INTERNATIONAL,
2376
                $formattedNumber
2377 1
            );
2378
        }
2379 7
        return $formattedNumber;
2380
    }
2381
2382
    /**
2383
     * Checks if this is a region under the North American Numbering Plan Administration (NANPA).
2384
     * @param string $regionCode
2385
     * @return boolean true if regionCode is one of the regions under NANPA
2386
     */
2387 5
    public function isNANPACountry($regionCode)
2388
    {
2389 5
        return in_array($regionCode, $this->nanpaRegions);
2390
    }
2391
2392
    /**
2393
     * Formats a phone number using the original phone number format that the number is parsed from.
2394
     * The original format is embedded in the country_code_source field of the PhoneNumber object
2395
     * passed in. If such information is missing, the number will be formatted into the NATIONAL
2396
     * format by default. When the number contains a leading zero and this is unexpected for this
2397
     * country, or we don't have a formatting pattern for the number, the method returns the raw input
2398
     * when it is available.
2399
     *
2400
     * Note this method guarantees no digit will be inserted, removed or modified as a result of
2401
     * formatting.
2402
     *
2403
     * @param PhoneNumber $number the phone number that needs to be formatted in its original number format
2404
     * @param string $regionCallingFrom the region whose IDD needs to be prefixed if the original number
2405
     *     has one
2406
     * @return string the formatted phone number in its original number format
2407
     */
2408 1
    public function formatInOriginalFormat(PhoneNumber $number, $regionCallingFrom)
2409
    {
2410 1
        if ($number->hasRawInput() &&
2411 1
            ($this->hasUnexpectedItalianLeadingZero($number) || !$this->hasFormattingPatternForNumber($number))
2412 1
        ) {
2413
            // We check if we have the formatting pattern because without that, we might format the number
2414
            // as a group without national prefix.
2415 1
            return $number->getRawInput();
2416
        }
2417 1
        if (!$number->hasCountryCodeSource()) {
2418 1
            return $this->format($number, PhoneNumberFormat::NATIONAL);
2419
        }
2420 1
        switch ($number->getCountryCodeSource()) {
2421 1
            case CountryCodeSource::FROM_NUMBER_WITH_PLUS_SIGN:
2422 1
                $formattedNumber = $this->format($number, PhoneNumberFormat::INTERNATIONAL);
2423 1
                break;
2424 1
            case CountryCodeSource::FROM_NUMBER_WITH_IDD:
2425 1
                $formattedNumber = $this->formatOutOfCountryCallingNumber($number, $regionCallingFrom);
2426 1
                break;
2427 1
            case CountryCodeSource::FROM_NUMBER_WITHOUT_PLUS_SIGN:
2428 1
                $formattedNumber = substr($this->format($number, PhoneNumberFormat::INTERNATIONAL), 1);
2429 1
                break;
2430 1
            case CountryCodeSource::FROM_DEFAULT_COUNTRY:
2431
                // Fall-through to default case.
2432 1
            default:
0 ignored issues
show
Coding Style introduced by
The default body in a switch statement must start on the line following the statement.

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

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


switch ($expr) {
    default:

        doSomething(); //wrong
        break;
}

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

Loading history...
2433
2434 1
                $regionCode = $this->getRegionCodeForCountryCode($number->getCountryCode());
2435
                // We strip non-digits from the NDD here, and from the raw input later, so that we can
2436
                // compare them easily.
2437 1
                $nationalPrefix = $this->getNddPrefixForRegion($regionCode, true /* strip non-digits */);
2438 1
                $nationalFormat = $this->format($number, PhoneNumberFormat::NATIONAL);
2439 1
                if ($nationalPrefix === null || mb_strlen($nationalPrefix) == 0) {
2440
                    // If the region doesn't have a national prefix at all, we can safely return the national
2441
                    // format without worrying about a national prefix being added.
2442 1
                    $formattedNumber = $nationalFormat;
2443 1
                    break;
2444
                }
2445
                // Otherwise, we check if the original number was entered with a national prefix.
2446 1
                if ($this->rawInputContainsNationalPrefix(
2447 1
                    $number->getRawInput(),
2448 1
                    $nationalPrefix,
2449
                    $regionCode
2450 1
                )
2451 1
                ) {
2452
                    // If so, we can safely return the national format.
2453 1
                    $formattedNumber = $nationalFormat;
2454 1
                    break;
2455
                }
2456
                // Metadata cannot be null here because getNddPrefixForRegion() (above) returns null if
2457
                // there is no metadata for the region.
2458 1
                $metadata = $this->getMetadataForRegion($regionCode);
2459 1
                $nationalNumber = $this->getNationalSignificantNumber($number);
2460 1
                $formatRule = $this->chooseFormattingPatternForNumber($metadata->numberFormats(), $nationalNumber);
2461
                // The format rule could still be null here if the national number was 0 and there was no
2462
                // raw input (this should not be possible for numbers generated by the phonenumber library
2463
                // as they would also not have a country calling code and we would have exited earlier).
2464 1
                if ($formatRule === null) {
2465
                    $formattedNumber = $nationalFormat;
2466
                    break;
2467
                }
2468
                // When the format we apply to this number doesn't contain national prefix, we can just
2469
                // return the national format.
2470
                // TODO: Refactor the code below with the code in isNationalPrefixPresentIfRequired.
2471 1
                $candidateNationalPrefixRule = $formatRule->getNationalPrefixFormattingRule();
2472
                // We assume that the first-group symbol will never be _before_ the national prefix.
2473 1
                $indexOfFirstGroup = strpos($candidateNationalPrefixRule, '$1');
2474 1
                if ($indexOfFirstGroup <= 0) {
2475 1
                    $formattedNumber = $nationalFormat;
2476 1
                    break;
2477
                }
2478 1
                $candidateNationalPrefixRule = substr($candidateNationalPrefixRule, 0, $indexOfFirstGroup);
2479 1
                $candidateNationalPrefixRule = $this->normalizeDigitsOnly($candidateNationalPrefixRule);
2480 1
                if (mb_strlen($candidateNationalPrefixRule) == 0) {
2481
                    // National prefix not used when formatting this number.
2482
                    $formattedNumber = $nationalFormat;
2483
                    break;
2484
                }
2485
                // Otherwise, we need to remove the national prefix from our output.
2486 1
                $numFormatCopy = new NumberFormat();
2487 1
                $numFormatCopy->mergeFrom($formatRule);
2488 1
                $numFormatCopy->clearNationalPrefixFormattingRule();
2489 1
                $numberFormats = array();
2490 1
                $numberFormats[] = $numFormatCopy;
2491 1
                $formattedNumber = $this->formatByPattern($number, PhoneNumberFormat::NATIONAL, $numberFormats);
2492 1
                break;
2493 1
        }
2494 1
        $rawInput = $number->getRawInput();
2495
        // If no digit is inserted/removed/modified as a result of our formatting, we return the
2496
        // formatted phone number; otherwise we return the raw input the user entered.
2497 1
        if ($formattedNumber !== null && mb_strlen($rawInput) > 0) {
2498 1
            $normalizedFormattedNumber = $this->normalizeDiallableCharsOnly($formattedNumber);
2499 1
            $normalizedRawInput = $this->normalizeDiallableCharsOnly($rawInput);
2500 1
            if ($normalizedFormattedNumber != $normalizedRawInput) {
2501 1
                $formattedNumber = $rawInput;
2502 1
            }
2503 1
        }
2504 1
        return $formattedNumber;
2505
    }
2506
2507
    /**
2508
     * Returns true if a number is from a region whose national significant number couldn't contain a
2509
     * leading zero, but has the italian_leading_zero field set to true.
2510
     * @param PhoneNumber $number
2511
     * @return bool
2512
     */
2513 1
    protected function hasUnexpectedItalianLeadingZero(PhoneNumber $number)
2514
    {
2515 1
        return $number->isItalianLeadingZero() && !$this->isLeadingZeroPossible($number->getCountryCode());
2516
    }
2517
2518
    /**
2519
     * Checks whether the country calling code is from a region whose national significant number
2520
     * could contain a leading zero. An example of such a region is Italy. Returns false if no
2521
     * metadata for the country is found.
2522
     * @param int $countryCallingCode
2523
     * @return bool
2524
     */
2525 2
    public function isLeadingZeroPossible($countryCallingCode)
2526
    {
2527 2
        $mainMetadataForCallingCode = $this->getMetadataForRegionOrCallingCode(
2528 2
            $countryCallingCode,
2529 2
            $this->getRegionCodeForCountryCode($countryCallingCode)
2530 2
        );
2531 2
        if ($mainMetadataForCallingCode === null) {
2532 1
            return false;
2533
        }
2534 2
        return (bool)$mainMetadataForCallingCode->isLeadingZeroPossible();
2535
    }
2536
2537
    /**
2538
     * @param PhoneNumber $number
2539
     * @return bool
2540
     */
2541 1
    protected function hasFormattingPatternForNumber(PhoneNumber $number)
2542
    {
2543 1
        $countryCallingCode = $number->getCountryCode();
2544 1
        $phoneNumberRegion = $this->getRegionCodeForCountryCode($countryCallingCode);
2545 1
        $metadata = $this->getMetadataForRegionOrCallingCode($countryCallingCode, $phoneNumberRegion);
2546 1
        if ($metadata === null) {
2547
            return false;
2548
        }
2549 1
        $nationalNumber = $this->getNationalSignificantNumber($number);
2550 1
        $formatRule = $this->chooseFormattingPatternForNumber($metadata->numberFormats(), $nationalNumber);
2551 1
        return $formatRule !== null;
2552
    }
2553
2554
    /**
2555
     * Returns the national dialling prefix for a specific region. For example, this would be 1 for
2556
     * the United States, and 0 for New Zealand. Set stripNonDigits to true to strip symbols like "~"
2557
     * (which indicates a wait for a dialling tone) from the prefix returned. If no national prefix is
2558
     * present, we return null.
2559
     *
2560
     * <p>Warning: Do not use this method for do-your-own formatting - for some regions, the
2561
     * national dialling prefix is used only for certain types of numbers. Use the library's
2562
     * formatting functions to prefix the national prefix when required.
2563
     *
2564
     * @param string $regionCode the region that we want to get the dialling prefix for
2565
     * @param boolean $stripNonDigits true to strip non-digits from the national dialling prefix
2566
     * @return string the dialling prefix for the region denoted by regionCode
2567
     */
2568 3
    public function getNddPrefixForRegion($regionCode, $stripNonDigits)
2569
    {
2570 3
        $metadata = $this->getMetadataForRegion($regionCode);
2571 3
        if ($metadata === null) {
2572 1
            return null;
2573
        }
2574 3
        $nationalPrefix = $metadata->getNationalPrefix();
2575
        // If no national prefix was found, we return null.
2576 3
        if (mb_strlen($nationalPrefix) == 0) {
2577 1
            return null;
2578
        }
2579 3
        if ($stripNonDigits) {
2580
            // Note: if any other non-numeric symbols are ever used in national prefixes, these would have
2581
            // to be removed here as well.
2582 3
            $nationalPrefix = str_replace("~", "", $nationalPrefix);
2583 3
        }
2584 3
        return $nationalPrefix;
2585
    }
2586
2587
    /**
2588
     * Check if rawInput, which is assumed to be in the national format, has a national prefix. The
2589
     * national prefix is assumed to be in digits-only form.
2590
     * @param string $rawInput
2591
     * @param string $nationalPrefix
2592
     * @param string $regionCode
2593
     * @return bool
2594
     */
2595 1
    protected function rawInputContainsNationalPrefix($rawInput, $nationalPrefix, $regionCode)
2596
    {
2597 1
        $normalizedNationalNumber = $this->normalizeDigitsOnly($rawInput);
2598 1
        if (strpos($normalizedNationalNumber, $nationalPrefix) === 0) {
2599
            try {
2600
                // Some Japanese numbers (e.g. 00777123) might be mistaken to contain the national prefix
2601
                // when written without it (e.g. 0777123) if we just do prefix matching. To tackle that, we
2602
                // check the validity of the number if the assumed national prefix is removed (777123 won't
2603
                // be valid in Japan).
2604 1
                return $this->isValidNumber(
2605 1
                    $this->parse(substr($normalizedNationalNumber, mb_strlen($nationalPrefix)), $regionCode)
2606 1
                );
2607
            } catch (NumberParseException $e) {
2608
                return false;
2609
            }
2610
        }
2611 1
        return false;
2612
    }
2613
2614
    /**
2615
     * Tests whether a phone number matches a valid pattern. Note this doesn't verify the number
2616
     * is actually in use, which is impossible to tell by just looking at a number itself.
2617
     *
2618
     * @param PhoneNumber $number the phone number that we want to validate
2619
     * @return boolean that indicates whether the number is of a valid pattern
2620
     */
2621 1836
    public function isValidNumber(PhoneNumber $number)
2622
    {
2623 1836
        $regionCode = $this->getRegionCodeForNumber($number);
2624 1836
        return $this->isValidNumberForRegion($number, $regionCode);
2625
    }
2626
2627
    /**
2628
     * Tests whether a phone number is valid for a certain region. Note this doesn't verify the number
2629
     * is actually in use, which is impossible to tell by just looking at a number itself. If the
2630
     * country calling code is not the same as the country calling code for the region, this
2631
     * immediately exits with false. After this, the specific number pattern rules for the region are
2632
     * examined. This is useful for determining for example whether a particular number is valid for
2633
     * Canada, rather than just a valid NANPA number.
2634
     * Warning: In most cases, you want to use {@link #isValidNumber} instead. For example, this
2635
     * method will mark numbers from British Crown dependencies such as the Isle of Man as invalid for
2636
     * the region "GB" (United Kingdom), since it has its own region code, "IM", which may be
2637
     * undesirable.
2638
     *
2639
     * @param PhoneNumber $number the phone number that we want to validate
2640
     * @param string $regionCode the region that we want to validate the phone number for
2641
     * @return boolean that indicates whether the number is of a valid pattern
2642
     */
2643 1842
    public function isValidNumberForRegion(PhoneNumber $number, $regionCode)
2644
    {
2645 1842
        $countryCode = $number->getCountryCode();
2646 1842
        $metadata = $this->getMetadataForRegionOrCallingCode($countryCode, $regionCode);
2647 1842
        if (($metadata === null) ||
2648 1819
            (static::REGION_CODE_FOR_NON_GEO_ENTITY !== $regionCode &&
2649 1810
                $countryCode !== $this->getCountryCodeForValidRegion($regionCode))
2650 1842
        ) {
2651
            // Either the region code was invalid, or the country calling code for this number does not
2652
            // match that of the region code.
2653 31
            return false;
2654
        }
2655 1818
        $nationalSignificantNumber = $this->getNationalSignificantNumber($number);
2656
2657 1818
        return $this->getNumberTypeHelper($nationalSignificantNumber, $metadata) != PhoneNumberType::UNKNOWN;
2658
    }
2659
2660
    /**
2661
     * Parses a string and returns it as a phone number in proto buffer format. The method is quite
2662
     * lenient and looks for a number in the input text (raw input) and does not check whether the
2663
     * string is definitely only a phone number. To do this, it ignores punctuation and white-space,
2664
     * as well as any text before the number (e.g. a leading “Tel: ”) and trims the non-number bits.
2665
     * It will accept a number in any format (E164, national, international etc), assuming it can
2666
     * interpreted with the defaultRegion supplied. It also attempts to convert any alpha characters
2667
     * into digits if it thinks this is a vanity number of the type "1800 MICROSOFT".
2668
     *
2669
     * <p> This method will throw a {@link NumberParseException} if the number is not considered to
2670
     * be a possible number. Note that validation of whether the number is actually a valid number
2671
     * for a particular region is not performed. This can be done separately with {@link #isValidnumber}.
2672
     *
2673
     * @param string $numberToParse number that we are attempting to parse. This can contain formatting
2674
     *                          such as +, ( and -, as well as a phone number extension.
2675
     * @param string $defaultRegion region that we are expecting the number to be from. This is only used
2676
     *                          if the number being parsed is not written in international format.
2677
     *                          The country_code for the number in this case would be stored as that
2678
     *                          of the default region supplied. If the number is guaranteed to
2679
     *                          start with a '+' followed by the country calling code, then
2680
     *                          "ZZ" or null can be supplied.
2681
     * @param PhoneNumber|null $phoneNumber
2682
     * @param bool $keepRawInput
2683
     * @return PhoneNumber a phone number proto buffer filled with the parsed number
2684
     * @throws NumberParseException  if the string is not considered to be a viable phone number (e.g.
2685
     *                               too few or too many digits) or if no default region was supplied
2686
     *                               and the number is not in international format (does not start
2687
     *                               with +)
2688
     */
2689 2731
    public function parse($numberToParse, $defaultRegion, PhoneNumber $phoneNumber = null, $keepRawInput = false)
2690
    {
2691 2731
        if ($phoneNumber === null) {
2692 2731
            $phoneNumber = new PhoneNumber();
2693 2731
        }
2694 2731
        $this->parseHelper($numberToParse, $defaultRegion, $keepRawInput, true, $phoneNumber);
2695 2726
        return $phoneNumber;
2696
    }
2697
2698
    /**
2699
     * Formats a phone number in the specified format using client-defined formatting rules. Note that
2700
     * if the phone number has a country calling code of zero or an otherwise invalid country calling
2701
     * code, we cannot work out things like whether there should be a national prefix applied, or how
2702
     * to format extensions, so we return the national significant number with no formatting applied.
2703
     *
2704
     * @param PhoneNumber $number the phone number to be formatted
2705
     * @param int $numberFormat the format the phone number should be formatted into
2706
     * @param array $userDefinedFormats formatting rules specified by clients
2707
     * @return String the formatted phone number
2708
     */
2709 2
    public function formatByPattern(PhoneNumber $number, $numberFormat, array $userDefinedFormats)
2710
    {
2711 2
        $countryCallingCode = $number->getCountryCode();
2712 2
        $nationalSignificantNumber = $this->getNationalSignificantNumber($number);
2713 2
        if (!$this->hasValidCountryCallingCode($countryCallingCode)) {
2714
            return $nationalSignificantNumber;
2715
        }
2716
        // Note getRegionCodeForCountryCode() is used because formatting information for regions which
2717
        // share a country calling code is contained by only one region for performance reasons. For
2718
        // example, for NANPA regions it will be contained in the metadata for US.
2719 2
        $regionCode = $this->getRegionCodeForCountryCode($countryCallingCode);
2720
        // Metadata cannot be null because the country calling code is valid
2721 2
        $metadata = $this->getMetadataForRegionOrCallingCode($countryCallingCode, $regionCode);
2722
2723 2
        $formattedNumber = "";
2724
2725 2
        $formattingPattern = $this->chooseFormattingPatternForNumber($userDefinedFormats, $nationalSignificantNumber);
2726 2
        if ($formattingPattern === null) {
2727
            // If no pattern above is matched, we format the number as a whole.
2728
            $formattedNumber .= $nationalSignificantNumber;
2729
        } else {
2730 2
            $numFormatCopy = new NumberFormat();
2731
            // Before we do a replacement of the national prefix pattern $NP with the national prefix, we
2732
            // need to copy the rule so that subsequent replacements for different numbers have the
2733
            // appropriate national prefix.
2734 2
            $numFormatCopy->mergeFrom($formattingPattern);
2735 2
            $nationalPrefixFormattingRule = $formattingPattern->getNationalPrefixFormattingRule();
2736 2
            if (mb_strlen($nationalPrefixFormattingRule) > 0) {
2737 1
                $nationalPrefix = $metadata->getNationalPrefix();
2738 1
                if (mb_strlen($nationalPrefix) > 0) {
2739
                    // Replace $NP with national prefix and $FG with the first group ($1).
2740 1
                    $npPatternMatcher = new Matcher(static::NP_PATTERN, $nationalPrefixFormattingRule);
2741 1
                    $nationalPrefixFormattingRule = $npPatternMatcher->replaceFirst($nationalPrefix);
2742 1
                    $fgPatternMatcher = new Matcher(static::FG_PATTERN, $nationalPrefixFormattingRule);
2743 1
                    $nationalPrefixFormattingRule = $fgPatternMatcher->replaceFirst("\\$1");
2744 1
                    $numFormatCopy->setNationalPrefixFormattingRule($nationalPrefixFormattingRule);
2745 1
                } else {
2746
                    // We don't want to have a rule for how to format the national prefix if there isn't one.
2747 1
                    $numFormatCopy->clearNationalPrefixFormattingRule();
2748
                }
2749 1
            }
2750 2
            $formattedNumber .= $this->formatNsnUsingPattern($nationalSignificantNumber, $numFormatCopy, $numberFormat);
2751
        }
2752 2
        $this->maybeAppendFormattedExtension($number, $metadata, $numberFormat, $formattedNumber);
2753 2
        $this->prefixNumberWithCountryCallingCode($countryCallingCode, $numberFormat, $formattedNumber);
2754 2
        return $formattedNumber;
2755
    }
2756
2757
    /**
2758
     * Gets a valid number for the specified region.
2759
     *
2760
     * @param string regionCode  the region for which an example number is needed
2761
     * @return PhoneNumber a valid fixed-line number for the specified region. Returns null when the metadata
2762
     *    does not contain such information, or the region 001 is passed in. For 001 (representing
2763
     *    non-geographical numbers), call {@link #getExampleNumberForNonGeoEntity} instead.
2764
     */
2765 247
    public function getExampleNumber($regionCode)
2766
    {
2767 247
        return $this->getExampleNumberForType($regionCode, PhoneNumberType::FIXED_LINE);
2768
    }
2769
2770
    /**
2771
     * Gets an invalid number for the specified region. This is useful for unit-testing purposes,
2772
     * where you want to test what will happen with an invalid number. Note that the number that is
2773
     * returned will always be able to be parsed and will have the correct country code. It may also
2774
     * be a valid *short* number/code for this region. Validity checking such numbers is handled with
2775
     * {@link ShortNumberInfo}.
2776
     *
2777
     * @param string $regionCode The region for which an example number is needed
2778
     * @return PhoneNumber|null An invalid number for the specified region. Returns null when an unsupported region
2779
     * or the region 001 (Earth) is passed in.
2780
     */
2781 244
    public function getInvalidExampleNumber($regionCode)
2782
    {
2783 244
        if (!$this->isValidRegionCode($regionCode)) {
2784
            return null;
2785
        }
2786
2787
        // We start off with a valid fixed-line number since every country supports this. Alternatively
2788
        // we could start with a different number type, since fixed-line numbers typically have a wide
2789
        // breadth of valid number lengths and we may have to make it very short before we get an
2790
        // invalid number.
2791
2792 244
        $desc = $this->getNumberDescByType($this->getMetadataForRegion($regionCode), PhoneNumberType::FIXED_LINE);
0 ignored issues
show
Bug introduced by
It seems like $this->getMetadataForRegion($regionCode) can be null; however, getNumberDescByType() does not accept null, maybe add an additional type check?

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

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

function doesNotAcceptNull(stdClass $x) { }

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

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

// Safe - Alternative 2
function withCheck2() {
    $x = mayReturnNull();
    if ($x instanceof stdClass) {
        doesNotAcceptNull($x);
    }
}
Loading history...
2793
2794 244
        if ($desc->getExampleNumber() == '') {
2795
            // This shouldn't happen; we have a test for this.
2796
            return null;
2797
        }
2798
2799 244
        $exampleNumber = $desc->getExampleNumber();
2800
2801
        // Try and make the number invalid. We do this by changing the length. We try reducing the
2802
        // length of the number, since currently no region has a number that is the same length as
2803
        // MIN_LENGTH_FOR_NSN. This is probably quicker than making the number longer, which is another
2804
        // alternative. We could also use the possible number pattern to extract the possible lengths of
2805
        // the number to make this faster, but this method is only for unit-testing so simplicity is
2806
        // preferred to performance.  We don't want to return a number that can't be parsed, so we check
2807
        // the number is long enough. We try all possible lengths because phone number plans often have
2808
        // overlapping prefixes so the number 123456 might be valid as a fixed-line number, and 12345 as
2809
        // a mobile number. It would be faster to loop in a different order, but we prefer numbers that
2810
        // look closer to real numbers (and it gives us a variety of different lengths for the resulting
2811
        // phone numbers - otherwise they would all be MIN_LENGTH_FOR_NSN digits long.)
2812 244
        for ($phoneNumberLength = mb_strlen($exampleNumber) - 1; $phoneNumberLength >= static::MIN_LENGTH_FOR_NSN; $phoneNumberLength--) {
2813 244
            $numberToTry = mb_substr($exampleNumber, 0, $phoneNumberLength);
2814
            try {
2815 244
                $possiblyValidNumber = $this->parse($numberToTry, $regionCode);
2816 244
                if (!$this->isValidNumber($possiblyValidNumber)) {
2817 244
                    return $possiblyValidNumber;
2818
                }
2819 14
            } catch (NumberParseException $e) {
2820
                // Shouldn't happen: we have already checked the length, we know example numbers have
2821
                // only valid digits, and we know the region code is fine.
2822
            }
2823 14
        }
2824
        // We have a test to check that this doesn't happen for any of our supported regions.
2825
        return null;
2826
    }
2827
2828
    /**
2829
     * Gets a valid number for the specified region and number type.
2830
     *
2831
     * @param string $regionCodeOrType the region for which an example number is needed
2832
     * @param int $type the PhoneNumberType of number that is needed
2833
     * @return PhoneNumber a valid number for the specified region and type. Returns null when the metadata
2834
     *     does not contain such information or if an invalid region or region 001 was entered.
2835
     *     For 001 (representing non-geographical numbers), call
2836
     *     {@link #getExampleNumberForNonGeoEntity} instead.
2837
     *
2838
     * If $regionCodeOrType is the only parameter supplied, then a valid number for the specified number type
2839
     * will be returned that may belong to any country.
2840
     */
2841 3179
    public function getExampleNumberForType($regionCodeOrType, $type = null)
2842
    {
2843 3179
        if ($regionCodeOrType !== null && $type === null) {
2844
            /*
2845
             * Gets a valid number for the specified number type (it may belong to any country).
2846
             */
2847 15
            foreach ($this->getSupportedRegions() as $regionCode) {
2848 15
                $exampleNumber = $this->getExampleNumberForType($regionCode, $regionCodeOrType);
2849 15
                if ($exampleNumber !== null) {
2850 11
                    return $exampleNumber;
2851
                }
2852 9
            }
2853
2854
            // If there wasn't an example number for a region, try the non-geographical entities
2855 4
            foreach ($this->getSupportedGlobalNetworkCallingCodes() as $countryCallingCode) {
2856 4
                $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...
2857
                try {
2858 4
                    if ($desc->getExampleNumber() != '') {
2859 4
                        return $this->parse("+" . $countryCallingCode . $desc->getExampleNumber(), static::UNKNOWN_REGION);
2860
                    }
2861
                } catch (NumberParseException $e) {
0 ignored issues
show
Coding Style Comprehensibility introduced by
Consider adding a comment why this CATCH block is empty.
Loading history...
2862
                }
2863
            }
2864
            // There are no example numbers of this type for any country in the library.
2865
            return null;
2866
        }
2867
2868
        // Check the region code is valid.
2869 3179
        if (!$this->isValidRegionCode($regionCodeOrType)) {
2870 1
            return null;
2871
        }
2872 3179
        $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...
2873
        try {
2874 3179
            if ($desc->hasExampleNumber()) {
2875 1800
                return $this->parse($desc->getExampleNumber(), $regionCodeOrType);
2876
            }
2877 1385
        } catch (NumberParseException $e) {
0 ignored issues
show
Coding Style Comprehensibility introduced by
Consider adding a comment why this CATCH block is empty.
Loading history...
2878
        }
2879 1385
        return null;
2880
    }
2881
2882
    /**
2883
     * @param PhoneMetadata $metadata
2884
     * @param int $type PhoneNumberType
2885
     * @return PhoneNumberDesc
2886
     */
2887 3423
    protected function getNumberDescByType(PhoneMetadata $metadata, $type)
2888
    {
2889
        switch ($type) {
2890 3423
            case PhoneNumberType::PREMIUM_RATE:
2891 245
                return $metadata->getPremiumRate();
2892 3178
            case PhoneNumberType::TOLL_FREE:
2893 245
                return $metadata->getTollFree();
2894 2933
            case PhoneNumberType::MOBILE:
2895 246
                return $metadata->getMobile();
2896 2688
            case PhoneNumberType::FIXED_LINE:
2897 2688
            case PhoneNumberType::FIXED_LINE_OR_MOBILE:
2898 1214
                return $metadata->getFixedLine();
2899 1474
            case PhoneNumberType::SHARED_COST:
2900 245
                return $metadata->getSharedCost();
2901 1229
            case PhoneNumberType::VOIP:
2902 245
                return $metadata->getVoip();
2903 984
            case PhoneNumberType::PERSONAL_NUMBER:
2904 245
                return $metadata->getPersonalNumber();
2905 739
            case PhoneNumberType::PAGER:
2906 245
                return $metadata->getPager();
2907 494
            case PhoneNumberType::UAN:
2908 245
                return $metadata->getUan();
2909 249
            case PhoneNumberType::VOICEMAIL:
2910 245
                return $metadata->getVoicemail();
2911 4
            default:
2912 4
                return $metadata->getGeneralDesc();
2913 4
        }
2914
    }
2915
2916
    /**
2917
     * Gets a valid number for the specified country calling code for a non-geographical entity.
2918
     *
2919
     * @param int $countryCallingCode the country calling code for a non-geographical entity
2920
     * @return PhoneNumber a valid number for the non-geographical entity. Returns null when the metadata
2921
     *    does not contain such information, or the country calling code passed in does not belong
2922
     *    to a non-geographical entity.
2923
     */
2924 10
    public function getExampleNumberForNonGeoEntity($countryCallingCode)
2925
    {
2926 10
        $metadata = $this->getMetadataForNonGeographicalRegion($countryCallingCode);
2927 10
        if ($metadata !== null) {
2928 10
            $desc = $metadata->getGeneralDesc();
2929
            try {
2930 10
                if ($desc->hasExampleNumber()) {
2931 10
                    return $this->parse("+" . $countryCallingCode . $desc->getExampleNumber(), static::UNKNOWN_REGION);
2932
                }
2933
            } catch (NumberParseException $e) {
0 ignored issues
show
Coding Style Comprehensibility introduced by
Consider adding a comment why this CATCH block is empty.
Loading history...
2934
            }
2935
        }
2936
        return null;
2937
    }
2938
2939
2940
    /**
2941
     * Takes two phone numbers and compares them for equality.
2942
     *
2943
     * <p>Returns EXACT_MATCH if the country_code, NSN, presence of a leading zero
2944
     * for Italian numbers and any extension present are the same. Returns NSN_MATCH
2945
     * if either or both has no region specified, and the NSNs and extensions are
2946
     * the same. Returns SHORT_NSN_MATCH if either or both has no region specified,
2947
     * or the region specified is the same, and one NSN could be a shorter version
2948
     * of the other number. This includes the case where one has an extension
2949
     * specified, and the other does not. Returns NO_MATCH otherwise. For example,
2950
     * the numbers +1 345 657 1234 and 657 1234 are a SHORT_NSN_MATCH. The numbers
2951
     * +1 345 657 1234 and 345 657 are a NO_MATCH.
2952
     *
2953
     * @param $firstNumberIn PhoneNumber|string First number to compare. If it is a
2954
     * string it can contain formatting, and can have country calling code specified
2955
     * with + at the start.
2956
     * @param $secondNumberIn PhoneNumber|string Second number to compare. If it is a
2957
     * string it can contain formatting, and can have country calling code specified
2958
     * with + at the start.
2959
     * @throws \InvalidArgumentException
2960
     * @return int {MatchType} NOT_A_NUMBER, NO_MATCH,
2961
     */
2962 4
    public function isNumberMatch($firstNumberIn, $secondNumberIn)
2963
    {
2964 4
        if (is_string($firstNumberIn) && is_string($secondNumberIn)) {
2965
            try {
2966 4
                $firstNumberAsProto = $this->parse($firstNumberIn, static::UNKNOWN_REGION);
2967 4
                return $this->isNumberMatch($firstNumberAsProto, $secondNumberIn);
2968 3
            } catch (NumberParseException $e) {
2969 3
                if ($e->getErrorType() === NumberParseException::INVALID_COUNTRY_CODE) {
2970
                    try {
2971 3
                        $secondNumberAsProto = $this->parse($secondNumberIn, static::UNKNOWN_REGION);
2972 2
                        return $this->isNumberMatch($secondNumberAsProto, $firstNumberIn);
2973 3
                    } catch (NumberParseException $e2) {
2974 3
                        if ($e2->getErrorType() === NumberParseException::INVALID_COUNTRY_CODE) {
2975
                            try {
2976 3
                                $firstNumberProto = new PhoneNumber();
2977 3
                                $secondNumberProto = new PhoneNumber();
2978 3
                                $this->parseHelper($firstNumberIn, null, false, false, $firstNumberProto);
2979 3
                                $this->parseHelper($secondNumberIn, null, false, false, $secondNumberProto);
2980 3
                                return $this->isNumberMatch($firstNumberProto, $secondNumberProto);
2981
                            } catch (NumberParseException $e3) {
2982
                                // Fall through and return MatchType::NOT_A_NUMBER
2983
                            }
2984
                        }
2985
                    }
2986
                }
2987
            }
2988 1
            return MatchType::NOT_A_NUMBER;
2989
        }
2990 4
        if ($firstNumberIn instanceof PhoneNumber && is_string($secondNumberIn)) {
2991
            // First see if the second number has an implicit country calling code, by attempting to parse
2992
            // it.
2993
            try {
2994 4
                $secondNumberAsProto = $this->parse($secondNumberIn, static::UNKNOWN_REGION);
2995 2
                return $this->isNumberMatch($firstNumberIn, $secondNumberAsProto);
2996 3
            } catch (NumberParseException $e) {
2997 3
                if ($e->getErrorType() === NumberParseException::INVALID_COUNTRY_CODE) {
2998
                    // The second number has no country calling code. EXACT_MATCH is no longer possible.
2999
                    // We parse it as if the region was the same as that for the first number, and if
3000
                    // EXACT_MATCH is returned, we replace this with NSN_MATCH.
3001 3
                    $firstNumberRegion = $this->getRegionCodeForCountryCode($firstNumberIn->getCountryCode());
3002
                    try {
3003 3
                        if ($firstNumberRegion != static::UNKNOWN_REGION) {
3004 3
                            $secondNumberWithFirstNumberRegion = $this->parse($secondNumberIn, $firstNumberRegion);
3005 3
                            $match = $this->isNumberMatch($firstNumberIn, $secondNumberWithFirstNumberRegion);
3006 3
                            if ($match === MatchType::EXACT_MATCH) {
3007 1
                                return MatchType::NSN_MATCH;
3008
                            }
3009 2
                            return $match;
3010
                        } else {
3011
                            // If the first number didn't have a valid country calling code, then we parse the
3012
                            // second number without one as well.
3013 1
                            $secondNumberProto = new PhoneNumber();
3014 1
                            $this->parseHelper($secondNumberIn, null, false, false, $secondNumberProto);
3015 1
                            return $this->isNumberMatch($firstNumberIn, $secondNumberProto);
3016
                        }
3017
                    } catch (NumberParseException $e2) {
3018
                        // Fall-through to return NOT_A_NUMBER.
3019
                    }
3020
                }
3021
            }
3022
        }
3023 4
        if ($firstNumberIn instanceof PhoneNumber && $secondNumberIn instanceof PhoneNumber) {
3024
            // Make copies of the phone number so that the numbers passed in are not edited.
3025 4
            $firstNumber = new PhoneNumber();
3026 4
            $firstNumber->mergeFrom($firstNumberIn);
3027 4
            $secondNumber = new PhoneNumber();
3028 4
            $secondNumber->mergeFrom($secondNumberIn);
3029
3030
            // First clear raw_input, country_code_source and preferred_domestic_carrier_code fields and any
3031
            // empty-string extensions so that we can use the proto-buffer equality method.
3032 4
            $firstNumber->clearRawInput();
3033 4
            $firstNumber->clearCountryCodeSource();
3034 4
            $firstNumber->clearPreferredDomesticCarrierCode();
3035 4
            $secondNumber->clearRawInput();
3036 4
            $secondNumber->clearCountryCodeSource();
3037 4
            $secondNumber->clearPreferredDomesticCarrierCode();
3038 4
            if ($firstNumber->hasExtension() && mb_strlen($firstNumber->getExtension()) === 0) {
3039 1
                $firstNumber->clearExtension();
3040 1
            }
3041
3042 4
            if ($secondNumber->hasExtension() && mb_strlen($secondNumber->getExtension()) === 0) {
3043 1
                $secondNumber->clearExtension();
3044 1
            }
3045
3046
            // Early exit if both had extensions and these are different.
3047 4
            if ($firstNumber->hasExtension() && $secondNumber->hasExtension() &&
3048 2
                $firstNumber->getExtension() != $secondNumber->getExtension()
3049 4
            ) {
3050 1
                return MatchType::NO_MATCH;
3051
            }
3052
3053 4
            $firstNumberCountryCode = $firstNumber->getCountryCode();
3054 4
            $secondNumberCountryCode = $secondNumber->getCountryCode();
3055
            // Both had country_code specified.
3056 4
            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...
3057 4
                if ($firstNumber->equals($secondNumber)) {
3058 2
                    return MatchType::EXACT_MATCH;
3059 2
                } elseif ($firstNumberCountryCode == $secondNumberCountryCode &&
3060 1
                    $this->isNationalNumberSuffixOfTheOther($firstNumber, $secondNumber)
3061 2
                ) {
3062
                    // A SHORT_NSN_MATCH occurs if there is a difference because of the presence or absence of
3063
                    // an 'Italian leading zero', the presence or absence of an extension, or one NSN being a
3064
                    // shorter variant of the other.
3065 1
                    return MatchType::SHORT_NSN_MATCH;
3066
                }
3067
                // This is not a match.
3068 1
                return MatchType::NO_MATCH;
3069
            }
3070
            // Checks cases where one or both country_code fields were not specified. To make equality
3071
            // checks easier, we first set the country_code fields to be equal.
3072 3
            $firstNumber->setCountryCode($secondNumberCountryCode);
3073
            // If all else was the same, then this is an NSN_MATCH.
3074 3
            if ($firstNumber->equals($secondNumber)) {
3075 1
                return MatchType::NSN_MATCH;
3076
            }
3077 3
            if ($this->isNationalNumberSuffixOfTheOther($firstNumber, $secondNumber)) {
3078 2
                return MatchType::SHORT_NSN_MATCH;
3079
            }
3080 1
            return MatchType::NO_MATCH;
3081
        }
3082
        return MatchType::NOT_A_NUMBER;
3083
    }
3084
3085
    /**
3086
     * Returns true when one national number is the suffix of the other or both are the same.
3087
     * @param PhoneNumber $firstNumber
3088
     * @param PhoneNumber $secondNumber
3089
     * @return bool
3090
     */
3091 3
    protected function isNationalNumberSuffixOfTheOther(PhoneNumber $firstNumber, PhoneNumber $secondNumber)
3092
    {
3093 3
        $firstNumberNationalNumber = trim((string)$firstNumber->getNationalNumber());
3094 3
        $secondNumberNationalNumber = trim((string)$secondNumber->getNationalNumber());
3095 3
        return $this->stringEndsWithString($firstNumberNationalNumber, $secondNumberNationalNumber) ||
3096 3
        $this->stringEndsWithString($secondNumberNationalNumber, $firstNumberNationalNumber);
3097
    }
3098
3099 3
    protected function stringEndsWithString($hayStack, $needle)
3100
    {
3101 3
        $revNeedle = strrev($needle);
3102 3
        $revHayStack = strrev($hayStack);
3103 3
        return strpos($revHayStack, $revNeedle) === 0;
3104
    }
3105
3106
    /**
3107
     * Returns true if the supplied region supports mobile number portability. Returns false for
3108
     * invalid, unknown or regions that don't support mobile number portability.
3109
     *
3110
     * @param string $regionCode the region for which we want to know whether it supports mobile number
3111
     *                    portability or not.
3112
     * @return bool
3113
     */
3114 3
    public function isMobileNumberPortableRegion($regionCode)
3115
    {
3116 3
        $metadata = $this->getMetadataForRegion($regionCode);
3117 3
        if ($metadata === null) {
3118
            return false;
3119
        }
3120
3121 3
        return $metadata->isMobileNumberPortableRegion();
3122
    }
3123
3124
    /**
3125
     * Check whether a phone number is a possible number given a number in the form of a string, and
3126
     * the region where the number could be dialed from. It provides a more lenient check than
3127
     * {@link #isValidNumber}. See {@link #isPossibleNumber(PhoneNumber)} for details.
3128
     *
3129
     * <p>This method first parses the number, then invokes {@link #isPossibleNumber(PhoneNumber)}
3130
     * with the resultant PhoneNumber object.
3131
     *
3132
     * @param PhoneNumber|string $number the number that needs to be checked, in the form of a string
3133
     * @param string $regionDialingFrom the region that we are expecting the number to be dialed from.
3134
     *     Note this is different from the region where the number belongs.  For example, the number
3135
     *     +1 650 253 0000 is a number that belongs to US. When written in this form, it can be
3136
     *     dialed from any region. When it is written as 00 1 650 253 0000, it can be dialed from any
3137
     *     region which uses an international dialling prefix of 00. When it is written as
3138
     *     650 253 0000, it can only be dialed from within the US, and when written as 253 0000, it
3139
     *     can only be dialed from within a smaller area in the US (Mountain View, CA, to be more
3140
     *     specific).
3141
     * @return boolean true if the number is possible
3142
     */
3143 2
    public function isPossibleNumber($number, $regionDialingFrom = null)
3144
    {
3145 2
        if ($regionDialingFrom !== null && is_string($number)) {
3146
            try {
3147 2
                return $this->isPossibleNumberWithReason(
3148 2
                    $this->parse($number, $regionDialingFrom)
3149 2
                ) === ValidationResult::IS_POSSIBLE;
3150 1
            } catch (NumberParseException $e) {
3151 1
                return false;
3152
            }
3153
        } else {
3154 2
            return $this->isPossibleNumberWithReason($number) === ValidationResult::IS_POSSIBLE;
0 ignored issues
show
Bug introduced by
It seems like $number defined by parameter $number on line 3143 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...
3155
        }
3156
    }
3157
3158
3159
    /**
3160
     * Check whether a phone number is a possible number. It provides a more lenient check than
3161
     * {@link #isValidNumber} in the following sense:
3162
     * <ol>
3163
     * <li> It only checks the length of phone numbers. In particular, it doesn't check starting
3164
     *      digits of the number.
3165
     * <li> It doesn't attempt to figure out the type of the number, but uses general rules which
3166
     *      applies to all types of phone numbers in a region. Therefore, it is much faster than
3167
     *      isValidNumber.
3168
     * <li> For fixed line numbers, many regions have the concept of area code, which together with
3169
     *      subscriber number constitute the national significant number. It is sometimes okay to dial
3170
     *      the subscriber number only when dialing in the same area. This function will return
3171
     *      true if the subscriber-number-only version is passed in. On the other hand, because
3172
     *      isValidNumber validates using information on both starting digits (for fixed line
3173
     *      numbers, that would most likely be area codes) and length (obviously includes the
3174
     *      length of area codes for fixed line numbers), it will return false for the
3175
     *      subscriber-number-only version.
3176
     * </ol>
3177
     * @param PhoneNumber $number the number that needs to be checked
3178
     * @return int a ValidationResult object which indicates whether the number is possible
3179
     */
3180 4
    public function isPossibleNumberWithReason(PhoneNumber $number)
3181
    {
3182 4
        $nationalNumber = $this->getNationalSignificantNumber($number);
3183 4
        $countryCode = $number->getCountryCode();
3184
        // Note: For Russian Fed and NANPA numbers, we just use the rules from the default region (US or
3185
        // Russia) since the getRegionCodeForNumber will not work if the number is possible but not
3186
        // valid. This would need to be revisited if the possible number pattern ever differed between
3187
        // various regions within those plans.
3188 4
        if (!$this->hasValidCountryCallingCode($countryCode)) {
3189 1
            return ValidationResult::INVALID_COUNTRY_CODE;
3190
        }
3191
3192 4
        $regionCode = $this->getRegionCodeForCountryCode($countryCode);
3193
        // Metadata cannot be null because the country calling code is valid.
3194 4
        $metadata = $this->getMetadataForRegionOrCallingCode($countryCode, $regionCode);
3195
3196 4
        $possibleNumberPattern = $metadata->getGeneralDesc()->getPossibleNumberPattern();
3197 4
        return $this->testNumberLengthAgainstPattern($possibleNumberPattern, $nationalNumber);
3198
    }
3199
3200
    /**
3201
     * Attempts to extract a valid number from a phone number that is too long to be valid, and resets
3202
     * the PhoneNumber object passed in to that valid version. If no valid number could be extracted,
3203
     * the PhoneNumber object passed in will not be modified.
3204
     * @param PhoneNumber $number a PhoneNumber object which contains a number that is too long to be valid.
3205
     * @return boolean true if a valid phone number can be successfully extracted.
3206
     */
3207 1
    public function truncateTooLongNumber(PhoneNumber $number)
3208
    {
3209 1
        if ($this->isValidNumber($number)) {
3210 1
            return true;
3211
        }
3212 1
        $numberCopy = new PhoneNumber();
3213 1
        $numberCopy->mergeFrom($number);
3214 1
        $nationalNumber = $number->getNationalNumber();
3215
        do {
3216 1
            $nationalNumber = floor($nationalNumber / 10);
3217 1
            $numberCopy->setNationalNumber($nationalNumber);
3218 1
            if ($this->isPossibleNumberWithReason($numberCopy) == ValidationResult::TOO_SHORT || $nationalNumber == 0) {
3219 1
                return false;
3220
            }
3221 1
        } while (!$this->isValidNumber($numberCopy));
3222 1
        $number->setNationalNumber($nationalNumber);
3223 1
        return true;
3224
    }
3225
}
3226