Completed
Pull Request — master (#170)
by Joshua
19:33 queued 10:06
created

PhoneNumberUtil::initValidStartCharPattern()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 4
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 3
CRAP Score 1

Importance

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