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