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; |
||
158 | |||
159 | /** |
||
160 | * Set of country codes that have geographically assigned mobile numbers (see GEO_MOBILE_COUNTRIES |
||
161 | * below) which are not based on *area codes*. For example, in China mobile numbers start with a |
||
162 | * carrier indicator, and beyond that are geographically assigned: this carrier indicator is not |
||
163 | * considered to be an area code. |
||
164 | * |
||
165 | * @var array |
||
166 | */ |
||
167 | protected static $GEO_MOBILE_COUNTRIES_WITHOUT_MOBILE_AREA_CODES; |
||
168 | |||
169 | /** |
||
170 | * Set of country calling codes that have geographically assigned mobile numbers. This may not be |
||
171 | * complete; we add calling codes case by case, as we find geographical mobile numbers or hear |
||
172 | * from user reports. Note that countries like the US, where we can't distinguish between |
||
173 | * fixed-line or mobile numbers, are not listed here, since we consider FIXED_LINE_OR_MOBILE to be |
||
174 | * a possibly geographically-related type anyway (like FIXED_LINE). |
||
175 | * |
||
176 | * @var array |
||
177 | */ |
||
178 | protected static $GEO_MOBILE_COUNTRIES; |
||
179 | |||
180 | /** |
||
181 | * For performance reasons, amalgamate both into one map. |
||
182 | * @var array |
||
183 | */ |
||
184 | protected static $ALPHA_PHONE_MAPPINGS; |
||
185 | |||
186 | /** |
||
187 | * Separate map of all symbols that we wish to retain when formatting alpha numbers. This |
||
188 | * includes digits, ASCII letters and number grouping symbols such as "-" and " ". |
||
189 | * @var array |
||
190 | */ |
||
191 | protected static $ALL_PLUS_NUMBER_GROUPING_SYMBOLS; |
||
192 | |||
193 | /** |
||
194 | * Simple ASCII digits map used to populate ALPHA_PHONE_MAPPINGS and |
||
195 | * ALL_PLUS_NUMBER_GROUPING_SYMBOLS. |
||
196 | * @var array |
||
197 | */ |
||
198 | protected static $asciiDigitMappings = array( |
||
199 | '0' => '0', |
||
200 | '1' => '1', |
||
201 | '2' => '2', |
||
202 | '3' => '3', |
||
203 | '4' => '4', |
||
204 | '5' => '5', |
||
205 | '6' => '6', |
||
206 | '7' => '7', |
||
207 | '8' => '8', |
||
208 | '9' => '9', |
||
209 | ); |
||
210 | |||
211 | /** |
||
212 | * Regexp of all possible ways to write extensions, for use when parsing. This will be run as a |
||
213 | * case-insensitive regexp match. Wide character versions are also provided after each ASCII |
||
214 | * version. |
||
215 | * @var String |
||
216 | */ |
||
217 | protected static $EXTN_PATTERNS_FOR_PARSING; |
||
218 | protected static $EXTN_PATTERN = null; |
||
219 | protected static $VALID_PHONE_NUMBER_PATTERN; |
||
220 | protected static $MIN_LENGTH_PHONE_NUMBER_PATTERN; |
||
221 | /** |
||
222 | * Regular expression of viable phone numbers. This is location independent. Checks we have at |
||
223 | * least three leading digits, and only valid punctuation, alpha characters and |
||
224 | * digits in the phone number. Does not include extension data. |
||
225 | * The symbol 'x' is allowed here as valid punctuation since it is often used as a placeholder for |
||
226 | * carrier codes, for example in Brazilian phone numbers. We also allow multiple "+" characters at |
||
227 | * the start. |
||
228 | * Corresponds to the following: |
||
229 | * [digits]{minLengthNsn}| |
||
230 | * plus_sign*(([punctuation]|[star])*[digits]){3,}([punctuation]|[star]|[digits]|[alpha])* |
||
231 | * |
||
232 | * The first reg-ex is to allow short numbers (two digits long) to be parsed if they are entered |
||
233 | * as "15" etc, but only if there is no punctuation in them. The second expression restricts the |
||
234 | * number of digits to three or more, but then allows them to be in international form, and to |
||
235 | * have alpha-characters and punctuation. |
||
236 | * |
||
237 | * Note VALID_PUNCTUATION starts with a -, so must be the first in the range. |
||
238 | * @var string |
||
239 | */ |
||
240 | protected static $VALID_PHONE_NUMBER; |
||
241 | protected static $numericCharacters = array( |
||
242 | "\xef\xbc\x90" => 0, |
||
243 | "\xef\xbc\x91" => 1, |
||
244 | "\xef\xbc\x92" => 2, |
||
245 | "\xef\xbc\x93" => 3, |
||
246 | "\xef\xbc\x94" => 4, |
||
247 | "\xef\xbc\x95" => 5, |
||
248 | "\xef\xbc\x96" => 6, |
||
249 | "\xef\xbc\x97" => 7, |
||
250 | "\xef\xbc\x98" => 8, |
||
251 | "\xef\xbc\x99" => 9, |
||
252 | |||
253 | "\xd9\xa0" => 0, |
||
254 | "\xd9\xa1" => 1, |
||
255 | "\xd9\xa2" => 2, |
||
256 | "\xd9\xa3" => 3, |
||
257 | "\xd9\xa4" => 4, |
||
258 | "\xd9\xa5" => 5, |
||
259 | "\xd9\xa6" => 6, |
||
260 | "\xd9\xa7" => 7, |
||
261 | "\xd9\xa8" => 8, |
||
262 | "\xd9\xa9" => 9, |
||
263 | |||
264 | "\xdb\xb0" => 0, |
||
265 | "\xdb\xb1" => 1, |
||
266 | "\xdb\xb2" => 2, |
||
267 | "\xdb\xb3" => 3, |
||
268 | "\xdb\xb4" => 4, |
||
269 | "\xdb\xb5" => 5, |
||
270 | "\xdb\xb6" => 6, |
||
271 | "\xdb\xb7" => 7, |
||
272 | "\xdb\xb8" => 8, |
||
273 | "\xdb\xb9" => 9, |
||
274 | |||
275 | "\xe1\xa0\x90" => 0, |
||
276 | "\xe1\xa0\x91" => 1, |
||
277 | "\xe1\xa0\x92" => 2, |
||
278 | "\xe1\xa0\x93" => 3, |
||
279 | "\xe1\xa0\x94" => 4, |
||
280 | "\xe1\xa0\x95" => 5, |
||
281 | "\xe1\xa0\x96" => 6, |
||
282 | "\xe1\xa0\x97" => 7, |
||
283 | "\xe1\xa0\x98" => 8, |
||
284 | "\xe1\xa0\x99" => 9, |
||
285 | ); |
||
286 | |||
287 | /** |
||
288 | * The set of county calling codes that map to the non-geo entity region ("001"). |
||
289 | * @var array |
||
290 | */ |
||
291 | protected $countryCodesForNonGeographicalRegion = array(); |
||
292 | /** |
||
293 | * The set of regions the library supports. |
||
294 | * @var array |
||
295 | */ |
||
296 | protected $supportedRegions = array(); |
||
297 | |||
298 | /** |
||
299 | * A mapping from a country calling code to the region codes which denote the region represented |
||
300 | * by that country calling code. In the case of multiple regions sharing a calling code, such as |
||
301 | * the NANPA regions, the one indicated with "isMainCountryForCode" in the metadata should be |
||
302 | * first. |
||
303 | * @var array |
||
304 | */ |
||
305 | protected $countryCallingCodeToRegionCodeMap = array(); |
||
306 | /** |
||
307 | * The set of regions that share country calling code 1. |
||
308 | * @var array |
||
309 | */ |
||
310 | 402 | protected $nanpaRegions = array(); |
|
311 | |||
312 | 402 | /** |
|
313 | 402 | * @var MetadataSourceInterface |
|
314 | */ |
||
315 | protected $metadataSource; |
||
316 | |||
317 | /** |
||
318 | 402 | * This class implements a singleton, so the only constructor is protected. |
|
319 | 402 | * @param MetadataSourceInterface $metadataSource |
|
320 | 402 | * @param $countryCallingCodeToRegionCodeMap |
|
321 | 402 | */ |
|
322 | protected function __construct(MetadataSourceInterface $metadataSource, $countryCallingCodeToRegionCodeMap) |
||
323 | 402 | { |
|
324 | $this->metadataSource = $metadataSource; |
||
325 | 402 | $this->countryCallingCodeToRegionCodeMap = $countryCallingCodeToRegionCodeMap; |
|
326 | 402 | $this->init(); |
|
327 | 402 | static::initCapturingExtnDigits(); |
|
328 | static::initExtnPatterns(); |
||
329 | 402 | static::initExtnPattern(); |
|
330 | static::$PLUS_CHARS_PATTERN = "[" . static::PLUS_CHARS . "]+"; |
||
331 | 402 | static::$SEPARATOR_PATTERN = "[" . static::VALID_PUNCTUATION . "]+"; |
|
332 | static::$CAPTURING_DIGIT_PATTERN = "(" . static::DIGITS . ")"; |
||
333 | static::$VALID_START_CHAR_PATTERN = "[" . static::PLUS_CHARS . static::DIGITS . "]"; |
||
334 | |||
335 | 402 | static::$ALPHA_PHONE_MAPPINGS = static::$ALPHA_MAPPINGS + static::$asciiDigitMappings; |
|
336 | 402 | ||
337 | 402 | static::$DIALLABLE_CHAR_MAPPINGS = static::$asciiDigitMappings; |
|
338 | 402 | static::$DIALLABLE_CHAR_MAPPINGS[static::PLUS_SIGN] = static::PLUS_SIGN; |
|
339 | 402 | static::$DIALLABLE_CHAR_MAPPINGS['*'] = '*'; |
|
340 | 402 | ||
341 | 402 | static::$ALL_PLUS_NUMBER_GROUPING_SYMBOLS = array(); |
|
342 | 402 | // Put (lower letter -> upper letter) and (upper letter -> upper letter) mappings. |
|
343 | 402 | foreach (static::$ALPHA_MAPPINGS as $c => $value) { |
|
344 | 402 | static::$ALL_PLUS_NUMBER_GROUPING_SYMBOLS[strtolower($c)] = $c; |
|
345 | 402 | static::$ALL_PLUS_NUMBER_GROUPING_SYMBOLS[$c] = $c; |
|
346 | 402 | } |
|
347 | 402 | static::$ALL_PLUS_NUMBER_GROUPING_SYMBOLS += static::$asciiDigitMappings; |
|
348 | 402 | static::$ALL_PLUS_NUMBER_GROUPING_SYMBOLS["-"] = '-'; |
|
349 | 402 | static::$ALL_PLUS_NUMBER_GROUPING_SYMBOLS["\xEF\xBC\x8D"] = '-'; |
|
350 | 402 | static::$ALL_PLUS_NUMBER_GROUPING_SYMBOLS["\xE2\x80\x90"] = '-'; |
|
351 | 402 | static::$ALL_PLUS_NUMBER_GROUPING_SYMBOLS["\xE2\x80\x91"] = '-'; |
|
352 | static::$ALL_PLUS_NUMBER_GROUPING_SYMBOLS["\xE2\x80\x92"] = '-'; |
||
353 | static::$ALL_PLUS_NUMBER_GROUPING_SYMBOLS["\xE2\x80\x93"] = '-'; |
||
354 | 402 | static::$ALL_PLUS_NUMBER_GROUPING_SYMBOLS["\xE2\x80\x94"] = '-'; |
|
355 | 402 | static::$ALL_PLUS_NUMBER_GROUPING_SYMBOLS["\xE2\x80\x95"] = '-'; |
|
356 | 402 | static::$ALL_PLUS_NUMBER_GROUPING_SYMBOLS["\xE2\x88\x92"] = '-'; |
|
357 | static::$ALL_PLUS_NUMBER_GROUPING_SYMBOLS["/"] = "/"; |
||
358 | 402 | static::$ALL_PLUS_NUMBER_GROUPING_SYMBOLS["\xEF\xBC\x8F"] = "/"; |
|
359 | static::$ALL_PLUS_NUMBER_GROUPING_SYMBOLS[" "] = " "; |
||
360 | 402 | static::$ALL_PLUS_NUMBER_GROUPING_SYMBOLS["\xE3\x80\x80"] = " "; |
|
361 | 402 | static::$ALL_PLUS_NUMBER_GROUPING_SYMBOLS["\xE2\x81\xA0"] = " "; |
|
362 | 402 | static::$ALL_PLUS_NUMBER_GROUPING_SYMBOLS["."] = "."; |
|
363 | static::$ALL_PLUS_NUMBER_GROUPING_SYMBOLS["\xEF\xBC\x8E"] = "."; |
||
364 | 402 | ||
365 | 402 | ||
366 | 402 | static::$MIN_LENGTH_PHONE_NUMBER_PATTERN = "[" . static::DIGITS . "]{" . static::MIN_LENGTH_FOR_NSN . "}"; |
|
367 | 402 | static::$VALID_PHONE_NUMBER = "[" . static::PLUS_CHARS . "]*(?:[" . static::VALID_PUNCTUATION . static::STAR_SIGN . "]*[" . static::DIGITS . "]){3,}[" . static::VALID_PUNCTUATION . static::STAR_SIGN . static::VALID_ALPHA . static::DIGITS . "]*"; |
|
368 | static::$VALID_PHONE_NUMBER_PATTERN = "%^" . static::$MIN_LENGTH_PHONE_NUMBER_PATTERN . "$|^" . static::$VALID_PHONE_NUMBER . "(?:" . static::$EXTN_PATTERNS_FOR_PARSING . ")?$%" . static::REGEX_FLAGS; |
||
369 | |||
370 | static::$UNWANTED_END_CHAR_PATTERN = "[^" . static::DIGITS . static::VALID_ALPHA . "#]+$"; |
||
371 | |||
372 | static::$MOBILE_TOKEN_MAPPINGS = array(); |
||
373 | static::$MOBILE_TOKEN_MAPPINGS['52'] = "1"; |
||
374 | static::$MOBILE_TOKEN_MAPPINGS['54'] = "9"; |
||
375 | |||
376 | static::$GEO_MOBILE_COUNTRIES_WITHOUT_MOBILE_AREA_CODES = array(); |
||
377 | static::$GEO_MOBILE_COUNTRIES_WITHOUT_MOBILE_AREA_CODES[] = 86; // China |
||
378 | |||
379 | static::$GEO_MOBILE_COUNTRIES = array(); |
||
380 | static::$GEO_MOBILE_COUNTRIES[] = 52; // Mexico |
||
381 | static::$GEO_MOBILE_COUNTRIES[] = 54; // Argentina |
||
382 | static::$GEO_MOBILE_COUNTRIES[] = 55; // Brazil |
||
383 | static::$GEO_MOBILE_COUNTRIES[] = 62; // Indonesia: some prefixes only (fixed CMDA wireless) |
||
384 | 5252 | ||
385 | static::$GEO_MOBILE_COUNTRIES = array_merge(static::$GEO_MOBILE_COUNTRIES, static::$GEO_MOBILE_COUNTRIES_WITHOUT_MOBILE_AREA_CODES); |
||
386 | 5252 | } |
|
387 | 402 | ||
388 | 267 | /** |
|
389 | * Gets a {@link PhoneNumberUtil} instance to carry out international phone number formatting, |
||
390 | * parsing, or validation. The instance is loaded with phone number metadata for a number of most |
||
391 | 402 | * commonly used regions. |
|
392 | * |
||
393 | * <p>The {@link PhoneNumberUtil} is implemented as a singleton. Therefore, calling getInstance |
||
394 | * multiple times will only result in one instance being created. |
||
395 | 402 | * |
|
396 | * @param string $baseFileLocation |
||
397 | * @param array|null $countryCallingCodeToRegionCodeMap |
||
398 | * @param MetadataLoaderInterface|null $metadataLoader |
||
399 | * @param MetadataSourceInterface|null $metadataSource |
||
400 | * @return PhoneNumberUtil instance |
||
401 | 5252 | */ |
|
402 | public static function getInstance($baseFileLocation = self::META_DATA_FILE_PREFIX, array $countryCallingCodeToRegionCodeMap = null, MetadataLoaderInterface $metadataLoader = null, MetadataSourceInterface $metadataSource = null) |
||
403 | { |
||
404 | 402 | if (static::$instance === null) { |
|
405 | if ($countryCallingCodeToRegionCodeMap === null) { |
||
406 | 402 | $countryCallingCodeToRegionCodeMap = CountryCodeToRegionCodeMap::$countryCodeToRegionCodeMap; |
|
407 | } |
||
408 | |||
409 | if ($metadataLoader === null) { |
||
410 | $metadataLoader = new DefaultMetadataLoader(); |
||
411 | } |
||
412 | |||
413 | if ($metadataSource === null) { |
||
414 | $metadataSource = new MultiFileMetadataSourceImpl($metadataLoader, __DIR__ . '/data/' . $baseFileLocation); |
||
415 | } |
||
416 | |||
417 | static::$instance = new static($metadataSource, $countryCallingCodeToRegionCodeMap); |
||
418 | } |
||
419 | return static::$instance; |
||
420 | } |
||
421 | 402 | ||
422 | protected function init() |
||
423 | { |
||
424 | 402 | foreach ($this->countryCallingCodeToRegionCodeMap as $countryCode => $regionCodes) { |
|
425 | 402 | // We can assume that if the country calling code maps to the non-geo entity region code then |
|
426 | // that's the only region code it maps to. |
||
427 | 402 | if (count($regionCodes) == 1 && static::REGION_CODE_FOR_NON_GEO_ENTITY === $regionCodes[0]) { |
|
428 | // This is the subset of all country codes that map to the non-geo entity region code. |
||
429 | 402 | $this->countryCodesForNonGeographicalRegion[] = $countryCode; |
|
430 | 402 | } else { |
|
431 | // The supported regions set does not include the "001" non-geo entity region code. |
||
432 | 402 | $this->supportedRegions = array_merge($this->supportedRegions, $regionCodes); |
|
433 | } |
||
434 | } |
||
435 | 402 | // If the non-geo entity still got added to the set of supported regions it must be because |
|
436 | // there are entries that list the non-geo entity alongside normal regions (which is wrong). |
||
437 | // If we discover this, remove the non-geo entity from the set of supported regions and log. |
||
438 | $idx_region_code_non_geo_entity = array_search(static::REGION_CODE_FOR_NON_GEO_ENTITY, $this->supportedRegions); |
||
439 | 402 | if ($idx_region_code_non_geo_entity !== false) { |
|
440 | unset($this->supportedRegions[$idx_region_code_non_geo_entity]); |
||
441 | } |
||
442 | 402 | $this->nanpaRegions = $this->countryCallingCodeToRegionCodeMap[static::NANPA_COUNTRY_CODE]; |
|
443 | } |
||
444 | |||
445 | protected static function initCapturingExtnDigits() |
||
449 | |||
450 | protected static function initExtnPatterns() |
||
461 | |||
462 | // The FIRST_GROUP_PATTERN was originally set to $1 but there are some countries for which the |
||
463 | // first group is not used in the national pattern (e.g. Argentina) so the $1 group does not match |
||
464 | // correctly. Therefore, we use \d, so that the first group actually used in the pattern will be |
||
465 | // matched. |
||
466 | |||
467 | /** |
||
468 | * Helper initialiser method to create the regular-expression pattern to match extensions, |
||
469 | 402 | * allowing the one-char extension symbols provided by {@code singleExtnSymbols}. |
|
470 | 402 | * @param string $singleExtnSymbols |
|
471 | 402 | * @return string |
|
472 | */ |
||
473 | protected static function createExtnPattern($singleExtnSymbols) |
||
474 | 402 | { |
|
475 | // There are three regular expressions here. The first covers RFC 3966 format, where the |
||
476 | 402 | // extension is added using ";ext=". The second more generic one starts with optional white |
|
477 | 402 | // space and ends with an optional full stop (.), followed by zero or more spaces/tabs and then |
|
478 | // the numbers themselves. The other one covers the special case of American numbers where the |
||
479 | // extension is written with a hash at the end, such as "- 503#". |
||
480 | // Note that the only capturing groups should be around the digits that you want to capture as |
||
481 | // part of the extension, or else parsing will fail! |
||
482 | 402 | // Canonical-equivalence doesn't seem to be an option with Android java, so we allow two options |
|
483 | // for representing the accented o - the character itself, and one in the unicode decomposed |
||
484 | 402 | // form with the combining acute accent. |
|
485 | 402 | return (static::RFC3966_EXTN_PREFIX . static::$CAPTURING_EXTN_DIGITS . "|" . "[ \xC2\xA0\\t,]*" . |
|
486 | "(?:e?xt(?:ensi(?:o\xCC\x81?|\xC3\xB3))?n?|(?:\xEF\xBD\x85)?\xEF\xBD\x98\xEF\xBD\x94(?:\xEF\xBD\x8E)?|" . |
||
487 | "[" . $singleExtnSymbols . "]|int|\xEF\xBD\x89\xEF\xBD\x8E\xEF\xBD\x94|anexo)" . |
||
488 | "[:\\.\xEF\xBC\x8E]?[ \xC2\xA0\\t,-]*" . static::$CAPTURING_EXTN_DIGITS . "#?|" . |
||
489 | "[- ]+(" . static::DIGITS . "{1,5})#"); |
||
490 | } |
||
491 | |||
492 | protected static function initExtnPattern() |
||
493 | { |
||
494 | static::$EXTN_PATTERN = "/(?:" . static::$EXTN_PATTERNS_FOR_PARSING . ")$/" . static::REGEX_FLAGS; |
||
495 | } |
||
496 | |||
497 | /** |
||
498 | * Used for testing purposes only to reset the PhoneNumberUtil singleton to null. |
||
499 | */ |
||
500 | public static function resetInstance() |
||
504 | |||
505 | /** |
||
506 | * Converts all alpha characters in a number to their respective digits on a keypad, but retains |
||
507 | * existing formatting. |
||
508 | * @param string $number |
||
509 | * @return string |
||
510 | 5 | */ |
|
511 | public static function convertAlphaCharactersInNumber($number) |
||
515 | |||
516 | /** |
||
517 | * Normalizes a string of characters representing a phone number by replacing all characters found |
||
518 | * in the accompanying map with the values therein, and stripping all other characters if |
||
519 | * removeNonMatches is true. |
||
520 | * |
||
521 | * @param string $number a string of characters representing a phone number |
||
522 | * @param array $normalizationReplacements a mapping of characters to what they should be replaced by in |
||
523 | * the normalized version of the phone number |
||
524 | * @param bool $removeNonMatches indicates whether characters that are not able to be replaced |
||
525 | 5 | * should be stripped from the number. If this is false, they will be left unchanged in the number. |
|
526 | 5 | * @return string the normalized string version of the phone number |
|
527 | */ |
||
528 | protected static function normalizeHelper($number, array $normalizationReplacements, $removeNonMatches) |
||
529 | { |
||
530 | $normalizedNumber = ""; |
||
531 | $strLength = mb_strlen($number, 'UTF-8'); |
||
532 | for ($i = 0; $i < $strLength; $i++) { |
||
533 | $character = mb_substr($number, $i, 1, 'UTF-8'); |
||
534 | if (isset($normalizationReplacements[mb_strtoupper($character, 'UTF-8')])) { |
||
535 | $normalizedNumber .= $normalizationReplacements[mb_strtoupper($character, 'UTF-8')]; |
||
536 | } else { |
||
537 | if (!$removeNonMatches) { |
||
538 | $normalizedNumber .= $character; |
||
539 | } |
||
540 | } |
||
541 | // If neither of the above are true, we remove this character. |
||
542 | } |
||
543 | return $normalizedNumber; |
||
544 | 249 | } |
|
545 | |||
546 | 249 | /** |
|
547 | * Helper function to check if the national prefix formatting rule has the first group only, i.e., |
||
548 | * does not start with the national prefix. |
||
549 | * @param string $nationalPrefixFormattingRule |
||
550 | * @return bool |
||
551 | */ |
||
552 | public static function formattingRuleHasFirstGroupOnly($nationalPrefixFormattingRule) |
||
553 | { |
||
554 | 5 | $m = preg_match(static::FIRST_GROUP_ONLY_PREFIX_PATTERN, $nationalPrefixFormattingRule); |
|
555 | return $m > 0; |
||
556 | 5 | } |
|
557 | |||
558 | /** |
||
559 | * Convenience method to get a list of what regions the library has metadata for. |
||
560 | * @return array |
||
561 | */ |
||
562 | public function getSupportedRegions() |
||
566 | |||
567 | /** |
||
568 | * Convenience method to get a list of what global network calling codes the library has metadata |
||
569 | * for. |
||
570 | * @return array |
||
571 | */ |
||
572 | public function getSupportedGlobalNetworkCallingCodes() |
||
576 | |||
577 | /** |
||
578 | * Gets the length of the geographical area code from the {@code nationalNumber} field of the |
||
579 | * PhoneNumber object passed in, so that clients could use it to split a national significant |
||
580 | * number into geographical area code and subscriber number. It works in such a way that the |
||
581 | * resultant subscriber number should be diallable, at least on some devices. An example of how |
||
582 | * this could be used: |
||
583 | * |
||
584 | * <code> |
||
585 | * $phoneUtil = PhoneNumberUtil::getInstance(); |
||
586 | * $number = $phoneUtil->parse("16502530000", "US"); |
||
587 | * $nationalSignificantNumber = $phoneUtil->getNationalSignificantNumber($number); |
||
588 | * |
||
589 | * $areaCodeLength = $phoneUtil->getLengthOfGeographicalAreaCode($number); |
||
590 | * if ($areaCodeLength > 0) |
||
591 | * { |
||
592 | * $areaCode = substr($nationalSignificantNumber, 0,$areaCodeLength); |
||
593 | * $subscriberNumber = substr($nationalSignificantNumber, $areaCodeLength); |
||
594 | * } else { |
||
595 | * $areaCode = ""; |
||
596 | * $subscriberNumber = $nationalSignificantNumber; |
||
597 | 1 | * } |
|
598 | * </code> |
||
599 | * |
||
600 | * N.B.: area code is a very ambiguous concept, so the I18N team generally recommends against |
||
601 | * using it for most purposes, but recommends using the more general {@code nationalNumber} |
||
602 | * instead. Read the following carefully before deciding to use this method: |
||
603 | * <ul> |
||
604 | * <li> geographical area codes change over time, and this method honors those changes; |
||
605 | * therefore, it doesn't guarantee the stability of the result it produces. |
||
606 | 1 | * <li> subscriber numbers may not be diallable from all devices (notably mobile devices, which |
|
607 | * typically requires the full national_number to be dialled in most regions). |
||
608 | * <li> most non-geographical numbers have no area codes, including numbers from non-geographical |
||
609 | * entities |
||
610 | * <li> some geographical numbers have no area codes. |
||
611 | * </ul> |
||
612 | * @param PhoneNumber $number PhoneNumber object for which clients want to know the length of the area code. |
||
613 | * @return int the length of area code of the PhoneNumber object passed in. |
||
614 | */ |
||
615 | public function getLengthOfGeographicalAreaCode(PhoneNumber $number) |
||
616 | { |
||
617 | $metadata = $this->getMetadataForRegion($this->getRegionCodeForNumber($number)); |
||
618 | if ($metadata === null) { |
||
619 | return 0; |
||
620 | } |
||
621 | // If a country doesn't use a national prefix, and this number doesn't have an Italian leading |
||
622 | 296 | // zero, we assume it is a closed dialling plan with no area codes. |
|
623 | if (!$metadata->hasNationalPrefix() && !$number->isItalianLeadingZero()) { |
||
|
|||
624 | return 0; |
||
625 | 296 | } |
|
626 | |||
627 | $type = $this->getNumberType($number); |
||
628 | $countryCallingCode = $number->getCountryCode(); |
||
629 | |||
630 | if ($type === PhoneNumberType::MOBILE |
||
631 | // Note this is a rough heuristic; it doesn't cover Indonesia well, for example, where area |
||
632 | // codes are present for some mobile phones but not for others. We have no better way of |
||
633 | // representing this in the metadata at this point. |
||
634 | && in_array($countryCallingCode, self::$GEO_MOBILE_COUNTRIES_WITHOUT_MOBILE_AREA_CODES) |
||
635 | ) { |
||
636 | 2 | return 0; |
|
637 | } |
||
638 | 2 | ||
639 | if (!$this->isNumberGeographical($type, $countryCallingCode)) { |
||
640 | return 0; |
||
641 | } |
||
642 | |||
643 | return $this->getLengthOfNationalDestinationCode($number); |
||
644 | } |
||
645 | |||
646 | /** |
||
647 | * Returns the metadata for the given region code or {@code null} if the region code is invalid |
||
648 | * or unknown. |
||
649 | 542 | * @param string $regionCode |
|
650 | * @return PhoneMetadata |
||
651 | */ |
||
652 | 542 | public function getMetadataForRegion($regionCode) |
|
653 | 3 | { |
|
654 | if (!$this->isValidRegionCode($regionCode)) { |
||
655 | 542 | return null; |
|
656 | } |
||
657 | 429 | ||
658 | return $this->metadataSource->getMetadataForRegion($regionCode); |
||
659 | } |
||
660 | |||
661 | 542 | /** |
|
662 | * Helper function to check region code is not unknown or null. |
||
663 | * @param string $regionCode |
||
664 | * @return bool |
||
665 | */ |
||
666 | protected function isValidRegionCode($regionCode) |
||
670 | |||
671 | /** |
||
672 | * Returns the region where a phone number is from. This could be used for geocoding at the region |
||
673 | * level. |
||
674 | * |
||
675 | * @param PhoneNumber $number the phone number whose origin we want to know |
||
676 | * @return null|string the region where the phone number is from, or null if no region matches this calling |
||
677 | * code |
||
678 | */ |
||
679 | public function getRegionCodeForNumber(PhoneNumber $number) |
||
680 | 7 | { |
|
681 | $countryCode = $number->getCountryCode(); |
||
682 | 7 | if (!isset($this->countryCallingCodeToRegionCodeMap[$countryCode])) { |
|
683 | 58 | return null; |
|
684 | } |
||
685 | $regions = $this->countryCallingCodeToRegionCodeMap[$countryCode]; |
||
686 | 43 | if (count($regions) == 1) { |
|
687 | 5 | return $regions[0]; |
|
688 | 30 | } else { |
|
689 | 34 | return $this->getRegionCodeForNumberFromRegionList($number, $regions); |
|
690 | 126 | } |
|
691 | } |
||
692 | |||
693 | /** |
||
694 | * @param PhoneNumber $number |
||
695 | * @param array $regionCodes |
||
696 | * @return null|string |
||
697 | */ |
||
698 | protected function getRegionCodeForNumberFromRegionList(PhoneNumber $number, array $regionCodes) |
||
699 | 247 | { |
|
700 | $nationalNumber = $this->getNationalSignificantNumber($number); |
||
701 | foreach ($regionCodes as $regionCode) { |
||
702 | 247 | // If leadingDigits is present, use this. Otherwise, do full validation. |
|
703 | // Metadata cannot be null because the region codes come from the country calling code map. |
||
704 | $metadata = $this->getMetadataForRegion($regionCode); |
||
705 | 10 | if ($metadata->hasLeadingDigits()) { |
|
706 | $nbMatches = preg_match( |
||
707 | '/' . $metadata->getLeadingDigits() . '/', |
||
708 | 247 | $nationalNumber, |
|
709 | 247 | $matches, |
|
710 | PREG_OFFSET_CAPTURE |
||
711 | ); |
||
712 | if ($nbMatches > 0 && $matches[0][1] === 0) { |
||
713 | return $regionCode; |
||
714 | } |
||
715 | } elseif ($this->getNumberTypeHelper($nationalNumber, $metadata) != PhoneNumberType::UNKNOWN) { |
||
716 | 219 | return $regionCode; |
|
717 | } |
||
718 | } |
||
719 | 180 | return null; |
|
720 | } |
||
721 | |||
722 | 3 | /** |
|
723 | * Gets the national significant number of the a phone number. Note a national significant number |
||
724 | * doesn't contain a national prefix or any formatting. |
||
725 | 7 | * |
|
726 | * @param PhoneNumber $number the phone number for which the national significant number is needed |
||
727 | * @return string the national significant number of the PhoneNumber object passed in |
||
728 | */ |
||
729 | public function getNationalSignificantNumber(PhoneNumber $number) |
||
740 | |||
741 | /** |
||
742 | 3 | * @param string $nationalNumber |
|
743 | * @param PhoneMetadata $metadata |
||
744 | * @return int PhoneNumberType constant |
||
745 | */ |
||
746 | protected function getNumberTypeHelper($nationalNumber, PhoneMetadata $metadata) |
||
747 | { |
||
748 | 58 | if (!$this->isNumberMatchingDesc($nationalNumber, $metadata->getGeneralDesc())) { |
|
749 | return PhoneNumberType::UNKNOWN; |
||
750 | } |
||
751 | if ($this->isNumberMatchingDesc($nationalNumber, $metadata->getPremiumRate())) { |
||
795 | |||
796 | /** |
||
797 | * @param string $nationalNumber |
||
798 | 179 | * @param PhoneNumberDesc $numberDesc |
|
799 | * @return bool |
||
800 | */ |
||
801 | public function isNumberMatchingDesc($nationalNumber, PhoneNumberDesc $numberDesc) |
||
802 | { |
||
803 | 179 | // Check if any possible number lengths are present; if so, we use them to avoid checking the |
|
804 | // validation pattern if they don't match. If they are absent, this means they match the general |
||
805 | // description, which we have already checked before checking a specific number type. |
||
806 | $actualLength = mb_strlen($nationalNumber); |
||
807 | $possibleLengths = $numberDesc->getPossibleLength(); |
||
808 | if (count($possibleLengths) > 0 && !in_array($actualLength, $possibleLengths)) { |
||
809 | return false; |
||
810 | } |
||
811 | |||
812 | $nationalNumberPatternMatcher = new Matcher($numberDesc->getNationalNumberPattern(), $nationalNumber); |
||
813 | |||
814 | return $nationalNumberPatternMatcher->matches(); |
||
815 | } |
||
816 | |||
817 | /** |
||
818 | * isNumberGeographical(PhoneNumber) |
||
819 | * |
||
820 | * Tests whether a phone number has a geographical association. It checks if the number is |
||
821 | * associated to a certain region in the country where it belongs to. Note that this doesn't |
||
822 | * verify if the number is actually in use. |
||
823 | * |
||
824 | * isNumberGeographical(PhoneNumberType, $countryCallingCode) |
||
825 | * |
||
826 | * Tests whether a phone number has a geographical association, as represented by its type and the |
||
827 | 1331 | * country it belongs to. |
|
828 | * |
||
829 | * This version exists since calculating the phone number type is expensive; if we have already |
||
830 | * done this, we don't want to do it again. |
||
831 | 1331 | * |
|
832 | 7 | * @param PhoneNumber|int $phoneNumberObjOrType A PhoneNumber object, or a PhoneNumberType integer |
|
833 | * @param int|null $countryCallingCode Used when passing a PhoneNumberType |
||
834 | * @return bool |
||
835 | */ |
||
836 | 1331 | public function isNumberGeographical($phoneNumberObjOrType, $countryCallingCode = null) |
|
837 | { |
||
838 | if ($phoneNumberObjOrType instanceof PhoneNumber) { |
||
839 | return $this->isNumberGeographical($this->getNumberType($phoneNumberObjOrType), $phoneNumberObjOrType->getCountryCode()); |
||
840 | } |
||
841 | |||
842 | return $phoneNumberObjOrType == PhoneNumberType::FIXED_LINE |
||
843 | 258 | || $phoneNumberObjOrType == PhoneNumberType::FIXED_LINE_OR_MOBILE |
|
844 | || (in_array($countryCallingCode, static::$GEO_MOBILE_COUNTRIES) |
||
845 | 258 | && $phoneNumberObjOrType == PhoneNumberType::MOBILE); |
|
846 | } |
||
847 | |||
848 | /** |
||
849 | * Gets the type of a phone number. |
||
850 | * @param PhoneNumber $number the number the phone number that we want to know the type |
||
851 | * @return int PhoneNumberType the type of the phone number |
||
852 | */ |
||
853 | 10 | public function getNumberType(PhoneNumber $number) |
|
854 | { |
||
855 | 10 | $regionCode = $this->getRegionCodeForNumber($number); |
|
856 | $metadata = $this->getMetadataForRegionOrCallingCode($number->getCountryCode(), $regionCode); |
||
857 | if ($metadata === null) { |
||
858 | return PhoneNumberType::UNKNOWN; |
||
859 | } |
||
860 | $nationalSignificantNumber = $this->getNationalSignificantNumber($number); |
||
861 | return $this->getNumberTypeHelper($nationalSignificantNumber, $metadata); |
||
862 | } |
||
863 | |||
864 | /** |
||
865 | * @param int $countryCallingCode |
||
866 | * @param string $regionCode |
||
867 | * @return PhoneMetadata |
||
868 | */ |
||
869 | protected function getMetadataForRegionOrCallingCode($countryCallingCode, $regionCode) |
||
870 | { |
||
871 | return static::REGION_CODE_FOR_NON_GEO_ENTITY === $regionCode ? |
||
872 | $this->getMetadataForNonGeographicalRegion($countryCallingCode) : $this->getMetadataForRegion($regionCode); |
||
873 | } |
||
874 | |||
875 | /** |
||
876 | * @param int $countryCallingCode |
||
877 | * @return PhoneMetadata |
||
878 | */ |
||
879 | public function getMetadataForNonGeographicalRegion($countryCallingCode) |
||
880 | { |
||
881 | if (!isset($this->countryCallingCodeToRegionCodeMap[$countryCallingCode])) { |
||
882 | return null; |
||
883 | } |
||
884 | return $this->metadataSource->getMetadataForNonGeographicalRegion($countryCallingCode); |
||
885 | } |
||
886 | |||
887 | /** |
||
888 | * Gets the length of the national destination code (NDC) from the PhoneNumber object passed in, |
||
889 | * so that clients could use it to split a national significant number into NDC and subscriber |
||
890 | * number. The NDC of a phone number is normally the first group of digit(s) right after the |
||
891 | * country calling code when the number is formatted in the international format, if there is a |
||
892 | * subscriber number part that follows. An example of how this could be used: |
||
893 | * |
||
894 | * <code> |
||
895 | * $phoneUtil = PhoneNumberUtil::getInstance(); |
||
896 | * $number = $phoneUtil->parse("18002530000", "US"); |
||
897 | * $nationalSignificantNumber = $phoneUtil->getNationalSignificantNumber($number); |
||
898 | * |
||
899 | * $nationalDestinationCodeLength = $phoneUtil->getLengthOfNationalDestinationCode($number); |
||
900 | * if ($nationalDestinationCodeLength > 0) { |
||
901 | * $nationalDestinationCode = substr($nationalSignificantNumber, 0, $nationalDestinationCodeLength); |
||
902 | * $subscriberNumber = substr($nationalSignificantNumber, $nationalDestinationCodeLength); |
||
903 | * } else { |
||
904 | * $nationalDestinationCode = ""; |
||
905 | * $subscriberNumber = $nationalSignificantNumber; |
||
906 | * } |
||
907 | * </code> |
||
908 | * |
||
909 | * Refer to the unit tests to see the difference between this function and |
||
910 | * {@link #getLengthOfGeographicalAreaCode}. |
||
911 | * |
||
912 | * @param PhoneNumber $number the PhoneNumber object for which clients want to know the length of the NDC. |
||
913 | * @return int the length of NDC of the PhoneNumber object passed in. |
||
914 | */ |
||
915 | public function getLengthOfNationalDestinationCode(PhoneNumber $number) |
||
952 | |||
953 | /** |
||
954 | 260 | * Formats a phone number in the specified format using default rules. Note that this does not |
|
955 | 260 | * promise to produce a phone number that the user can dial from where they are - although we do |
|
956 | * format in either 'national' or 'international' format depending on what the client asks for, we |
||
957 | * do not currently support a more abbreviated format, such as for users in the same "area" who |
||
958 | 260 | * could potentially dial the number without area code. Note that if the phone number has a |
|
959 | * country calling code of 0 or an otherwise invalid country calling code, we cannot work out |
||
960 | * which formatting rules to apply so we return the national significant number with no formatting |
||
961 | 259 | * applied. |
|
962 | * |
||
963 | * @param PhoneNumber $number the phone number to be formatted |
||
964 | 1 | * @param int $numberFormat the PhoneNumberFormat the phone number should be formatted into |
|
965 | * @return string the formatted phone number |
||
966 | */ |
||
967 | public function format(PhoneNumber $number, $numberFormat) |
||
968 | { |
||
969 | if ($number->getNationalNumber() == 0 && $number->hasRawInput()) { |
||
970 | // Unparseable numbers that kept their raw input just use that. |
||
971 | // This is the only case where a number can be formatted as E164 without a |
||
972 | // leading '+' symbol (but the original number wasn't parseable anyway). |
||
973 | // TODO: Consider removing the 'if' above so that unparseable |
||
974 | // strings without raw input format to the empty string instead of "+00" |
||
975 | 260 | $rawInput = $number->getRawInput(); |
|
976 | if (mb_strlen($rawInput) > 0) { |
||
977 | 260 | return $rawInput; |
|
978 | 260 | } |
|
979 | } |
||
980 | $metadata = null; |
||
981 | $formattedNumber = ""; |
||
982 | $countryCallingCode = $number->getCountryCode(); |
||
983 | $nationalSignificantNumber = $this->getNationalSignificantNumber($number); |
||
984 | if ($numberFormat == PhoneNumberFormat::E164) { |
||
985 | // Early exit for E164 case (even if the country calling code is invalid) since no formatting |
||
986 | 259 | // of the national number needs to be applied. Extensions are not formatted. |
|
987 | $formattedNumber .= $nationalSignificantNumber; |
||
988 | $this->prefixNumberWithCountryCallingCode($countryCallingCode, PhoneNumberFormat::E164, $formattedNumber); |
||
989 | 259 | } elseif (!$this->hasValidCountryCallingCode($countryCallingCode)) { |
|
990 | 259 | $formattedNumber .= $nationalSignificantNumber; |
|
991 | 259 | } else { |
|
992 | 20 | // Note getRegionCodeForCountryCode() is used because formatting information for regions which |
|
993 | 5 | // share a country calling code is contained by only one region for performance reasons. For |
|
994 | 5 | // example, for NANPA regions it will be contained in the metadata for US. |
|
995 | 25 | $regionCode = $this->getRegionCodeForCountryCode($countryCallingCode); |
|
996 | 4 | // Metadata cannot be null because the country calling code is valid (which means that the |
|
997 | 4 | // region code cannot be ZZ and must be one of our supported region codes). |
|
998 | 25 | $metadata = $this->getMetadataForRegionOrCallingCode($countryCallingCode, $regionCode); |
|
999 | $formattedNumber .= $this->formatNsn($nationalSignificantNumber, $metadata, $numberFormat); |
||
1000 | 25 | $this->prefixNumberWithCountryCallingCode($countryCallingCode, $numberFormat, $formattedNumber); |
|
1001 | } |
||
1002 | $this->maybeAppendFormattedExtension($number, $metadata, $numberFormat, $formattedNumber); |
||
1003 | return $formattedNumber; |
||
1004 | } |
||
1005 | |||
1006 | /** |
||
1007 | * A helper function that is used by format and formatByPattern. |
||
1008 | * @param int $countryCallingCode |
||
1009 | 21 | * @param int $numberFormat PhoneNumberFormat |
|
1010 | * @param string $formattedNumber |
||
1011 | 21 | */ |
|
1012 | protected function prefixNumberWithCountryCallingCode($countryCallingCode, $numberFormat, &$formattedNumber) |
||
1013 | { |
||
1014 | switch ($numberFormat) { |
||
1015 | case PhoneNumberFormat::E164: |
||
1016 | $formattedNumber = static::PLUS_SIGN . $countryCallingCode . $formattedNumber; |
||
1017 | return; |
||
1018 | case PhoneNumberFormat::INTERNATIONAL: |
||
1019 | $formattedNumber = static::PLUS_SIGN . $countryCallingCode . " " . $formattedNumber; |
||
1020 | return; |
||
1021 | case PhoneNumberFormat::RFC3966: |
||
1022 | $formattedNumber = static::RFC3966_PREFIX . static::PLUS_SIGN . $countryCallingCode . "-" . $formattedNumber; |
||
1023 | return; |
||
1024 | case PhoneNumberFormat::NATIONAL: |
||
1025 | 293 | default: |
|
1026 | return; |
||
1027 | 293 | } |
|
1028 | 293 | } |
|
1029 | |||
1030 | /** |
||
1031 | * Helper function to check the country calling code is valid. |
||
1032 | * @param int $countryCallingCode |
||
1033 | * @return bool |
||
1034 | */ |
||
1035 | protected function hasValidCountryCallingCode($countryCallingCode) |
||
1036 | { |
||
1037 | return isset($this->countryCallingCodeToRegionCodeMap[$countryCallingCode]); |
||
1038 | } |
||
1039 | |||
1040 | /** |
||
1041 | * Returns the region code that matches the specific country calling code. In the case of no |
||
1042 | 23 | * region code being found, ZZ will be returned. In the case of multiple regions, the one |
|
1043 | * designated in the metadata as the "main" region for this calling code will be returned. If the |
||
1044 | * countryCallingCode entered is valid but doesn't match a specific region (such as in the case of |
||
1045 | * non-geographical calling codes like 800) the value "001" will be returned (corresponding to |
||
1046 | * the value for World in the UN M.49 schema). |
||
1047 | * |
||
1048 | 23 | * @param int $countryCallingCode |
|
1049 | 21 | * @return string |
|
1050 | */ |
||
1051 | 21 | public function getRegionCodeForCountryCode($countryCallingCode) |
|
1052 | { |
||
1053 | $regionCodes = isset($this->countryCallingCodeToRegionCodeMap[$countryCallingCode]) ? $this->countryCallingCodeToRegionCodeMap[$countryCallingCode] : null; |
||
1054 | 21 | return $regionCodes === null ? static::UNKNOWN_REGION : $regionCodes[0]; |
|
1055 | } |
||
1056 | |||
1057 | /** |
||
1058 | * Note in some regions, the national number can be written in two completely different ways |
||
1059 | * depending on whether it forms part of the NATIONAL format or INTERNATIONAL format. The |
||
1060 | * numberFormat parameter here is used to specify which format to use for those cases. If a |
||
1061 | 22 | * carrierCode is specified, this will be inserted into the formatted string to replace $CC. |
|
1062 | * @param string $number |
||
1063 | * @param PhoneMetadata $metadata |
||
1064 | 10 | * @param int $numberFormat PhoneNumberFormat |
|
1065 | * @param null|string $carrierCode |
||
1066 | * @return string |
||
1067 | 10 | */ |
|
1068 | protected function formatNsn($number, PhoneMetadata $metadata, $numberFormat, $carrierCode = null) |
||
1081 | 21 | ||
1082 | /** |
||
1083 | * @param NumberFormat[] $availableFormats |
||
1084 | * @param string $nationalNumber |
||
1085 | * @return NumberFormat|null |
||
1086 | */ |
||
1087 | public function chooseFormattingPatternForNumber(array $availableFormats, $nationalNumber) |
||
1088 | { |
||
1089 | foreach ($availableFormats as $numFormat) { |
||
1090 | $leadingDigitsPatternMatcher = null; |
||
1091 | $size = $numFormat->leadingDigitsPatternSize(); |
||
1092 | 22 | // We always use the last leading_digits_pattern, as it is the most detailed. |
|
1093 | if ($size > 0) { |
||
1094 | $leadingDigitsPatternMatcher = new Matcher( |
||
1095 | $numFormat->getLeadingDigitsPattern($size - 1), |
||
1096 | $nationalNumber |
||
1097 | ); |
||
1098 | } |
||
1099 | if ($size == 0 || $leadingDigitsPatternMatcher->lookingAt()) { |
||
1100 | 22 | $m = new Matcher($numFormat->getPattern(), $nationalNumber); |
|
1101 | 22 | if ($m->matches() > 0) { |
|
1102 | return $numFormat; |
||
1103 | } |
||
1104 | } |
||
1105 | } |
||
1106 | return null; |
||
1107 | } |
||
1108 | |||
1109 | /** |
||
1110 | * Note that carrierCode is optional - if null or an empty string, no carrier code replacement |
||
1111 | * will take place. |
||
1112 | * @param string $nationalNumber |
||
1113 | * @param NumberFormat $formattingPattern |
||
1114 | * @param int $numberFormat PhoneNumberFormat |
||
1115 | * @param null|string $carrierCode |
||
1116 | 22 | * @return string |
|
1117 | 22 | */ |
|
1118 | protected function formatNsnUsingPattern( |
||
1119 | $nationalNumber, |
||
1120 | NumberFormat $formattingPattern, |
||
1121 | $numberFormat, |
||
1122 | 11 | $carrierCode = null |
|
1123 | ) { |
||
1124 | $numberFormatRule = $formattingPattern->getFormat(); |
||
1125 | $m = new Matcher($formattingPattern->getPattern(), $nationalNumber); |
||
1126 | 11 | if ($numberFormat === PhoneNumberFormat::NATIONAL && |
|
1127 | 1 | $carrierCode !== null && mb_strlen($carrierCode) > 0 && |
|
1128 | 22 | mb_strlen($formattingPattern->getDomesticCarrierCodeFormattingRule()) > 0 |
|
1129 | ) { |
||
1130 | // Replace the $CC in the formatting rule with the desired carrier code. |
||
1131 | $carrierCodeFormattingRule = $formattingPattern->getDomesticCarrierCodeFormattingRule(); |
||
1132 | $ccPatternMatcher = new Matcher(static::CC_PATTERN, $carrierCodeFormattingRule); |
||
1133 | $carrierCodeFormattingRule = $ccPatternMatcher->replaceFirst($carrierCode); |
||
1134 | // Now replace the $FG in the formatting rule with the first group and the carrier code |
||
1135 | // combined in the appropriate way. |
||
1136 | $firstGroupMatcher = new Matcher(static::FIRST_GROUP_PATTERN, $numberFormatRule); |
||
1137 | 22 | $numberFormatRule = $firstGroupMatcher->replaceFirst($carrierCodeFormattingRule); |
|
1138 | 22 | $formattedNationalNumber = $m->replaceAll($numberFormatRule); |
|
1139 | } else { |
||
1140 | // Use the national prefix formatting rule instead. |
||
1141 | $nationalPrefixFormattingRule = $formattingPattern->getNationalPrefixFormattingRule(); |
||
1142 | if ($numberFormat == PhoneNumberFormat::NATIONAL && |
||
1143 | $nationalPrefixFormattingRule !== null && |
||
1144 | mb_strlen($nationalPrefixFormattingRule) > 0 |
||
1145 | ) { |
||
1146 | $firstGroupMatcher = new Matcher(static::FIRST_GROUP_PATTERN, $numberFormatRule); |
||
1147 | $formattedNationalNumber = $m->replaceAll( |
||
1148 | $firstGroupMatcher->replaceFirst($nationalPrefixFormattingRule) |
||
1149 | 1 | ); |
|
1150 | } else { |
||
1151 | $formattedNationalNumber = $m->replaceAll($numberFormatRule); |
||
1152 | } |
||
1153 | } |
||
1154 | if ($numberFormat == PhoneNumberFormat::RFC3966) { |
||
1155 | // Strip any leading punctuation. |
||
1156 | $matcher = new Matcher(static::$SEPARATOR_PATTERN, $formattedNationalNumber); |
||
1157 | if ($matcher->lookingAt()) { |
||
1158 | $formattedNationalNumber = $matcher->replaceFirst(""); |
||
1159 | 1 | } |
|
1160 | 1 | // Replace the rest with a dash between each number group. |
|
1161 | $formattedNationalNumber = $matcher->reset($formattedNationalNumber)->replaceAll("-"); |
||
1162 | } |
||
1163 | return $formattedNationalNumber; |
||
1164 | } |
||
1165 | |||
1166 | /** |
||
1167 | * Appends the formatted extension of a phone number to formattedNumber, if the phone number had |
||
1168 | * an extension specified. |
||
1169 | * |
||
1170 | * @param PhoneNumber $number |
||
1171 | * @param PhoneMetadata|null $metadata |
||
1172 | 9 | * @param int $numberFormat PhoneNumberFormat |
|
1173 | * @param string $formattedNumber |
||
1174 | */ |
||
1175 | 3 | protected function maybeAppendFormattedExtension(PhoneNumber $number, $metadata, $numberFormat, &$formattedNumber) |
|
1176 | { |
||
1177 | 9 | if ($number->hasExtension() && mb_strlen($number->getExtension()) > 0) { |
|
1178 | if ($numberFormat === PhoneNumberFormat::RFC3966) { |
||
1179 | $formattedNumber .= static::RFC3966_EXTN_PREFIX . $number->getExtension(); |
||
1180 | } else { |
||
1181 | if (!empty($metadata) && $metadata->hasPreferredExtnPrefix()) { |
||
1182 | $formattedNumber .= $metadata->getPreferredExtnPrefix() . $number->getExtension(); |
||
1183 | } else { |
||
1184 | $formattedNumber .= static::DEFAULT_EXTN_PREFIX . $number->getExtension(); |
||
1185 | } |
||
1186 | } |
||
1187 | } |
||
1188 | } |
||
1189 | |||
1190 | /** |
||
1191 | * Returns the mobile token for the provided country calling code if it has one, otherwise |
||
1192 | * returns an empty string. A mobile token is a number inserted before the area code when dialing |
||
1193 | * a mobile number from that country from abroad. |
||
1194 | * |
||
1195 | * @param int $countryCallingCode the country calling code for which we want the mobile token |
||
1196 | * @return string the mobile token, as a string, for the given country calling code |
||
1197 | */ |
||
1198 | public static function getCountryMobileToken($countryCallingCode) |
||
1199 | { |
||
1200 | if (array_key_exists($countryCallingCode, static::$MOBILE_TOKEN_MAPPINGS)) { |
||
1201 | return static::$MOBILE_TOKEN_MAPPINGS[$countryCallingCode]; |
||
1202 | } |
||
1203 | return ""; |
||
1204 | } |
||
1205 | |||
1206 | /** |
||
1207 | * Checks if the number is a valid vanity (alpha) number such as 800 MICROSOFT. A valid vanity |
||
1208 | * number will start with at least 3 digits and will have three or more alpha characters. This |
||
1209 | * does not do region-specific checks - to work out if this number is actually valid for a region, |
||
1210 | 2204 | * it should be parsed and methods such as {@link #isPossibleNumberWithReason} and |
|
1211 | * {@link #isValidNumber} should be used. |
||
1212 | * |
||
1213 | 2 | * @param string $number the number that needs to be checked |
|
1214 | * @return bool true if the number is a valid vanity number |
||
1215 | */ |
||
1216 | public function isAlphaNumber($number) |
||
1217 | { |
||
1218 | if (!$this->isViablePhoneNumber($number)) { |
||
1219 | 2204 | // Number is too short, or doesn't match the basic phone number pattern. |
|
1220 | return false; |
||
1221 | } |
||
1222 | $this->maybeStripExtension($number); |
||
1223 | return (bool)preg_match('/' . static::VALID_ALPHA_PHONE_PATTERN . '/' . static::REGEX_FLAGS, $number); |
||
1224 | } |
||
1225 | |||
1226 | /** |
||
1227 | 2204 | * Checks to see if the string of characters could possibly be a phone number at all. At the |
|
1228 | * moment, checks to see that the string begins with at least 2 digits, ignoring any punctuation |
||
1229 | 2204 | * commonly found in phone numbers. |
|
1230 | * This method does not require the number to be normalized in advance - but does assume that |
||
1231 | * leading non-number symbols have been removed, such as by the method extractPossibleNumber. |
||
1232 | * |
||
1233 | * @param string $number to be checked for viability as a phone number |
||
1234 | * @return boolean true if the number could be a phone number of some sort, otherwise false |
||
1235 | */ |
||
1236 | public static function isViablePhoneNumber($number) |
||
1247 | |||
1248 | /** |
||
1249 | * We append optionally the extension pattern to the end here, as a valid phone number may |
||
1250 | * have an extension prefix appended, followed by 1 or more digits. |
||
1251 | * @return string |
||
1252 | 1 | */ |
|
1253 | protected static function getValidPhoneNumberPattern() |
||
1254 | 1 | { |
|
1255 | return static::$VALID_PHONE_NUMBER_PATTERN; |
||
1256 | } |
||
1257 | |||
1258 | 2203 | /** |
|
1259 | * Strips any extension (as in, the part of the number dialled after the call is connected, |
||
1260 | * usually indicated with extn, ext, x or similar) from the end of the number, and returns it. |
||
1261 | * |
||
1262 | * @param string $number the non-normalized telephone number that we wish to strip the extension from |
||
1263 | * @return string the phone extension |
||
1264 | */ |
||
1265 | protected function maybeStripExtension(&$number) |
||
1266 | { |
||
1267 | $matches = array(); |
||
1268 | $find = preg_match(static::$EXTN_PATTERN, $number, $matches, PREG_OFFSET_CAPTURE); |
||
1269 | // If we find a potential extension, and the number preceding this is a viable number, we assume |
||
1270 | // it is an extension. |
||
1271 | if ($find > 0 && $this->isViablePhoneNumber(substr($number, 0, $matches[0][1]))) { |
||
1272 | // The numbers are captured into groups in the regular expression. |
||
1273 | |||
1274 | for ($i = 1, $length = count($matches); $i <= $length; $i++) { |
||
1275 | if ($matches[$i][0] != "") { |
||
1276 | // We go through the capturing groups until we find one that captured some digits. If none |
||
1277 | // did, then we will return the empty string. |
||
1278 | $extension = $matches[$i][0]; |
||
1279 | $number = substr($number, 0, $matches[0][1]); |
||
1280 | return $extension; |
||
1281 | } |
||
1282 | } |
||
1283 | } |
||
1284 | return ""; |
||
1285 | } |
||
1286 | |||
1287 | /** |
||
1288 | * Parses a string and returns it in proto buffer format. This method differs from {@link #parse} |
||
1289 | * in that it always populates the raw_input field of the protocol buffer with numberToParse as |
||
1290 | 31 | * well as the country_code_source field. |
|
1291 | * |
||
1292 | * @param string $numberToParse number that we are attempting to parse. This can contain formatting |
||
1293 | * such as +, ( and -, as well as a phone number extension. It can also |
||
1294 | 31 | * be provided in RFC3966 format. |
|
1295 | * @param string $defaultRegion region that we are expecting the number to be from. This is only used |
||
1296 | * if the number being parsed is not written in international format. |
||
1297 | * The country calling code for the number in this case would be stored |
||
1298 | * as that of the default region supplied. |
||
1299 | 3 | * @param PhoneNumber $phoneNumber |
|
1300 | * @return PhoneNumber a phone number proto buffer filled with the parsed number |
||
1301 | */ |
||
1302 | 31 | public function parseAndKeepRawInput($numberToParse, $defaultRegion, PhoneNumber $phoneNumber = null) |
|
1303 | { |
||
1304 | if ($phoneNumber === null) { |
||
1305 | $phoneNumber = new PhoneNumber(); |
||
1306 | } |
||
1307 | $this->parseHelper($numberToParse, $defaultRegion, true, true, $phoneNumber); |
||
1308 | return $phoneNumber; |
||
1309 | } |
||
1310 | |||
1311 | /** |
||
1312 | * A helper function to set the values related to leading zeros in a PhoneNumber. |
||
1313 | * @param string $nationalNumber |
||
1314 | * @param PhoneNumber $phoneNumber |
||
1315 | */ |
||
1316 | public static function setItalianLeadingZerosForPhoneNumber($nationalNumber, PhoneNumber $phoneNumber) |
||
1317 | { |
||
1318 | if (strlen($nationalNumber) > 1 && substr($nationalNumber, 0, 1) == '0') { |
||
1319 | $phoneNumber->setItalianLeadingZero(true); |
||
1320 | 2424 | $numberOfLeadingZeros = 1; |
|
1321 | // Note that if the national number is all "0"s, the last "0" is not counted as a leading |
||
1322 | 2205 | // zero. |
|
1323 | while ($numberOfLeadingZeros < (strlen($nationalNumber) - 1) && |
||
1324 | substr($nationalNumber, $numberOfLeadingZeros, 1) == '0') { |
||
1325 | $numberOfLeadingZeros++; |
||
1326 | } |
||
1327 | |||
1328 | if ($numberOfLeadingZeros != 1) { |
||
1329 | $phoneNumber->setNumberOfLeadingZeros($numberOfLeadingZeros); |
||
1330 | } |
||
1331 | } |
||
1332 | } |
||
1333 | |||
1334 | /** |
||
1335 | 2204 | * Parses a string and fills up the phoneNumber. This method is the same as the public |
|
1336 | * parse() method, with the exception that it allows the default region to be null, for use by |
||
1337 | * isNumberMatch(). checkRegion should be set to false if it is permitted for the default region |
||
1338 | * to be null or unknown ("ZZ"). |
||
1339 | * @param string $numberToParse |
||
1340 | 2 | * @param string $defaultRegion |
|
1341 | 2 | * @param bool $keepRawInput |
|
1342 | * @param bool $checkRegion |
||
1343 | * @param PhoneNumber $phoneNumber |
||
1344 | * @throws NumberParseException |
||
1345 | */ |
||
1346 | protected function parseHelper($numberToParse, $defaultRegion, $keepRawInput, $checkRegion, PhoneNumber $phoneNumber) |
||
1347 | { |
||
1348 | if ($numberToParse === null) { |
||
1349 | 1 | throw new NumberParseException(NumberParseException::NOT_A_NUMBER, "The phone number supplied was null."); |
|
1350 | 1 | } |
|
1351 | |||
1352 | $numberToParse = trim($numberToParse); |
||
1353 | |||
1354 | 2203 | if (mb_strlen($numberToParse) > static::MAX_INPUT_STRING_LENGTH) { |
|
1355 | throw new NumberParseException( |
||
1356 | NumberParseException::TOO_LONG, |
||
1357 | "The string supplied was too long to parse." |
||
1358 | ); |
||
1359 | } |
||
1360 | |||
1361 | $nationalNumber = ''; |
||
1362 | $this->buildNationalNumberForParsing($numberToParse, $nationalNumber); |
||
1363 | |||
1364 | if (!$this->isViablePhoneNumber($nationalNumber)) { |
||
1365 | throw new NumberParseException( |
||
1366 | NumberParseException::NOT_A_NUMBER, |
||
1367 | 2203 | "The string supplied did not seem to be a phone number." |
|
1368 | ); |
||
1369 | } |
||
1370 | |||
1371 | // Check the region supplied is valid, or that the extracted number starts with some sort of + |
||
1372 | 2203 | // sign so the number's region can be determined. |
|
1373 | if ($checkRegion && !$this->checkRegionForParsing($nationalNumber, $defaultRegion)) { |
||
1374 | throw new NumberParseException( |
||
1375 | NumberParseException::INVALID_COUNTRY_CODE, |
||
1376 | "Missing or invalid default region." |
||
1377 | ); |
||
1378 | } |
||
1379 | |||
1380 | if ($keepRawInput) { |
||
1381 | $phoneNumber->setRawInput($numberToParse); |
||
1382 | } |
||
1383 | // Attempt to parse extension first, since it doesn't require region-specific data and we want |
||
1384 | // to have the non-normalised number here. |
||
1385 | $extension = $this->maybeStripExtension($nationalNumber); |
||
1386 | if (mb_strlen($extension) > 0) { |
||
1387 | $phoneNumber->setExtension($extension); |
||
1388 | } |
||
1389 | |||
1390 | 1 | $regionMetadata = $this->getMetadataForRegion($defaultRegion); |
|
1391 | // Check to see if the number is given in international format so we know whether this number is |
||
1392 | 1 | // from the default region or not. |
|
1393 | 1 | $normalizedNationalNumber = ""; |
|
1394 | try { |
||
1395 | // TODO: This method should really just take in the string buffer that has already |
||
1396 | // been created, and just remove the prefix, rather than taking in a string and then |
||
1397 | // outputting a string buffer. |
||
1398 | $countryCode = $this->maybeExtractCountryCode( |
||
1399 | 2203 | $nationalNumber, |
|
1400 | 2203 | $regionMetadata, |
|
1401 | $normalizedNationalNumber, |
||
1402 | 271 | $keepRawInput, |
|
1403 | $phoneNumber |
||
1404 | ); |
||
1405 | } catch (NumberParseException $e) { |
||
1406 | $matcher = new Matcher(static::$PLUS_CHARS_PATTERN, $nationalNumber); |
||
1407 | if ($e->getErrorType() == NumberParseException::INVALID_COUNTRY_CODE && $matcher->lookingAt()) { |
||
1408 | // Strip the plus-char, and try again. |
||
1409 | $countryCode = $this->maybeExtractCountryCode( |
||
1410 | substr($nationalNumber, $matcher->end()), |
||
1411 | 2424 | $regionMetadata, |
|
1412 | $normalizedNationalNumber, |
||
1413 | $keepRawInput, |
||
1414 | $phoneNumber |
||
1415 | ); |
||
1416 | 2424 | if ($countryCode == 0) { |
|
1417 | 271 | throw new NumberParseException( |
|
1418 | NumberParseException::INVALID_COUNTRY_CODE, |
||
1419 | "Could not interpret numbers after plus-sign." |
||
1420 | 2 | ); |
|
1421 | 2 | } |
|
1422 | } else { |
||
1423 | throw new NumberParseException($e->getErrorType(), $e->getMessage(), $e); |
||
1424 | 2203 | } |
|
1425 | 2203 | } |
|
1426 | 2203 | if ($countryCode !== 0) { |
|
1427 | $phoneNumberRegion = $this->getRegionCodeForCountryCode($countryCode); |
||
1428 | if ($phoneNumberRegion != $defaultRegion) { |
||
1429 | // Metadata cannot be null because the country calling code is valid. |
||
1430 | $regionMetadata = $this->getMetadataForRegionOrCallingCode($countryCode, $phoneNumberRegion); |
||
1431 | } |
||
1432 | 1787 | } else { |
|
1433 | 1787 | // If no extracted country calling code, use the region supplied instead. The national number |
|
1434 | // is just the normalized version of the number we were given to parse. |
||
1435 | |||
1436 | $normalizedNationalNumber .= $this->normalize($nationalNumber); |
||
1437 | if ($defaultRegion !== null) { |
||
1438 | $countryCode = $regionMetadata->getCountryCode(); |
||
1439 | 2203 | $phoneNumber->setCountryCode($countryCode); |
|
1440 | } elseif ($keepRawInput) { |
||
1441 | $phoneNumber->clearCountryCodeSource(); |
||
1442 | } |
||
1443 | } |
||
1444 | if (mb_strlen($normalizedNationalNumber) < static::MIN_LENGTH_FOR_NSN) { |
||
1445 | 2203 | throw new NumberParseException( |
|
1446 | NumberParseException::TOO_SHORT_NSN, |
||
1447 | 1 | "The string supplied is too short to be a phone number." |
|
1448 | 1 | ); |
|
1449 | } |
||
1450 | if ($regionMetadata !== null) { |
||
1451 | $carrierCode = ""; |
||
1452 | $potentialNationalNumber = $normalizedNationalNumber; |
||
1453 | $this->maybeStripNationalPrefixAndCarrierCode($potentialNationalNumber, $regionMetadata, $carrierCode); |
||
1454 | // We require that the NSN remaining after stripping the national prefix and carrier code be |
||
1455 | // long enough to be a possible length for the region. Otherwise, we don't do the stripping, |
||
1456 | // since the original number could be a valid short number. |
||
1457 | if ($this->testNumberLength($potentialNationalNumber, $regionMetadata->getGeneralDesc()) !== ValidationResult::TOO_SHORT) { |
||
1458 | $normalizedNationalNumber = $potentialNationalNumber; |
||
1459 | if ($keepRawInput) { |
||
1460 | $phoneNumber->setPreferredDomesticCarrierCode($carrierCode); |
||
1461 | } |
||
1462 | 2202 | } |
|
1463 | 1 | } |
|
1464 | $lengthOfNationalNumber = mb_strlen($normalizedNationalNumber); |
||
1465 | if ($lengthOfNationalNumber < static::MIN_LENGTH_FOR_NSN) { |
||
1466 | 1 | throw new NumberParseException( |
|
1467 | NumberParseException::TOO_SHORT_NSN, |
||
1468 | "The string supplied is too short to be a phone number." |
||
1469 | 3 | ); |
|
1470 | } |
||
1471 | if ($lengthOfNationalNumber > static::MAX_LENGTH_FOR_NSN) { |
||
1472 | throw new NumberParseException( |
||
1473 | NumberParseException::TOO_LONG, |
||
1474 | "The string supplied is too long to be a phone number." |
||
1475 | ); |
||
1476 | } |
||
1477 | 2204 | $this->setItalianLeadingZerosForPhoneNumber($normalizedNationalNumber, $phoneNumber); |
|
1478 | |||
1479 | |||
1480 | 2204 | /* |
|
1481 | * We have to store the National Number as a string instead of a "long" as Google do |
||
1482 | * |
||
1483 | * Since PHP doesn't always support 64 bit INTs, this was a float, but that had issues |
||
1484 | * with long numbers. |
||
1485 | * |
||
1486 | * We have to remove the leading zeroes ourself though |
||
1487 | */ |
||
1488 | if ((int)$normalizedNationalNumber == 0) { |
||
1489 | 1 | $normalizedNationalNumber = "0"; |
|
1490 | } else { |
||
1491 | $normalizedNationalNumber = ltrim($normalizedNationalNumber, '0'); |
||
1492 | } |
||
1493 | 1 | ||
1494 | $phoneNumber->setNationalNumber($normalizedNationalNumber); |
||
1495 | } |
||
1496 | |||
1497 | /** |
||
1498 | * Converts numberToParse to a form that we can parse and write it to nationalNumber if it is |
||
1499 | * written in RFC3966; otherwise extract a possible number out of it and write to nationalNumber. |
||
1500 | * @param string $numberToParse |
||
1501 | * @param string $nationalNumber |
||
1502 | */ |
||
1503 | protected function buildNationalNumberForParsing($numberToParse, &$nationalNumber) |
||
1504 | { |
||
1505 | $indexOfPhoneContext = strpos($numberToParse, static::RFC3966_PHONE_CONTEXT); |
||
1506 | if ($indexOfPhoneContext > 0) { |
||
1507 | $phoneContextStart = $indexOfPhoneContext + mb_strlen(static::RFC3966_PHONE_CONTEXT); |
||
1508 | 1 | // If the phone context contains a phone number prefix, we need to capture it, whereas domains |
|
1509 | // will be ignored. |
||
1510 | if (substr($numberToParse, $phoneContextStart, 1) == static::PLUS_SIGN) { |
||
1511 | // Additional parameters might follow the phone context. If so, we will remove them here |
||
1512 | // because the parameters after phone context are not important for parsing the |
||
1513 | 2204 | // phone number. |
|
1514 | $phoneContextEnd = strpos($numberToParse, ';', $phoneContextStart); |
||
1515 | if ($phoneContextEnd > 0) { |
||
1516 | $nationalNumber .= substr($numberToParse, $phoneContextStart, $phoneContextEnd - $phoneContextStart); |
||
1517 | } else { |
||
1518 | $nationalNumber .= substr($numberToParse, $phoneContextStart); |
||
1519 | } |
||
1520 | 2204 | } |
|
1521 | |||
1522 | // Now append everything between the "tel:" prefix and the phone-context. This should include |
||
1523 | // the national number, an optional extension or isdn-subaddress component. Note we also |
||
1524 | // handle the case when "tel:" is missing, as we have seen in some of the phone number inputs. |
||
1525 | // In that case, we append everything from the beginning. |
||
1526 | |||
1527 | $indexOfRfc3966Prefix = strpos($numberToParse, static::RFC3966_PREFIX); |
||
1528 | $indexOfNationalNumber = ($indexOfRfc3966Prefix !== false) ? $indexOfRfc3966Prefix + strlen(static::RFC3966_PREFIX) : 0; |
||
1529 | $nationalNumber .= substr($numberToParse, $indexOfNationalNumber, ($indexOfPhoneContext - $indexOfNationalNumber)); |
||
1530 | } else { |
||
1531 | // Extract a possible number from the string passed in (this strips leading characters that |
||
1532 | // could not be the start of a phone number.) |
||
1533 | $nationalNumber .= $this->extractPossibleNumber($numberToParse); |
||
1534 | } |
||
1535 | |||
1536 | // Delete the isdn-subaddress and everything after it if it is present. Note extension won't |
||
1537 | 1970 | // appear at the same time with isdn-subaddress according to paragraph 5.3 of the RFC3966 spec, |
|
1538 | $indexOfIsdn = strpos($nationalNumber, static::RFC3966_ISDN_SUBADDRESS); |
||
1539 | 1970 | if ($indexOfIsdn > 0) { |
|
1540 | $nationalNumber = substr($nationalNumber, 0, $indexOfIsdn); |
||
1541 | 1970 | } |
|
1542 | // If both phone context and isdn-subaddress are absent but other parameters are present, the |
||
1543 | // parameters are left in nationalNumber. This is because we are concerned about deleting |
||
1544 | // content from a potential number string when there is no strong evidence that the number is |
||
1545 | // actually written in RFC3966. |
||
1546 | } |
||
1547 | |||
1548 | /** |
||
1549 | * Attempts to extract a possible number from the string passed in. This currently strips all |
||
1550 | * leading characters that cannot be used to start a phone number. Characters that can be used to |
||
1551 | 1970 | * start a phone number are defined in the VALID_START_CHAR_PATTERN. If none of these characters |
|
1552 | * are found in the number passed in, an empty string is returned. This function also attempts to |
||
1553 | * strip off any alternative extensions or endings if two or more are present, such as in the case |
||
1554 | * of: (530) 583-6985 x302/x2303. The second extension here makes this actually two phone numbers, |
||
1555 | 1970 | * (530) 583-6985 x302 and (530) 583-6985 x2303. We remove the second extension so that the first |
|
1556 | * number is parsed correctly. |
||
1557 | 3 | * |
|
1558 | * @param int $number the string that might contain a phone number |
||
1559 | * @return string the number, stripped of any non-phone-number prefix (such as "Tel:") or an empty |
||
1560 | * string if no character used to start phone numbers (such as + or any digit) is |
||
1561 | * found in the number |
||
1562 | */ |
||
1563 | public static function extractPossibleNumber($number) |
||
1564 | { |
||
1565 | $matches = array(); |
||
1566 | $match = preg_match('/' . static::$VALID_START_CHAR_PATTERN . '/ui', $number, $matches, PREG_OFFSET_CAPTURE); |
||
1567 | if ($match > 0) { |
||
1568 | $number = substr($number, $matches[0][1]); |
||
1569 | 2203 | // Remove trailing non-alpha non-numerical characters. |
|
1570 | $trailingCharsMatcher = new Matcher(static::$UNWANTED_END_CHAR_PATTERN, $number); |
||
1571 | if ($trailingCharsMatcher->find() && $trailingCharsMatcher->start() > 0) { |
||
1572 | $number = substr($number, 0, $trailingCharsMatcher->start()); |
||
1573 | } |
||
1574 | |||
1575 | 1 | // Check for extra numbers at the end. |
|
1576 | $match = preg_match('%' . static::$SECOND_NUMBER_START_PATTERN . '%', $number, $matches, PREG_OFFSET_CAPTURE); |
||
1577 | if ($match > 0) { |
||
1578 | 2203 | $number = substr($number, 0, $matches[0][1]); |
|
1579 | } |
||
1580 | |||
1581 | return $number; |
||
1582 | } else { |
||
1583 | return ""; |
||
1584 | } |
||
1585 | } |
||
1586 | |||
1587 | /** |
||
1588 | * Checks to see that the region code used is valid, or if it is not valid, that the number to |
||
1589 | * parse starts with a + symbol so that we can attempt to infer the region from the number. |
||
1590 | * Returns false if it cannot use the region provided and the region cannot be inferred. |
||
1591 | * @param string $numberToParse |
||
1592 | * @param string $defaultRegion |
||
1593 | * @return bool |
||
1594 | */ |
||
1595 | protected function checkRegionForParsing($numberToParse, $defaultRegion) |
||
1596 | { |
||
1597 | if (!$this->isValidRegionCode($defaultRegion)) { |
||
1598 | // If the number is null or empty, we can't infer the region. |
||
1599 | $plusCharsPatternMatcher = new Matcher(static::$PLUS_CHARS_PATTERN, $numberToParse); |
||
1600 | if ($numberToParse === null || mb_strlen($numberToParse) == 0 || !$plusCharsPatternMatcher->lookingAt()) { |
||
1601 | return false; |
||
1602 | } |
||
1603 | } |
||
1604 | return true; |
||
1605 | } |
||
1606 | |||
1607 | /** |
||
1608 | * Tries to extract a country calling code from a number. This method will return zero if no |
||
1609 | * country calling code is considered to be present. Country calling codes are extracted in the |
||
1610 | * following ways: |
||
1611 | * <ul> |
||
1612 | * <li> by stripping the international dialing prefix of the region the person is dialing from, |
||
1613 | 2428 | * if this is present in the number, and looking at the next digits |
|
1614 | * <li> by stripping the '+' sign if present and then looking at the next digits |
||
1615 | * <li> by comparing the start of the number and the country calling code of the default region. |
||
1616 | * If the number is not considered possible for the numbering plan of the default region |
||
1617 | * initially, but starts with the country calling code of this region, validation will be |
||
1618 | * reattempted after stripping this country calling code. If this number is considered a |
||
1619 | * possible number, then the first digits will be considered the country calling code and |
||
1620 | * removed as such. |
||
1621 | * </ul> |
||
1622 | * It will throw a NumberParseException if the number starts with a '+' but the country calling |
||
1623 | 2203 | * code supplied after this does not match that of any known region. |
|
1624 | * |
||
1625 | 2203 | * @param string $number non-normalized telephone number that we wish to extract a country calling |
|
1626 | 2203 | * code from - may begin with '+' |
|
1627 | * @param PhoneMetadata $defaultRegionMetadata metadata about the region this number may be from |
||
1628 | * @param string $nationalNumber a string buffer to store the national significant number in, in the case |
||
1629 | * that a country calling code was extracted. The number is appended to any existing contents. |
||
1630 | * If no country calling code was extracted, this will be left unchanged. |
||
1631 | 2203 | * @param bool $keepRawInput true if the country_code_source and preferred_carrier_code fields of |
|
1632 | * phoneNumber should be populated. |
||
1633 | * @param PhoneNumber $phoneNumber the PhoneNumber object where the country_code and country_code_source need |
||
1634 | 2203 | * to be populated. Note the country_code is always populated, whereas country_code_source is |
|
1635 | * only populated when keepCountryCodeSource is true. |
||
1636 | * @return int the country calling code extracted or 0 if none could be extracted |
||
1637 | * @throws NumberParseException |
||
1638 | */ |
||
1639 | public function maybeExtractCountryCode( |
||
1640 | $number, |
||
1641 | PhoneMetadata $defaultRegionMetadata = null, |
||
1642 | &$nationalNumber, |
||
1643 | 266 | $keepRawInput, |
|
1644 | PhoneNumber $phoneNumber |
||
1645 | 267 | ) { |
|
1646 | if (mb_strlen($number) == 0) { |
||
1647 | return 0; |
||
1648 | } |
||
1649 | $fullNumber = $number; |
||
1650 | // Set the default prefix to be something that will never match. |
||
1651 | 1 | $possibleCountryIddPrefix = "NonMatch"; |
|
1652 | 1 | if ($defaultRegionMetadata !== null) { |
|
1653 | $possibleCountryIddPrefix = $defaultRegionMetadata->getInternationalPrefix(); |
||
1654 | 2428 | } |
|
1655 | $countryCodeSource = $this->maybeStripInternationalPrefixAndNormalize($fullNumber, $possibleCountryIddPrefix); |
||
1656 | |||
1657 | if ($keepRawInput) { |
||
1658 | $phoneNumber->setCountryCodeSource($countryCodeSource); |
||
1659 | 2428 | } |
|
1660 | 2428 | if ($countryCodeSource != CountryCodeSource::FROM_DEFAULT_COUNTRY) { |
|
1661 | if (mb_strlen($fullNumber) <= static::MIN_LENGTH_FOR_NSN) { |
||
1662 | throw new NumberParseException( |
||
1663 | NumberParseException::TOO_SHORT_AFTER_IDD, |
||
1664 | "Phone number had an IDD, but after this was not long enough to be a viable phone number." |
||
1665 | ); |
||
1666 | 50 | } |
|
1667 | 50 | $potentialCountryCode = $this->extractCountryCode($fullNumber, $nationalNumber); |
|
1668 | |||
1669 | if ($potentialCountryCode != 0) { |
||
1670 | $phoneNumber->setCountryCode($potentialCountryCode); |
||
1671 | return $potentialCountryCode; |
||
1672 | } |
||
1673 | |||
1674 | // If this fails, they must be using a strange country calling code that we don't recognize, |
||
1675 | // or that doesn't exist. |
||
1676 | throw new NumberParseException( |
||
1677 | NumberParseException::INVALID_COUNTRY_CODE, |
||
1678 | 45 | "Country calling code supplied was not recognised." |
|
1679 | 45 | ); |
|
1680 | } elseif ($defaultRegionMetadata !== null) { |
||
1681 | 7 | // Check to see if the number starts with the country calling code for the default region. If |
|
1682 | 7 | // so, we remove the country calling code, and do some checks on the validity of the number |
|
1683 | // before and after. |
||
1684 | $defaultCountryCode = $defaultRegionMetadata->getCountryCode(); |
||
1685 | $defaultCountryCodeString = (string)$defaultCountryCode; |
||
1686 | 7 | $normalizedNumber = (string)$fullNumber; |
|
1687 | if (strpos($normalizedNumber, $defaultCountryCodeString) === 0) { |
||
1688 | $potentialNationalNumber = substr($normalizedNumber, mb_strlen($defaultCountryCodeString)); |
||
1689 | $generalDesc = $defaultRegionMetadata->getGeneralDesc(); |
||
1690 | $validNumberPattern = $generalDesc->getNationalNumberPattern(); |
||
1691 | // Don't need the carrier code. |
||
1692 | 2423 | $carriercode = null; |
|
1693 | 2203 | $this->maybeStripNationalPrefixAndCarrierCode( |
|
1694 | $potentialNationalNumber, |
||
1695 | $defaultRegionMetadata, |
||
1696 | $carriercode |
||
1697 | ); |
||
1698 | // If the number was not valid before but is valid now, or if it was too long before, we |
||
1699 | // consider the number with the country calling code stripped to be a better result and |
||
1700 | // keep that instead. |
||
1701 | if ((preg_match('/^(' . $validNumberPattern . ')$/x', $fullNumber) == 0 |
||
1702 | && preg_match('/^(' . $validNumberPattern . ')$/x', $potentialNationalNumber) > 0) |
||
1703 | || $this->testNumberLength((string)$fullNumber, $generalDesc) === ValidationResult::TOO_LONG |
||
1704 | ) { |
||
1705 | $nationalNumber .= $potentialNationalNumber; |
||
1706 | if ($keepRawInput) { |
||
1707 | 2428 | $phoneNumber->setCountryCodeSource(CountryCodeSource::FROM_NUMBER_WITHOUT_PLUS_SIGN); |
|
1708 | } |
||
1709 | $phoneNumber->setCountryCode($defaultCountryCode); |
||
1710 | return $defaultCountryCode; |
||
1711 | } |
||
1712 | 2203 | } |
|
1713 | } |
||
1714 | // No country calling code present. |
||
1715 | 2203 | $phoneNumber->setCountryCode(0); |
|
1716 | return 0; |
||
1717 | } |
||
1718 | |||
1719 | 265 | /** |
|
1720 | * Strips any international prefix (such as +, 00, 011) present in the number provided, normalizes |
||
1721 | * the resulting number, and indicates if an international prefix was present. |
||
1722 | 2428 | * |
|
1723 | * @param string $number the non-normalized telephone number that we wish to strip any international |
||
1724 | * dialing prefix from. |
||
1725 | 3 | * @param string $possibleIddPrefix string the international direct dialing prefix from the region we |
|
1726 | 2428 | * think this number may be dialed in |
|
1727 | * @return int the corresponding CountryCodeSource if an international dialing prefix could be |
||
1728 | * removed from the number, otherwise CountryCodeSource.FROM_DEFAULT_COUNTRY if the number did |
||
1729 | * not seem to be in international format. |
||
1730 | */ |
||
1731 | public function maybeStripInternationalPrefixAndNormalize(&$number, $possibleIddPrefix) |
||
1732 | { |
||
1733 | if (mb_strlen($number) == 0) { |
||
1734 | return CountryCodeSource::FROM_DEFAULT_COUNTRY; |
||
1735 | } |
||
1736 | $matches = array(); |
||
1737 | // Check to see if the number begins with one or more plus signs. |
||
1738 | $match = preg_match('/^' . static::$PLUS_CHARS_PATTERN . '/' . static::REGEX_FLAGS, $number, $matches, PREG_OFFSET_CAPTURE); |
||
1739 | if ($match > 0) { |
||
1740 | $number = mb_substr($number, $matches[0][1] + mb_strlen($matches[0][0])); |
||
1741 | // Can now normalize the rest of the number since we've consumed the "+" sign at the start. |
||
1742 | $number = $this->normalize($number); |
||
1743 | return CountryCodeSource::FROM_NUMBER_WITH_PLUS_SIGN; |
||
1744 | } |
||
1745 | // Attempt to parse the first digits as an international prefix. |
||
1746 | $iddPattern = $possibleIddPrefix; |
||
1747 | $number = $this->normalize($number); |
||
1748 | return $this->parsePrefixAsIdd($iddPattern, $number) |
||
1749 | ? CountryCodeSource::FROM_NUMBER_WITH_IDD |
||
1750 | : CountryCodeSource::FROM_DEFAULT_COUNTRY; |
||
1751 | } |
||
1752 | |||
1753 | /** |
||
1754 | * Normalizes a string of characters representing a phone number. This performs |
||
1755 | * the following conversions: |
||
1756 | * Punctuation is stripped. |
||
1757 | * For ALPHA/VANITY numbers: |
||
1758 | * Letters are converted to their numeric representation on a telephone |
||
1759 | * keypad. The keypad used here is the one defined in ITU Recommendation |
||
1760 | * E.161. This is only done if there are 3 or more letters in the number, |
||
1761 | * to lessen the risk that such letters are typos. |
||
1762 | * For other numbers: |
||
1763 | * Wide-ascii digits are converted to normal ASCII (European) digits. |
||
1764 | * Arabic-Indic numerals are converted to European numerals. |
||
1765 | * Spurious alpha characters are stripped. |
||
1766 | * |
||
1767 | * @param string $number a string of characters representing a phone number. |
||
1768 | * @return string the normalized string version of the phone number. |
||
1769 | */ |
||
1770 | public static function normalize(&$number) |
||
1771 | { |
||
1772 | $m = new Matcher(static::VALID_ALPHA_PHONE_PATTERN, $number); |
||
1773 | 28 | if ($m->matches()) { |
|
1774 | return static::normalizeHelper($number, static::$ALPHA_PHONE_MAPPINGS, true); |
||
1775 | 28 | } else { |
|
1776 | return static::normalizeDigitsOnly($number); |
||
1777 | } |
||
1778 | } |
||
1779 | |||
1780 | /** |
||
1781 | * Normalizes a string of characters representing a phone number. This converts wide-ascii and |
||
1782 | * arabic-indic numerals to European numerals, and strips punctuation and alpha characters. |
||
1783 | * |
||
1784 | * @param $number string a string of characters representing a phone number |
||
1785 | * @return string the normalized string version of the phone number |
||
1786 | */ |
||
1787 | public static function normalizeDigitsOnly($number) |
||
1788 | { |
||
1789 | return static::normalizeDigits($number, false /* strip non-digits */); |
||
1790 | 28 | } |
|
1791 | |||
1792 | /** |
||
1793 | * @param string $number |
||
1794 | * @param bool $keepNonDigits |
||
1795 | * @return string |
||
1796 | */ |
||
1797 | public static function normalizeDigits($number, $keepNonDigits) |
||
1798 | { |
||
1799 | $normalizedDigits = ""; |
||
1800 | 2427 | $numberAsArray = preg_split('/(?<!^)(?!$)/u', $number); |
|
1801 | foreach ($numberAsArray as $character) { |
||
1802 | if (is_numeric($character)) { |
||
1803 | $normalizedDigits .= $character; |
||
1804 | } elseif ($keepNonDigits) { |
||
1805 | $normalizedDigits .= $character; |
||
1806 | } |
||
1807 | // If neither of the above are true, we remove this character. |
||
1808 | |||
1809 | // Check if we are in the unicode number range |
||
1810 | 4 | if (array_key_exists($character, static::$numericCharacters)) { |
|
1811 | 2 | $normalizedDigits .= static::$numericCharacters[$character]; |
|
1812 | } |
||
1813 | } |
||
1814 | return $normalizedDigits; |
||
1815 | 3 | } |
|
1816 | |||
1817 | 2427 | /** |
|
1818 | * Strips the IDD from the start of the number if present. Helper function used by |
||
1819 | * maybeStripInternationalPrefixAndNormalize. |
||
1820 | * @param string $iddPattern |
||
1821 | * @param string $number |
||
1822 | * @return bool |
||
1823 | */ |
||
1824 | protected function parsePrefixAsIdd($iddPattern, &$number) |
||
1825 | { |
||
1826 | $m = new Matcher($iddPattern, $number); |
||
1827 | if ($m->lookingAt()) { |
||
1828 | 267 | $matchEnd = $m->end(); |
|
1829 | // Only strip this if the first digit after the match is not a 0, since country calling codes |
||
1830 | // cannot begin with 0. |
||
1831 | $digitMatcher = new Matcher(static::$CAPTURING_DIGIT_PATTERN, substr($number, $matchEnd)); |
||
1832 | 1 | if ($digitMatcher->find()) { |
|
1833 | $normalizedGroup = $this->normalizeDigitsOnly($digitMatcher->group(1)); |
||
1834 | if ($normalizedGroup == "0") { |
||
1835 | return false; |
||
1836 | } |
||
1837 | 27 | } |
|
1838 | $number = substr($number, $matchEnd); |
||
1839 | 267 | return true; |
|
1840 | } |
||
1841 | 27 | return false; |
|
1842 | 1 | } |
|
1843 | |||
1844 | /** |
||
1845 | * Extracts country calling code from fullNumber, returns it and places the remaining number in nationalNumber. |
||
1846 | * It assumes that the leading plus sign or IDD has already been removed. |
||
1847 | * Returns 0 if fullNumber doesn't start with a valid country calling code, and leaves nationalNumber unmodified. |
||
1848 | * @param string $fullNumber |
||
1849 | * @param string $nationalNumber |
||
1850 | * @return int |
||
1851 | */ |
||
1852 | protected function extractCountryCode(&$fullNumber, &$nationalNumber) |
||
1853 | { |
||
1854 | 2163 | if ((mb_strlen($fullNumber) == 0) || ($fullNumber[0] == '0')) { |
|
1855 | // Country codes do not begin with a '0'. |
||
1856 | return 0; |
||
1857 | } |
||
1858 | 778 | $numberLength = mb_strlen($fullNumber); |
|
1859 | for ($i = 1; $i <= static::MAX_LENGTH_COUNTRY_CODE && $i <= $numberLength; $i++) { |
||
1860 | 781 | $potentialCountryCode = (int)substr($fullNumber, 0, $i); |
|
1861 | if (isset($this->countryCallingCodeToRegionCodeMap[$potentialCountryCode])) { |
||
1862 | $nationalNumber .= substr($fullNumber, $i); |
||
1863 | return $potentialCountryCode; |
||
1864 | } |
||
1865 | } |
||
1866 | return 0; |
||
1867 | } |
||
1868 | |||
1869 | /** |
||
1870 | * Strips any national prefix (such as 0, 1) present in the number provided. |
||
1871 | * |
||
1872 | * @param string $number the normalized telephone number that we wish to strip any national |
||
1873 | * dialing prefix from |
||
1874 | * @param PhoneMetadata $metadata the metadata for the region that we think this number is from |
||
1875 | 48 | * @param string $carrierCode a place to insert the carrier code if one is extracted |
|
1876 | * @return bool true if a national prefix or carrier code (or both) could be extracted. |
||
1877 | */ |
||
1878 | public function maybeStripNationalPrefixAndCarrierCode(&$number, PhoneMetadata $metadata, &$carrierCode) |
||
1937 | |||
1938 | /** |
||
1939 | * Helper method to check a number against possible lengths for this number, and determine whether |
||
1940 | * it matches, or is too short or too long. Currently, if a number pattern suggests that numbers |
||
1941 | * of length 7 and 10 are possible, and a number in between these possible lengths is entered, |
||
1942 | * such as of length 8, this will return TOO_LONG. |
||
1943 | 7 | * @param string $number |
|
1944 | * @param PhoneNumberDesc $phoneNumberDesc |
||
1945 | 7 | * @return int ValidationResult |
|
1946 | 7 | */ |
|
1947 | protected function testNumberLength($number, PhoneNumberDesc $phoneNumberDesc) |
||
1948 | { |
||
1949 | $possibleLengths = $phoneNumberDesc->getPossibleLength(); |
||
1950 | $localLengths = $phoneNumberDesc->getPossibleLengthLocalOnly(); |
||
1951 | |||
1952 | $actualLength = mb_strlen($number); |
||
1953 | |||
1954 | if (in_array($actualLength, $localLengths)) { |
||
1955 | return ValidationResult::IS_POSSIBLE; |
||
1956 | } |
||
1957 | |||
1958 | // There should always be "possibleLengths" set for every element. This will be a build-time |
||
1959 | // check once ShortNumberMetadata.xml is migrated to contain this information as well. |
||
1960 | $minimumLength = reset($possibleLengths); |
||
1961 | if ($minimumLength == $actualLength) { |
||
1962 | return ValidationResult::IS_POSSIBLE; |
||
1963 | } elseif ($minimumLength > $actualLength) { |
||
1964 | return ValidationResult::TOO_SHORT; |
||
1965 | } elseif (isset($possibleLengths[count($possibleLengths) - 1]) && $possibleLengths[count($possibleLengths) - 1] < $actualLength) { |
||
1966 | return ValidationResult::TOO_LONG; |
||
1967 | } |
||
1968 | |||
1969 | // Note that actually the number is not too long if possibleLengths does not contain the length: |
||
1970 | // we know it is less than the highest possible number length, and higher than the lowest |
||
1971 | // possible number length. However, we don't currently have an enum to express this, so we |
||
1972 | 1543 | // return TOO_LONG in the short-term. |
|
1973 | // We skip the first element; we've already checked it. |
||
1974 | array_shift($possibleLengths); |
||
1975 | 1543 | return in_array($actualLength, $possibleLengths) ? ValidationResult::IS_POSSIBLE : ValidationResult::TOO_LONG; |
|
1976 | } |
||
1977 | |||
1978 | /** |
||
1979 | * Returns a list with the region codes that match the specific country calling code. For |
||
1980 | * non-geographical country calling codes, the region code 001 is returned. Also, in the case |
||
1981 | * of no region code being found, an empty list is returned. |
||
1982 | * @param int $countryCallingCode |
||
1983 | * @return array |
||
1984 | */ |
||
1985 | public function getRegionCodesForCountryCode($countryCallingCode) |
||
1986 | { |
||
1987 | $regionCodes = isset($this->countryCallingCodeToRegionCodeMap[$countryCallingCode]) ? $this->countryCallingCodeToRegionCodeMap[$countryCallingCode] : null; |
||
1988 | return $regionCodes === null ? array() : $regionCodes; |
||
1989 | } |
||
1990 | |||
1991 | /** |
||
1992 | * Returns the country calling code for a specific region. For example, this would be 1 for the |
||
1993 | 1 | * United States, and 64 for New Zealand. Assumes the region is already valid. |
|
1994 | * |
||
1995 | * @param string $regionCode the region that we want to get the country calling code for |
||
1996 | * @return int the country calling code for the region denoted by regionCode |
||
1997 | */ |
||
1998 | public function getCountryCodeForRegion($regionCode) |
||
2005 | |||
2006 | /** |
||
2007 | * Returns the country calling code for a specific region. For example, this would be 1 for the |
||
2008 | * United States, and 64 for New Zealand. Assumes the region is already valid. |
||
2009 | * |
||
2010 | * @param string $regionCode the region that we want to get the country calling code for |
||
2011 | * @return int the country calling code for the region denoted by regionCode |
||
2012 | * @throws \InvalidArgumentException if the region is invalid |
||
2013 | */ |
||
2014 | protected function getCountryCodeForValidRegion($regionCode) |
||
2015 | { |
||
2016 | $metadata = $this->getMetadataForRegion($regionCode); |
||
2017 | if ($metadata === null) { |
||
2018 | throw new \InvalidArgumentException("Invalid region code: " . $regionCode); |
||
2019 | } |
||
2020 | return $metadata->getCountryCode(); |
||
2021 | } |
||
2022 | |||
2023 | /** |
||
2024 | * Returns a number formatted in such a way that it can be dialed from a mobile phone in a |
||
2025 | * specific region. If the number cannot be reached from the region (e.g. some countries block |
||
2026 | 1 | * toll-free numbers from being called outside of the country), the method returns an empty |
|
2027 | * string. |
||
2028 | 1 | * |
|
2029 | * @param PhoneNumber $number the phone number to be formatted |
||
2030 | * @param string $regionCallingFrom the region where the call is being placed |
||
2031 | * @param boolean $withFormatting whether the number should be returned with formatting symbols, such as |
||
2032 | * spaces and dashes. |
||
2033 | * @return string the formatted phone number |
||
2034 | */ |
||
2035 | public function formatNumberForMobileDialing(PhoneNumber $number, $regionCallingFrom, $withFormatting) |
||
2036 | { |
||
2037 | $countryCallingCode = $number->getCountryCode(); |
||
2038 | if (!$this->hasValidCountryCallingCode($countryCallingCode)) { |
||
2039 | return $number->hasRawInput() ? $number->getRawInput() : ""; |
||
2040 | } |
||
2041 | |||
2042 | $formattedNumber = ""; |
||
2043 | // Clear the extension, as that part cannot normally be dialed together with the main number. |
||
2044 | $numberNoExt = new PhoneNumber(); |
||
2045 | $numberNoExt->mergeFrom($number)->clearExtension(); |
||
2046 | $regionCode = $this->getRegionCodeForCountryCode($countryCallingCode); |
||
2047 | $numberType = $this->getNumberType($numberNoExt); |
||
2048 | $isValidNumber = ($numberType !== PhoneNumberType::UNKNOWN); |
||
2049 | if ($regionCallingFrom == $regionCode) { |
||
2050 | $isFixedLineOrMobile = ($numberType == PhoneNumberType::FIXED_LINE) || ($numberType == PhoneNumberType::MOBILE) || ($numberType == PhoneNumberType::FIXED_LINE_OR_MOBILE); |
||
2051 | // Carrier codes may be needed in some countries. We handle this here. |
||
2052 | if ($regionCode == "CO" && $numberType == PhoneNumberType::FIXED_LINE) { |
||
2053 | $formattedNumber = $this->formatNationalNumberWithCarrierCode( |
||
2054 | $numberNoExt, |
||
2055 | static::COLOMBIA_MOBILE_TO_FIXED_LINE_PREFIX |
||
2056 | ); |
||
2057 | } elseif ($regionCode == "BR" && $isFixedLineOrMobile) { |
||
2058 | // Brazilian fixed line and mobile numbers need to be dialed with a carrier code when |
||
2059 | // called within Brazil. Without that, most of the carriers won't connect the call. |
||
2060 | // Because of that, we return an empty string here. |
||
2061 | $formattedNumber = $numberNoExt->hasPreferredDomesticCarrierCode( |
||
2062 | ) ? $this->formatNationalNumberWithCarrierCode($numberNoExt, "") : ""; |
||
2063 | } elseif ($isValidNumber && $regionCode == "HU") { |
||
2064 | // The national format for HU numbers doesn't contain the national prefix, because that is |
||
2065 | // how numbers are normally written down. However, the national prefix is obligatory when |
||
2066 | // dialing from a mobile phone, except for short numbers. As a result, we add it back here |
||
2067 | // if it is a valid regular length phone number. |
||
2068 | $formattedNumber = $this->getNddPrefixForRegion( |
||
2069 | $regionCode, |
||
2070 | true /* strip non-digits */ |
||
2071 | ) . " " . $this->format($numberNoExt, PhoneNumberFormat::NATIONAL); |
||
2072 | 1 | } elseif ($countryCallingCode === static::NANPA_COUNTRY_CODE) { |
|
2073 | // For NANPA countries, we output international format for numbers that can be dialed |
||
2074 | // internationally, since that always works, except for numbers which might potentially be |
||
2075 | // short numbers, which are always dialled in national format. |
||
2076 | $regionMetadata = $this->getMetadataForRegion($regionCallingFrom); |
||
2077 | if ($this->canBeInternationallyDialled($numberNoExt) |
||
2078 | && $this->testNumberLength($this->getNationalSignificantNumber($numberNoExt), |
||
2079 | $regionMetadata->getGeneralDesc()) !== ValidationResult::TOO_SHORT |
||
2080 | ) { |
||
2081 | $formattedNumber = $this->format($numberNoExt, PhoneNumberFormat::INTERNATIONAL); |
||
2082 | } else { |
||
2083 | $formattedNumber = $this->format($numberNoExt, PhoneNumberFormat::NATIONAL); |
||
2084 | } |
||
2085 | } else { |
||
2086 | // For non-geographical countries, Mexican and Chilean fixed line and mobile numbers, we |
||
2087 | // output international format for numbers that can be dialed internationally as that always |
||
2088 | // works. |
||
2089 | 1 | if (($regionCode == static::REGION_CODE_FOR_NON_GEO_ENTITY || |
|
2090 | // MX fixed line and mobile numbers should always be formatted in international format, |
||
2091 | // even when dialed within MX. For national format to work, a carrier code needs to be |
||
2092 | // used, and the correct carrier code depends on if the caller and callee are from the |
||
2093 | // same local area. It is trickier to get that to work correctly than using |
||
2094 | 1 | // international format, which is tested to work fine on all carriers. |
|
2095 | // CL fixed line numbers need the national prefix when dialing in the national format, |
||
2096 | // but don't have it when used for display. The reverse is true for mobile numbers. |
||
2097 | // As a result, we output them in the international format to make it work. |
||
2098 | (($regionCode == "MX" || $regionCode == "CL") && $isFixedLineOrMobile)) && $this->canBeInternationallyDialled( |
||
2099 | $numberNoExt |
||
2100 | ) |
||
2101 | ) { |
||
2102 | $formattedNumber = $this->format($numberNoExt, PhoneNumberFormat::INTERNATIONAL); |
||
2103 | } else { |
||
2104 | $formattedNumber = $this->format($numberNoExt, PhoneNumberFormat::NATIONAL); |
||
2105 | } |
||
2106 | } |
||
2107 | } elseif ($isValidNumber && $this->canBeInternationallyDialled($numberNoExt)) { |
||
2108 | // We assume that short numbers are not diallable from outside their region, so if a number |
||
2109 | // is not a valid regular length phone number, we treat it as if it cannot be internationally |
||
2110 | // dialled. |
||
2111 | return $withFormatting ? |
||
2112 | $this->format($numberNoExt, PhoneNumberFormat::INTERNATIONAL) : |
||
2113 | $this->format($numberNoExt, PhoneNumberFormat::E164); |
||
2114 | } |
||
2115 | return $withFormatting ? $formattedNumber : $this->normalizeDiallableCharsOnly($formattedNumber); |
||
2116 | } |
||
2117 | |||
2118 | /** |
||
2119 | * Formats a phone number in national format for dialing using the carrier as specified in the |
||
2120 | * {@code carrierCode}. The {@code carrierCode} will always be used regardless of whether the |
||
2121 | * phone number already has a preferred domestic carrier code stored. If {@code carrierCode} |
||
2122 | * contains an empty string, returns the number in national format without any carrier code. |
||
2123 | * |
||
2124 | * @param PhoneNumber $number the phone number to be formatted |
||
2125 | * @param string $carrierCode the carrier selection code to be used |
||
2126 | * @return string the formatted phone number in national format for dialing using the carrier as |
||
2127 | * specified in the {@code carrierCode} |
||
2128 | */ |
||
2129 | public function formatNationalNumberWithCarrierCode(PhoneNumber $number, $carrierCode) |
||
2130 | { |
||
2131 | $countryCallingCode = $number->getCountryCode(); |
||
2132 | $nationalSignificantNumber = $this->getNationalSignificantNumber($number); |
||
2133 | if (!$this->hasValidCountryCallingCode($countryCallingCode)) { |
||
2134 | return $nationalSignificantNumber; |
||
2135 | } |
||
2136 | |||
2137 | // Note getRegionCodeForCountryCode() is used because formatting information for regions which |
||
2138 | // share a country calling code is contained by only one region for performance reasons. For |
||
2139 | // example, for NANPA regions it will be contained in the metadata for US. |
||
2140 | $regionCode = $this->getRegionCodeForCountryCode($countryCallingCode); |
||
2141 | // Metadata cannot be null because the country calling code is valid. |
||
2142 | $metadata = $this->getMetadataForRegionOrCallingCode($countryCallingCode, $regionCode); |
||
2143 | |||
2144 | $formattedNumber = $this->formatNsn( |
||
2145 | $nationalSignificantNumber, |
||
2146 | $metadata, |
||
2147 | PhoneNumberFormat::NATIONAL, |
||
2148 | $carrierCode |
||
2149 | ); |
||
2150 | $this->maybeAppendFormattedExtension($number, $metadata, PhoneNumberFormat::NATIONAL, $formattedNumber); |
||
2151 | $this->prefixNumberWithCountryCallingCode( |
||
2152 | $countryCallingCode, |
||
2153 | PhoneNumberFormat::NATIONAL, |
||
2154 | $formattedNumber |
||
2155 | 29 | ); |
|
2156 | return $formattedNumber; |
||
2157 | } |
||
2158 | 29 | ||
2159 | /** |
||
2160 | * Formats a phone number in national format for dialing using the carrier as specified in the |
||
2161 | * preferredDomesticCarrierCode field of the PhoneNumber object passed in. If that is missing, |
||
2162 | * use the {@code fallbackCarrierCode} passed in instead. If there is no |
||
2163 | * {@code preferredDomesticCarrierCode}, and the {@code fallbackCarrierCode} contains an empty |
||
2164 | * string, return the number in national format without any carrier code. |
||
2165 | 29 | * |
|
2166 | * <p>Use {@link #formatNationalNumberWithCarrierCode} instead if the carrier code passed in |
||
2167 | * should take precedence over the number's {@code preferredDomesticCarrierCode} when formatting. |
||
2168 | * |
||
2169 | * @param PhoneNumber $number the phone number to be formatted |
||
2170 | * @param string $fallbackCarrierCode the carrier selection code to be used, if none is found in the |
||
2171 | * phone number itself |
||
2172 | * @return string the formatted phone number in national format for dialing using the number's |
||
2173 | * {@code preferredDomesticCarrierCode}, or the {@code fallbackCarrierCode} passed in if |
||
2174 | * none is found |
||
2175 | */ |
||
2176 | public function formatNationalNumberWithPreferredCarrierCode(PhoneNumber $number, $fallbackCarrierCode) |
||
2185 | |||
2186 | /** |
||
2187 | * Returns true if the number can be dialled from outside the region, or unknown. If the number |
||
2188 | * can only be dialled from within the region, returns false. Does not check the number is a valid |
||
2189 | * number. |
||
2190 | * TODO: Make this method public when we have enough metadata to make it worthwhile. |
||
2191 | * |
||
2192 | * @param PhoneNumber $number the phone-number for which we want to know whether it is diallable from outside the region |
||
2193 | * @return bool |
||
2194 | */ |
||
2195 | public function canBeInternationallyDialled(PhoneNumber $number) |
||
2196 | { |
||
2197 | $metadata = $this->getMetadataForRegion($this->getRegionCodeForNumber($number)); |
||
2198 | if ($metadata === null) { |
||
2199 | // Note numbers belonging to non-geographical entities (e.g. +800 numbers) are always |
||
2200 | // internationally diallable, and will be caught here. |
||
2201 | return true; |
||
2202 | } |
||
2203 | 1 | $nationalSignificantNumber = $this->getNationalSignificantNumber($number); |
|
2204 | return !$this->isNumberMatchingDesc($nationalSignificantNumber, $metadata->getNoInternationalDialling()); |
||
2205 | } |
||
2206 | |||
2207 | /** |
||
2208 | * Normalizes a string of characters representing a phone number. This strips all characters which |
||
2209 | * are not diallable on a mobile phone keypad (including all non-ASCII digits). |
||
2210 | * |
||
2211 | * @param string $number a string of characters representing a phone number |
||
2212 | * @return string the normalized string version of the phone number |
||
2213 | 1 | */ |
|
2214 | public static function normalizeDiallableCharsOnly($number) |
||
2218 | |||
2219 | /** |
||
2220 | * Formats a phone number for out-of-country dialing purposes. |
||
2221 | * |
||
2222 | * Note that in this version, if the number was entered originally using alpha characters and |
||
2223 | * this version of the number is stored in raw_input, this representation of the number will be |
||
2224 | * used rather than the digit representation. Grouping information, as specified by characters |
||
2225 | * such as "-" and " ", will be retained. |
||
2226 | * |
||
2227 | * <p><b>Caveats:</b></p> |
||
2228 | * <ul> |
||
2229 | * <li> This will not produce good results if the country calling code is both present in the raw |
||
2230 | * input _and_ is the start of the national number. This is not a problem in the regions |
||
2231 | * which typically use alpha numbers. |
||
2232 | * <li> This will also not produce good results if the raw input has any grouping information |
||
2233 | * within the first three digits of the national number, and if the function needs to strip |
||
2234 | * preceding digits/words in the raw input before these digits. Normally people group the |
||
2235 | * first three digits together so this is not a huge problem - and will be fixed if it |
||
2236 | * proves to be so. |
||
2237 | * </ul> |
||
2238 | * |
||
2239 | * @param PhoneNumber $number the phone number that needs to be formatted |
||
2240 | * @param String $regionCallingFrom the region where the call is being placed |
||
2241 | * @return String the formatted phone number |
||
2242 | */ |
||
2243 | public function formatOutOfCountryKeepingAlphaChars(PhoneNumber $number, $regionCallingFrom) |
||
2336 | |||
2337 | /** |
||
2338 | 2 | * Formats a phone number for out-of-country dialing purposes. If no regionCallingFrom is |
|
2339 | * supplied, we format the number in its INTERNATIONAL format. If the country calling code is the |
||
2340 | * same as that of the region where the number is from, then NATIONAL formatting will be applied. |
||
2341 | * |
||
2342 | * <p>If the number itself has a country calling code of zero or an otherwise invalid country |
||
2343 | * calling code, then we return the number with no formatting applied. |
||
2344 | * |
||
2345 | * <p>Note this function takes care of the case for calling inside of NANPA and between Russia and |
||
2346 | 3 | * Kazakhstan (who share the same country calling code). In those cases, no international prefix |
|
2347 | * is used. For regions which have multiple international prefixes, the number in its |
||
2348 | * INTERNATIONAL format will be returned instead. |
||
2349 | * |
||
2350 | 2 | * @param PhoneNumber $number the phone number to be formatted |
|
2351 | * @param string $regionCallingFrom the region where the call is being placed |
||
2352 | * @return string the formatted phone number |
||
2353 | 2 | */ |
|
2354 | public function formatOutOfCountryCallingNumber(PhoneNumber $number, $regionCallingFrom) |
||
2355 | { |
||
2356 | if (!$this->isValidRegionCode($regionCallingFrom)) { |
||
2357 | return $this->format($number, PhoneNumberFormat::INTERNATIONAL); |
||
2358 | 3 | } |
|
2359 | $countryCallingCode = $number->getCountryCode(); |
||
2360 | $nationalSignificantNumber = $this->getNationalSignificantNumber($number); |
||
2361 | 3 | if (!$this->hasValidCountryCallingCode($countryCallingCode)) { |
|
2362 | return $nationalSignificantNumber; |
||
2363 | 3 | } |
|
2364 | 3 | if ($countryCallingCode == static::NANPA_COUNTRY_CODE) { |
|
2365 | if ($this->isNANPACountry($regionCallingFrom)) { |
||
2366 | // For NANPA regions, return the national format for these regions but prefix it with the |
||
2367 | 3 | // country calling code. |
|
2368 | return $countryCallingCode . " " . $this->format($number, PhoneNumberFormat::NATIONAL); |
||
2369 | } |
||
2370 | } elseif ($countryCallingCode == $this->getCountryCodeForValidRegion($regionCallingFrom)) { |
||
2371 | 3 | // If regions share a country calling code, the country calling code need not be dialled. |
|
2372 | // This also applies when dialling within a region, so this if clause covers both these cases. |
||
2373 | 1 | // Technically this is the case for dialling from La Reunion to other overseas departments of |
|
2374 | // France (French Guiana, Martinique, Guadeloupe), but not vice versa - so we don't cover this |
||
2375 | 1 | // edge case for now and for those cases return the version including country calling code. |
|
2376 | // Details here: http://www.petitfute.com/voyage/225-info-pratiques-reunion |
||
2377 | return $this->format($number, PhoneNumberFormat::NATIONAL); |
||
2378 | 3 | } |
|
2379 | 3 | // Metadata cannot be null because we checked 'isValidRegionCode()' above. |
|
2380 | 2 | $metadataForRegionCallingFrom = $this->getMetadataForRegion($regionCallingFrom); |
|
2381 | |||
2382 | $internationalPrefix = $metadataForRegionCallingFrom->getInternationalPrefix(); |
||
2383 | |||
2384 | // For regions that have multiple international prefixes, the international format of the |
||
2385 | // number is returned, unless there is a preferred international prefix. |
||
2386 | $internationalPrefixForFormatting = ""; |
||
2387 | $uniqueInternationalPrefixMatcher = new Matcher(static::UNIQUE_INTERNATIONAL_PREFIX, $internationalPrefix); |
||
2388 | |||
2389 | if ($uniqueInternationalPrefixMatcher->matches()) { |
||
2390 | $internationalPrefixForFormatting = $internationalPrefix; |
||
2391 | } elseif ($metadataForRegionCallingFrom->hasPreferredInternationalPrefix()) { |
||
2392 | $internationalPrefixForFormatting = $metadataForRegionCallingFrom->getPreferredInternationalPrefix(); |
||
2393 | } |
||
2394 | |||
2395 | $regionCode = $this->getRegionCodeForCountryCode($countryCallingCode); |
||
2396 | // Metadata cannot be null because the country calling code is valid. |
||
2397 | $metadataForRegion = $this->getMetadataForRegionOrCallingCode($countryCallingCode, $regionCode); |
||
2398 | $formattedNationalNumber = $this->formatNsn( |
||
2399 | $nationalSignificantNumber, |
||
2400 | $metadataForRegion, |
||
2401 | PhoneNumberFormat::INTERNATIONAL |
||
2402 | ); |
||
2403 | $formattedNumber = $formattedNationalNumber; |
||
2404 | $this->maybeAppendFormattedExtension( |
||
2405 | $number, |
||
2406 | $metadataForRegion, |
||
2407 | PhoneNumberFormat::INTERNATIONAL, |
||
2408 | 1 | $formattedNumber |
|
2409 | ); |
||
2410 | if (mb_strlen($internationalPrefixForFormatting) > 0) { |
||
2411 | $formattedNumber = $internationalPrefixForFormatting . " " . $countryCallingCode . " " . $formattedNumber; |
||
2412 | } else { |
||
2413 | $this->prefixNumberWithCountryCallingCode( |
||
2414 | $countryCallingCode, |
||
2415 | PhoneNumberFormat::INTERNATIONAL, |
||
2416 | $formattedNumber |
||
2417 | ); |
||
2418 | } |
||
2419 | return $formattedNumber; |
||
2420 | } |
||
2421 | |||
2422 | /** |
||
2423 | * Checks if this is a region under the North American Numbering Plan Administration (NANPA). |
||
2424 | * @param string $regionCode |
||
2425 | * @return boolean true if regionCode is one of the regions under NANPA |
||
2426 | */ |
||
2427 | public function isNANPACountry($regionCode) |
||
2431 | |||
2432 | /** |
||
2433 | * Formats a phone number using the original phone number format that the number is parsed from. |
||
2434 | * The original format is embedded in the country_code_source field of the PhoneNumber object |
||
2435 | * passed in. If such information is missing, the number will be formatted into the NATIONAL |
||
2436 | * format by default. When the number contains a leading zero and this is unexpected for this |
||
2437 | * country, or we don't have a formatting pattern for the number, the method returns the raw input |
||
2438 | * when it is available. |
||
2439 | * |
||
2440 | * Note this method guarantees no digit will be inserted, removed or modified as a result of |
||
2441 | * formatting. |
||
2442 | 1 | * |
|
2443 | 1 | * @param PhoneNumber $number the phone number that needs to be formatted in its original number format |
|
2444 | * @param string $regionCallingFrom the region whose IDD needs to be prefixed if the original number |
||
2445 | * has one |
||
2446 | * @return string the formatted phone number in its original number format |
||
2447 | */ |
||
2448 | public function formatInOriginalFormat(PhoneNumber $number, $regionCallingFrom) |
||
2449 | { |
||
2450 | if ($number->hasRawInput() && |
||
2451 | ($this->hasUnexpectedItalianLeadingZero($number) || !$this->hasFormattingPatternForNumber($number)) |
||
2452 | ) { |
||
2453 | // We check if we have the formatting pattern because without that, we might format the number |
||
2454 | // as a group without national prefix. |
||
2455 | return $number->getRawInput(); |
||
2456 | } |
||
2457 | if (!$number->hasCountryCodeSource()) { |
||
2458 | return $this->format($number, PhoneNumberFormat::NATIONAL); |
||
2459 | } |
||
2460 | switch ($number->getCountryCodeSource()) { |
||
2461 | case CountryCodeSource::FROM_NUMBER_WITH_PLUS_SIGN: |
||
2462 | $formattedNumber = $this->format($number, PhoneNumberFormat::INTERNATIONAL); |
||
2463 | break; |
||
2464 | case CountryCodeSource::FROM_NUMBER_WITH_IDD: |
||
2465 | $formattedNumber = $this->formatOutOfCountryCallingNumber($number, $regionCallingFrom); |
||
2466 | break; |
||
2467 | case CountryCodeSource::FROM_NUMBER_WITHOUT_PLUS_SIGN: |
||
2468 | $formattedNumber = substr($this->format($number, PhoneNumberFormat::INTERNATIONAL), 1); |
||
2469 | break; |
||
2470 | case CountryCodeSource::FROM_DEFAULT_COUNTRY: |
||
2471 | // Fall-through to default case. |
||
2472 | default: |
||
2473 | |||
2474 | $regionCode = $this->getRegionCodeForCountryCode($number->getCountryCode()); |
||
2475 | // We strip non-digits from the NDD here, and from the raw input later, so that we can |
||
2476 | // compare them easily. |
||
2477 | $nationalPrefix = $this->getNddPrefixForRegion($regionCode, true /* strip non-digits */); |
||
2478 | $nationalFormat = $this->format($number, PhoneNumberFormat::NATIONAL); |
||
2479 | if ($nationalPrefix === null || mb_strlen($nationalPrefix) == 0) { |
||
2480 | // If the region doesn't have a national prefix at all, we can safely return the national |
||
2481 | // format without worrying about a national prefix being added. |
||
2482 | $formattedNumber = $nationalFormat; |
||
2483 | break; |
||
2484 | } |
||
2485 | // Otherwise, we check if the original number was entered with a national prefix. |
||
2486 | if ($this->rawInputContainsNationalPrefix( |
||
2487 | $number->getRawInput(), |
||
2488 | $nationalPrefix, |
||
2489 | $regionCode |
||
2490 | ) |
||
2491 | ) { |
||
2492 | // If so, we can safely return the national format. |
||
2493 | $formattedNumber = $nationalFormat; |
||
2494 | break; |
||
2495 | } |
||
2496 | // Metadata cannot be null here because getNddPrefixForRegion() (above) returns null if |
||
2497 | // there is no metadata for the region. |
||
2498 | $metadata = $this->getMetadataForRegion($regionCode); |
||
2499 | $nationalNumber = $this->getNationalSignificantNumber($number); |
||
2500 | $formatRule = $this->chooseFormattingPatternForNumber($metadata->numberFormats(), $nationalNumber); |
||
2501 | // The format rule could still be null here if the national number was 0 and there was no |
||
2502 | // raw input (this should not be possible for numbers generated by the phonenumber library |
||
2503 | // as they would also not have a country calling code and we would have exited earlier). |
||
2504 | if ($formatRule === null) { |
||
2505 | $formattedNumber = $nationalFormat; |
||
2506 | break; |
||
2507 | } |
||
2508 | // When the format we apply to this number doesn't contain national prefix, we can just |
||
2509 | // return the national format. |
||
2510 | // TODO: Refactor the code below with the code in isNationalPrefixPresentIfRequired. |
||
2511 | $candidateNationalPrefixRule = $formatRule->getNationalPrefixFormattingRule(); |
||
2512 | // We assume that the first-group symbol will never be _before_ the national prefix. |
||
2513 | $indexOfFirstGroup = strpos($candidateNationalPrefixRule, '$1'); |
||
2514 | if ($indexOfFirstGroup <= 0) { |
||
2515 | $formattedNumber = $nationalFormat; |
||
2516 | break; |
||
2517 | } |
||
2518 | $candidateNationalPrefixRule = substr($candidateNationalPrefixRule, 0, $indexOfFirstGroup); |
||
2519 | $candidateNationalPrefixRule = $this->normalizeDigitsOnly($candidateNationalPrefixRule); |
||
2520 | if (mb_strlen($candidateNationalPrefixRule) == 0) { |
||
2521 | // National prefix not used when formatting this number. |
||
2522 | $formattedNumber = $nationalFormat; |
||
2523 | break; |
||
2524 | } |
||
2525 | 1 | // Otherwise, we need to remove the national prefix from our output. |
|
2526 | $numFormatCopy = new NumberFormat(); |
||
2527 | $numFormatCopy->mergeFrom($formatRule); |
||
2528 | $numFormatCopy->clearNationalPrefixFormattingRule(); |
||
2529 | $numberFormats = array(); |
||
2530 | $numberFormats[] = $numFormatCopy; |
||
2531 | $formattedNumber = $this->formatByPattern($number, PhoneNumberFormat::NATIONAL, $numberFormats); |
||
2532 | 1 | break; |
|
2533 | } |
||
2534 | $rawInput = $number->getRawInput(); |
||
2535 | // If no digit is inserted/removed/modified as a result of our formatting, we return the |
||
2536 | // formatted phone number; otherwise we return the raw input the user entered. |
||
2537 | if ($formattedNumber !== null && mb_strlen($rawInput) > 0) { |
||
2538 | $normalizedFormattedNumber = $this->normalizeDiallableCharsOnly($formattedNumber); |
||
2539 | $normalizedRawInput = $this->normalizeDiallableCharsOnly($rawInput); |
||
2540 | if ($normalizedFormattedNumber != $normalizedRawInput) { |
||
2541 | $formattedNumber = $rawInput; |
||
2542 | } |
||
2543 | } |
||
2544 | return $formattedNumber; |
||
2545 | } |
||
2546 | |||
2547 | /** |
||
2548 | * Returns true if a number is from a region whose national significant number couldn't contain a |
||
2549 | * leading zero, but has the italian_leading_zero field set to true. |
||
2550 | * @param PhoneNumber $number |
||
2551 | * @return bool |
||
2552 | */ |
||
2553 | protected function hasUnexpectedItalianLeadingZero(PhoneNumber $number) |
||
2557 | |||
2558 | /** |
||
2559 | * Checks whether the country calling code is from a region whose national significant number |
||
2560 | * could contain a leading zero. An example of such a region is Italy. Returns false if no |
||
2561 | * metadata for the country is found. |
||
2562 | * @param int $countryCallingCode |
||
2563 | * @return bool |
||
2564 | */ |
||
2565 | public function isLeadingZeroPossible($countryCallingCode) |
||
2576 | |||
2577 | 1 | /** |
|
2578 | * @param PhoneNumber $number |
||
2579 | 1 | * @return bool |
|
2580 | */ |
||
2581 | protected function hasFormattingPatternForNumber(PhoneNumber $number) |
||
2582 | { |
||
2583 | $countryCallingCode = $number->getCountryCode(); |
||
2584 | 1 | $phoneNumberRegion = $this->getRegionCodeForCountryCode($countryCallingCode); |
|
2585 | $metadata = $this->getMetadataForRegionOrCallingCode($countryCallingCode, $phoneNumberRegion); |
||
2586 | if ($metadata === null) { |
||
2587 | return false; |
||
2588 | } |
||
2589 | $nationalNumber = $this->getNationalSignificantNumber($number); |
||
2590 | $formatRule = $this->chooseFormattingPatternForNumber($metadata->numberFormats(), $nationalNumber); |
||
2591 | return $formatRule !== null; |
||
2592 | } |
||
2593 | |||
2594 | /** |
||
2595 | * Returns the national dialling prefix for a specific region. For example, this would be 1 for |
||
2596 | * the United States, and 0 for New Zealand. Set stripNonDigits to true to strip symbols like "~" |
||
2597 | * (which indicates a wait for a dialling tone) from the prefix returned. If no national prefix is |
||
2598 | * present, we return null. |
||
2599 | * |
||
2600 | * <p>Warning: Do not use this method for do-your-own formatting - for some regions, the |
||
2601 | * national dialling prefix is used only for certain types of numbers. Use the library's |
||
2602 | * formatting functions to prefix the national prefix when required. |
||
2603 | * |
||
2604 | * @param string $regionCode the region that we want to get the dialling prefix for |
||
2605 | * @param boolean $stripNonDigits true to strip non-digits from the national dialling prefix |
||
2606 | * @return string the dialling prefix for the region denoted by regionCode |
||
2607 | */ |
||
2608 | public function getNddPrefixForRegion($regionCode, $stripNonDigits) |
||
2609 | { |
||
2610 | $metadata = $this->getMetadataForRegion($regionCode); |
||
2611 | if ($metadata === null) { |
||
2612 | return null; |
||
2613 | } |
||
2614 | $nationalPrefix = $metadata->getNationalPrefix(); |
||
2615 | // If no national prefix was found, we return null. |
||
2616 | if (mb_strlen($nationalPrefix) == 0) { |
||
2617 | return null; |
||
2618 | } |
||
2619 | if ($stripNonDigits) { |
||
2620 | // Note: if any other non-numeric symbols are ever used in national prefixes, these would have |
||
2621 | 1816 | // to be removed here as well. |
|
2622 | $nationalPrefix = str_replace("~", "", $nationalPrefix); |
||
2623 | } |
||
2624 | return $nationalPrefix; |
||
2625 | 1816 | } |
|
2626 | |||
2627 | /** |
||
2628 | * Check if rawInput, which is assumed to be in the national format, has a national prefix. The |
||
2629 | * national prefix is assumed to be in digits-only form. |
||
2630 | * @param string $rawInput |
||
2631 | * @param string $nationalPrefix |
||
2632 | * @param string $regionCode |
||
2633 | * @return bool |
||
2634 | */ |
||
2635 | protected function rawInputContainsNationalPrefix($rawInput, $nationalPrefix, $regionCode) |
||
2636 | { |
||
2637 | $normalizedNationalNumber = $this->normalizeDigitsOnly($rawInput); |
||
2638 | if (strpos($normalizedNationalNumber, $nationalPrefix) === 0) { |
||
2639 | try { |
||
2640 | // Some Japanese numbers (e.g. 00777123) might be mistaken to contain the national prefix |
||
2641 | // when written without it (e.g. 0777123) if we just do prefix matching. To tackle that, we |
||
2642 | // check the validity of the number if the assumed national prefix is removed (777123 won't |
||
2643 | 1575 | // be valid in Japan). |
|
2644 | return $this->isValidNumber( |
||
2645 | $this->parse(substr($normalizedNationalNumber, mb_strlen($nationalPrefix)), $regionCode) |
||
2646 | ); |
||
2647 | 1575 | } catch (NumberParseException $e) { |
|
2648 | 1552 | return false; |
|
2649 | } |
||
2650 | } |
||
2651 | return false; |
||
2652 | } |
||
2653 | 28 | ||
2654 | /** |
||
2655 | * Tests whether a phone number matches a valid pattern. Note this doesn't verify the number |
||
2656 | * is actually in use, which is impossible to tell by just looking at a number itself. |
||
2657 | * |
||
2658 | 1575 | * @param PhoneNumber $number the phone number that we want to validate |
|
2659 | * @return boolean that indicates whether the number is of a valid pattern |
||
2660 | */ |
||
2661 | public function isValidNumber(PhoneNumber $number) |
||
2662 | { |
||
2663 | $regionCode = $this->getRegionCodeForNumber($number); |
||
2664 | return $this->isValidNumberForRegion($number, $regionCode); |
||
2665 | } |
||
2666 | |||
2667 | /** |
||
2668 | * Tests whether a phone number is valid for a certain region. Note this doesn't verify the number |
||
2669 | * is actually in use, which is impossible to tell by just looking at a number itself. If the |
||
2670 | * country calling code is not the same as the country calling code for the region, this |
||
2671 | * immediately exits with false. After this, the specific number pattern rules for the region are |
||
2672 | * examined. This is useful for determining for example whether a particular number is valid for |
||
2673 | * Canada, rather than just a valid NANPA number. |
||
2674 | * Warning: In most cases, you want to use {@link #isValidNumber} instead. For example, this |
||
2675 | * method will mark numbers from British Crown dependencies such as the Isle of Man as invalid for |
||
2676 | * the region "GB" (United Kingdom), since it has its own region code, "IM", which may be |
||
2677 | * undesirable. |
||
2678 | * |
||
2679 | * @param PhoneNumber $number the phone number that we want to validate |
||
2680 | * @param string $regionCode the region that we want to validate the phone number for |
||
2681 | * @return boolean that indicates whether the number is of a valid pattern |
||
2682 | */ |
||
2683 | public function isValidNumberForRegion(PhoneNumber $number, $regionCode) |
||
2684 | { |
||
2685 | $countryCode = $number->getCountryCode(); |
||
2686 | $metadata = $this->getMetadataForRegionOrCallingCode($countryCode, $regionCode); |
||
2687 | if (($metadata === null) || |
||
2688 | (static::REGION_CODE_FOR_NON_GEO_ENTITY !== $regionCode && |
||
2689 | 2205 | $countryCode !== $this->getCountryCodeForValidRegion($regionCode)) |
|
2690 | ) { |
||
2691 | 2205 | // Either the region code was invalid, or the country calling code for this number does not |
|
2692 | // match that of the region code. |
||
2693 | return false; |
||
2694 | 3 | } |
|
2695 | 2202 | $nationalSignificantNumber = $this->getNationalSignificantNumber($number); |
|
2696 | |||
2697 | return $this->getNumberTypeHelper($nationalSignificantNumber, $metadata) != PhoneNumberType::UNKNOWN; |
||
2698 | } |
||
2699 | |||
2700 | /** |
||
2701 | * Parses a string and returns it as a phone number in proto buffer format. The method is quite |
||
2702 | * lenient and looks for a number in the input text (raw input) and does not check whether the |
||
2703 | * string is definitely only a phone number. To do this, it ignores punctuation and white-space, |
||
2704 | * as well as any text before the number (e.g. a leading “Tel: ”) and trims the non-number bits. |
||
2705 | * It will accept a number in any format (E164, national, international etc), assuming it can |
||
2706 | * interpreted with the defaultRegion supplied. It also attempts to convert any alpha characters |
||
2707 | * into digits if it thinks this is a vanity number of the type "1800 MICROSOFT". |
||
2708 | * |
||
2709 | * <p> This method will throw a {@link NumberParseException} if the number is not considered to |
||
2710 | * be a possible number. Note that validation of whether the number is actually a valid number |
||
2711 | * for a particular region is not performed. This can be done separately with {@link #isValidnumber}. |
||
2712 | * |
||
2713 | * @param string $numberToParse number that we are attempting to parse. This can contain formatting |
||
2714 | * such as +, ( and -, as well as a phone number extension. |
||
2715 | * @param string $defaultRegion region that we are expecting the number to be from. This is only used |
||
2716 | * if the number being parsed is not written in international format. |
||
2717 | * The country_code for the number in this case would be stored as that |
||
2718 | * of the default region supplied. If the number is guaranteed to |
||
2719 | * start with a '+' followed by the country calling code, then |
||
2720 | * "ZZ" or null can be supplied. |
||
2721 | * @param PhoneNumber|null $phoneNumber |
||
2722 | * @param bool $keepRawInput |
||
2723 | * @return PhoneNumber a phone number proto buffer filled with the parsed number |
||
2724 | * @throws NumberParseException if the string is not considered to be a viable phone number (e.g. |
||
2725 | * too few or too many digits) or if no default region was supplied |
||
2726 | * and the number is not in international format (does not start |
||
2727 | * with +) |
||
2728 | */ |
||
2729 | public function parse($numberToParse, $defaultRegion, PhoneNumber $phoneNumber = null, $keepRawInput = false) |
||
2730 | { |
||
2731 | if ($phoneNumber === null) { |
||
2732 | $phoneNumber = new PhoneNumber(); |
||
2733 | } |
||
2734 | $this->parseHelper($numberToParse, $defaultRegion, $keepRawInput, true, $phoneNumber); |
||
2735 | return $phoneNumber; |
||
2736 | } |
||
2737 | |||
2738 | /** |
||
2739 | * Formats a phone number in the specified format using client-defined formatting rules. Note that |
||
2740 | * if the phone number has a country calling code of zero or an otherwise invalid country calling |
||
2741 | * code, we cannot work out things like whether there should be a national prefix applied, or how |
||
2742 | * to format extensions, so we return the national significant number with no formatting applied. |
||
2743 | * |
||
2744 | * @param PhoneNumber $number the phone number to be formatted |
||
2745 | * @param int $numberFormat the format the phone number should be formatted into |
||
2746 | * @param array $userDefinedFormats formatting rules specified by clients |
||
2747 | * @return String the formatted phone number |
||
2748 | */ |
||
2749 | public function formatByPattern(PhoneNumber $number, $numberFormat, array $userDefinedFormats) |
||
2750 | { |
||
2751 | $countryCallingCode = $number->getCountryCode(); |
||
2752 | $nationalSignificantNumber = $this->getNationalSignificantNumber($number); |
||
2753 | if (!$this->hasValidCountryCallingCode($countryCallingCode)) { |
||
2754 | return $nationalSignificantNumber; |
||
2755 | } |
||
2756 | // Note getRegionCodeForCountryCode() is used because formatting information for regions which |
||
2757 | // share a country calling code is contained by only one region for performance reasons. For |
||
2758 | // example, for NANPA regions it will be contained in the metadata for US. |
||
2759 | $regionCode = $this->getRegionCodeForCountryCode($countryCallingCode); |
||
2760 | // Metadata cannot be null because the country calling code is valid |
||
2761 | $metadata = $this->getMetadataForRegionOrCallingCode($countryCallingCode, $regionCode); |
||
2762 | |||
2763 | $formattedNumber = ""; |
||
2764 | |||
2765 | $formattingPattern = $this->chooseFormattingPatternForNumber($userDefinedFormats, $nationalSignificantNumber); |
||
2766 | if ($formattingPattern === null) { |
||
2767 | // If no pattern above is matched, we format the number as a whole. |
||
2768 | $formattedNumber .= $nationalSignificantNumber; |
||
2769 | } else { |
||
2770 | $numFormatCopy = new NumberFormat(); |
||
2771 | // Before we do a replacement of the national prefix pattern $NP with the national prefix, we |
||
2772 | // need to copy the rule so that subsequent replacements for different numbers have the |
||
2773 | // appropriate national prefix. |
||
2774 | $numFormatCopy->mergeFrom($formattingPattern); |
||
2775 | $nationalPrefixFormattingRule = $formattingPattern->getNationalPrefixFormattingRule(); |
||
2776 | if (mb_strlen($nationalPrefixFormattingRule) > 0) { |
||
2777 | $nationalPrefix = $metadata->getNationalPrefix(); |
||
2778 | if (mb_strlen($nationalPrefix) > 0) { |
||
2779 | // Replace $NP with national prefix and $FG with the first group ($1). |
||
2780 | $npPatternMatcher = new Matcher(static::NP_PATTERN, $nationalPrefixFormattingRule); |
||
2781 | 244 | $nationalPrefixFormattingRule = $npPatternMatcher->replaceFirst($nationalPrefix); |
|
2782 | $fgPatternMatcher = new Matcher(static::FG_PATTERN, $nationalPrefixFormattingRule); |
||
2783 | $nationalPrefixFormattingRule = $fgPatternMatcher->replaceFirst("\\$1"); |
||
2784 | $numFormatCopy->setNationalPrefixFormattingRule($nationalPrefixFormattingRule); |
||
2785 | } else { |
||
2786 | // We don't want to have a rule for how to format the national prefix if there isn't one. |
||
2787 | $numFormatCopy->clearNationalPrefixFormattingRule(); |
||
2788 | } |
||
2789 | } |
||
2790 | $formattedNumber .= $this->formatNsnUsingPattern($nationalSignificantNumber, $numFormatCopy, $numberFormat); |
||
2791 | } |
||
2792 | $this->maybeAppendFormattedExtension($number, $metadata, $numberFormat, $formattedNumber); |
||
2793 | $this->prefixNumberWithCountryCallingCode($countryCallingCode, $numberFormat, $formattedNumber); |
||
2794 | return $formattedNumber; |
||
2795 | } |
||
2796 | |||
2797 | /** |
||
2798 | * Gets a valid number for the specified region. |
||
2799 | * |
||
2800 | * @param string regionCode the region for which an example number is needed |
||
2801 | * @return PhoneNumber a valid fixed-line number for the specified region. Returns null when the metadata |
||
2802 | * does not contain such information, or the region 001 is passed in. For 001 (representing |
||
2803 | * non-geographical numbers), call {@link #getExampleNumberForNonGeoEntity} instead. |
||
2804 | */ |
||
2805 | public function getExampleNumber($regionCode) |
||
2809 | |||
2810 | /** |
||
2811 | * Gets an invalid number for the specified region. This is useful for unit-testing purposes, |
||
2812 | * where you want to test what will happen with an invalid number. Note that the number that is |
||
2813 | * returned will always be able to be parsed and will have the correct country code. It may also |
||
2814 | * be a valid *short* number/code for this region. Validity checking such numbers is handled with |
||
2815 | * {@link ShortNumberInfo}. |
||
2816 | * |
||
2817 | 244 | * @param string $regionCode The region for which an example number is needed |
|
2818 | * @return PhoneNumber|null An invalid number for the specified region. Returns null when an unsupported region |
||
2819 | * or the region 001 (Earth) is passed in. |
||
2820 | */ |
||
2821 | public function getInvalidExampleNumber($regionCode) |
||
2822 | 6 | { |
|
2823 | 229 | if (!$this->isValidRegionCode($regionCode)) { |
|
2824 | return null; |
||
2825 | } |
||
2826 | |||
2827 | // We start off with a valid fixed-line number since every country supports this. Alternatively |
||
2828 | // we could start with a different number type, since fixed-line numbers typically have a wide |
||
2829 | // breadth of valid number lengths and we may have to make it very short before we get an |
||
2830 | // invalid number. |
||
2831 | |||
2832 | $desc = $this->getNumberDescByType($this->getMetadataForRegion($regionCode), PhoneNumberType::FIXED_LINE); |
||
2833 | |||
2834 | if ($desc->getExampleNumber() == '') { |
||
2835 | // This shouldn't happen; we have a test for this. |
||
2836 | return null; |
||
2837 | } |
||
2838 | |||
2839 | $exampleNumber = $desc->getExampleNumber(); |
||
2840 | |||
2841 | 3163 | // Try and make the number invalid. We do this by changing the length. We try reducing the |
|
2842 | // length of the number, since currently no region has a number that is the same length as |
||
2843 | 3163 | // MIN_LENGTH_FOR_NSN. This is probably quicker than making the number longer, which is another |
|
2844 | // alternative. We could also use the possible number pattern to extract the possible lengths of |
||
2845 | // the number to make this faster, but this method is only for unit-testing so simplicity is |
||
2846 | // preferred to performance. We don't want to return a number that can't be parsed, so we check |
||
2847 | 15 | // the number is long enough. We try all possible lengths because phone number plans often have |
|
2848 | // overlapping prefixes so the number 123456 might be valid as a fixed-line number, and 12345 as |
||
2849 | 6 | // a mobile number. It would be faster to loop in a different order, but we prefer numbers that |
|
2850 | 11 | // look closer to real numbers (and it gives us a variety of different lengths for the resulting |
|
2851 | // phone numbers - otherwise they would all be MIN_LENGTH_FOR_NSN digits long.) |
||
2852 | 6 | for ($phoneNumberLength = mb_strlen($exampleNumber) - 1; $phoneNumberLength >= static::MIN_LENGTH_FOR_NSN; $phoneNumberLength--) { |
|
2853 | $numberToTry = mb_substr($exampleNumber, 0, $phoneNumberLength); |
||
2867 | |||
2868 | /** |
||
2869 | * Gets a valid number for the specified region and number type. |
||
2870 | * |
||
2871 | * @param string $regionCodeOrType the region for which an example number is needed |
||
2872 | * @param int $type the PhoneNumberType of number that is needed |
||
2873 | * @return PhoneNumber a valid number for the specified region and type. Returns null when the metadata |
||
2874 | * does not contain such information or if an invalid region or region 001 was entered. |
||
2875 | * For 001 (representing non-geographical numbers), call |
||
2876 | * {@link #getExampleNumberForNonGeoEntity} instead. |
||
2877 | * |
||
2878 | 1378 | * If $regionCodeOrType is the only parameter supplied, then a valid number for the specified number type |
|
2879 | 1378 | * will be returned that may belong to any country. |
|
2880 | 15 | */ |
|
2881 | public function getExampleNumberForType($regionCodeOrType, $type = null) |
||
2921 | |||
2922 | /** |
||
2923 | * @param PhoneMetadata $metadata |
||
2924 | 9 | * @param int $type PhoneNumberType |
|
2925 | * @return PhoneNumberDesc |
||
2926 | */ |
||
2927 | 9 | protected function getNumberDescByType(PhoneMetadata $metadata, $type) |
|
2955 | |||
2956 | /** |
||
2957 | * Gets a valid number for the specified country calling code for a non-geographical entity. |
||
2958 | * |
||
2959 | * @param int $countryCallingCode the country calling code for a non-geographical entity |
||
2960 | * @return PhoneNumber a valid number for the non-geographical entity. Returns null when the metadata |
||
2961 | * does not contain such information, or the country calling code passed in does not belong |
||
2962 | 2 | * to a non-geographical entity. |
|
2963 | */ |
||
2964 | public function getExampleNumberForNonGeoEntity($countryCallingCode) |
||
2978 | |||
2979 | |||
2980 | /** |
||
2981 | * Takes two phone numbers and compares them for equality. |
||
2982 | * |
||
2983 | * <p>Returns EXACT_MATCH if the country_code, NSN, presence of a leading zero |
||
2984 | * for Italian numbers and any extension present are the same. Returns NSN_MATCH |
||
2985 | 2 | * if either or both has no region specified, and the NSNs and extensions are |
|
2986 | * the same. Returns SHORT_NSN_MATCH if either or both has no region specified, |
||
2987 | * or the region specified is the same, and one NSN could be a shorter version |
||
2988 | * of the other number. This includes the case where one has an extension |
||
2989 | * specified, and the other does not. Returns NO_MATCH otherwise. For example, |
||
2990 | * the numbers +1 345 657 1234 and 657 1234 are a SHORT_NSN_MATCH. The numbers |
||
2991 | * +1 345 657 1234 and 345 657 are a NO_MATCH. |
||
2992 | * |
||
2993 | * @param $firstNumberIn PhoneNumber|string First number to compare. If it is a |
||
2994 | * string it can contain formatting, and can have country calling code specified |
||
2995 | * with + at the start. |
||
2996 | * @param $secondNumberIn PhoneNumber|string Second number to compare. If it is a |
||
2997 | * string it can contain formatting, and can have country calling code specified |
||
2998 | * with + at the start. |
||
2999 | * @throws \InvalidArgumentException |
||
3000 | * @return int {MatchType} NOT_A_NUMBER, NO_MATCH, |
||
3001 | */ |
||
3002 | public function isNumberMatch($firstNumberIn, $secondNumberIn) |
||
3124 | |||
3125 | /** |
||
3126 | * Returns true when one national number is the suffix of the other or both are the same. |
||
3127 | * @param PhoneNumber $firstNumber |
||
3128 | * @param PhoneNumber $secondNumber |
||
3129 | * @return bool |
||
3130 | */ |
||
3131 | protected function isNationalNumberSuffixOfTheOther(PhoneNumber $firstNumber, PhoneNumber $secondNumber) |
||
3138 | |||
3139 | protected function stringEndsWithString($hayStack, $needle) |
||
3145 | |||
3146 | /** |
||
3147 | * Returns true if the supplied region supports mobile number portability. Returns false for |
||
3148 | * invalid, unknown or regions that don't support mobile number portability. |
||
3149 | * |
||
3150 | * @param string $regionCode the region for which we want to know whether it supports mobile number |
||
3151 | 1 | * portability or not. |
|
3152 | 1 | * @return bool |
|
3153 | */ |
||
3154 | public function isMobileNumberPortableRegion($regionCode) |
||
3163 | |||
3164 | /** |
||
3165 | * Check whether a phone number is a possible number given a number in the form of a string, and |
||
3166 | * the region where the number could be dialed from. It provides a more lenient check than |
||
3167 | * {@link #isValidNumber}. See {@link #isPossibleNumber(PhoneNumber)} for details. |
||
3168 | * |
||
3169 | * <p>This method first parses the number, then invokes {@link #isPossibleNumber(PhoneNumber)} |
||
3170 | * with the resultant PhoneNumber object. |
||
3171 | * |
||
3172 | * @param PhoneNumber|string $number the number that needs to be checked, in the form of a string |
||
3173 | * @param string $regionDialingFrom the region that we are expecting the number to be dialed from. |
||
3174 | * Note this is different from the region where the number belongs. For example, the number |
||
3175 | * +1 650 253 0000 is a number that belongs to US. When written in this form, it can be |
||
3176 | * dialed from any region. When it is written as 00 1 650 253 0000, it can be dialed from any |
||
3177 | * region which uses an international dialling prefix of 00. When it is written as |
||
3178 | * 650 253 0000, it can only be dialed from within the US, and when written as 253 0000, it |
||
3179 | * can only be dialed from within a smaller area in the US (Mountain View, CA, to be more |
||
3180 | 1 | * specific). |
|
3181 | * @return boolean true if the number is possible |
||
3182 | */ |
||
3183 | public function isPossibleNumber($number, $regionDialingFrom = null) |
||
3197 | |||
3198 | |||
3199 | /** |
||
3200 | * Check whether a phone number is a possible number. It provides a more lenient check than |
||
3201 | * {@link #isValidNumber} in the following sense: |
||
3202 | * <ol> |
||
3203 | * <li> It only checks the length of phone numbers. In particular, it doesn't check starting |
||
3204 | * digits of the number. |
||
3205 | * <li> It doesn't attempt to figure out the type of the number, but uses general rules which |
||
3206 | * applies to all types of phone numbers in a region. Therefore, it is much faster than |
||
3207 | 1 | * isValidNumber. |
|
3208 | * <li> For fixed line numbers, many regions have the concept of area code, which together with |
||
3209 | * subscriber number constitute the national significant number. It is sometimes okay to dial |
||
3210 | 1 | * the subscriber number only when dialing in the same area. This function will return |
|
3211 | * true if the subscriber-number-only version is passed in. On the other hand, because |
||
3212 | * isValidNumber validates using information on both starting digits (for fixed line |
||
3213 | * numbers, that would most likely be area codes) and length (obviously includes the |
||
3214 | * length of area codes for fixed line numbers), it will return false for the |
||
3215 | * subscriber-number-only version. |
||
3216 | * </ol> |
||
3217 | * @param PhoneNumber $number the number that needs to be checked |
||
3218 | * @return int a ValidationResult object which indicates whether the number is possible |
||
3219 | */ |
||
3220 | public function isPossibleNumberWithReason(PhoneNumber $number) |
||
3238 | |||
3239 | /** |
||
3240 | * Attempts to extract a valid number from a phone number that is too long to be valid, and resets |
||
3241 | * the PhoneNumber object passed in to that valid version. If no valid number could be extracted, |
||
3242 | * the PhoneNumber object passed in will not be modified. |
||
3243 | * @param PhoneNumber $number a PhoneNumber object which contains a number that is too long to be valid. |
||
3244 | * @return boolean true if a valid phone number can be successfully extracted. |
||
3245 | */ |
||
3246 | public function truncateTooLongNumber(PhoneNumber $number) |
||
3264 | } |
||
3265 |
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.