Completed
Pull Request — phoneNumberMatcher (#171)
by Joshua
23:58 queued 09:37
created

PhoneNumberUtil::formattingRuleHasFirstGroupOnly()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 8
Code Lines 5

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 4
CRAP Score 2

Importance

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