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