Tighten formatInOriginalFormat not to format numbers which we don't have
formatting patterns, and use the raw_input instead.

Bug: 5520899
Change-Id: I2016180ad8c83c73e8ebb74ed2dc8fd616f68cbd
diff --git a/java/src/com/android/i18n/phonenumbers/PhoneNumberUtil.java b/java/src/com/android/i18n/phonenumbers/PhoneNumberUtil.java
index 3f0138a..4a435b8 100644
--- a/java/src/com/android/i18n/phonenumbers/PhoneNumberUtil.java
+++ b/java/src/com/android/i18n/phonenumbers/PhoneNumberUtil.java
@@ -1339,7 +1339,11 @@
    * @return  the formatted phone number in its original number format
    */
   public String formatInOriginalFormat(PhoneNumber number, String regionCallingFrom) {
-    if (number.hasRawInput() && !isValidNumber(number)) {
+    if (number.hasRawInput() &&
+        (!hasFormattingPatternForNumber(number) || !isValidNumber(number))) {
+      // We check if we have the formatting pattern because without that, we might format the number
+      // as a group without national prefix. We also want to check the validity of the number
+      // because we don't want to risk formatting the number if we don't really understand it.
       return number.getRawInput();
     }
     if (!number.hasCountryCodeSource()) {
@@ -1358,6 +1362,18 @@
     }
   }
 
+  private boolean hasFormattingPatternForNumber(PhoneNumber number) {
+    String phoneNumberRegion = getRegionCodeForCountryCode(number.getCountryCode());
+    PhoneMetadata metadata = getMetadataForRegion(phoneNumberRegion);
+    if (metadata == null) {
+      return false;
+    }
+    String nationalNumber = getNationalSignificantNumber(number);
+    NumberFormat formatRule =
+        chooseFormattingPatternForNumber(metadata.numberFormats(), nationalNumber);
+    return formatRule != null;
+  }
+
   /**
    * Formats a phone number for out-of-country dialing purposes.
    *
diff --git a/java/test/com/android/i18n/phonenumbers/PhoneNumberUtilTest.java b/java/test/com/android/i18n/phonenumbers/PhoneNumberUtilTest.java
index 54433bf..8033be2 100644
--- a/java/test/com/android/i18n/phonenumbers/PhoneNumberUtilTest.java
+++ b/java/test/com/android/i18n/phonenumbers/PhoneNumberUtilTest.java
@@ -730,6 +730,11 @@
     // When the raw input is unavailable, format as usual.
     PhoneNumber number7 = phoneUtil.parse("7345678901", RegionCode.US);
     assertEquals("734 567 8901", phoneUtil.formatInOriginalFormat(number7, RegionCode.US));
+
+    // This number is valid, but we don't have a formatting pattern for it. Fall back to the raw
+    // input.
+    PhoneNumber number8 = phoneUtil.parseAndKeepRawInput("02-4567-8900", RegionCode.KR);
+    assertEquals("02-4567-8900", phoneUtil.formatInOriginalFormat(number8, RegionCode.KR));
   }
 
   public void testIsPremiumRate() {