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