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