Skip to content

Commit

Permalink
Fix ambiguous phone number detection (#642)
Browse files Browse the repository at this point in the history
`possibleResults` could end up with multiple instances of identical
phone numbers leading to an incorrect `ambiguousNumber` error.
  • Loading branch information
cosmer-work authored May 16, 2023
1 parent 6edd6e3 commit 6f30a97
Show file tree
Hide file tree
Showing 3 changed files with 10 additions and 4 deletions.
2 changes: 1 addition & 1 deletion PhoneNumberKit/Constants.swift
Original file line number Diff line number Diff line change
Expand Up @@ -40,7 +40,7 @@ public enum PhoneNumberError: Error, Equatable {
case tooShort
case deprecated
case metadataNotFound
case ambiguousNumber(phoneNumbers: [PhoneNumber])
case ambiguousNumber(phoneNumbers: Set<PhoneNumber>)
}

extension PhoneNumberError: LocalizedError {
Expand Down
6 changes: 3 additions & 3 deletions PhoneNumberKit/ParseManager.swift
Original file line number Diff line number Diff line change
Expand Up @@ -75,18 +75,18 @@ final class ParseManager {
}

// If everything fails, iterate through other territories with the same country code (7)
var possibleResults = [PhoneNumber]()
var possibleResults: Set<PhoneNumber> = []
if let metadataList = metadataManager.filterTerritories(byCode: countryCode) {
for metadata in metadataList where regionMetadata.codeID != metadata.codeID {
if let result = try validPhoneNumber(from: nationalNumber, using: metadata, countryCode: countryCode, ignoreType: ignoreType, numberString: numberString, numberExtension: numberExtension) {
possibleResults.append(result)
possibleResults.insert(result)
}
}
}

switch possibleResults.count {
case 0: throw PhoneNumberError.notANumber
case 1: return possibleResults[0]
case 1: return possibleResults.first!
default: throw PhoneNumberError.ambiguousNumber(phoneNumbers: possibleResults)
}
}
Expand Down
6 changes: 6 additions & 0 deletions PhoneNumberKitTests/PhoneNumberKitParsingTests.swift
Original file line number Diff line number Diff line change
Expand Up @@ -547,4 +547,10 @@ class PhoneNumberKitParsingTests: XCTestCase {
XCTAssertEqual(number.type, PhoneNumberType.mobile)
XCTAssertEqual(number.numberExtension, "22")
}

func testNonAmbiguousPhoneNumber() {
// This phone number was incorrectly identified as ambiguous.
let address = "+1 345 916 1234"
try XCTAssertNotNil(phoneNumberKit.parse(address, withRegion: "JM"))
}
}

0 comments on commit 6f30a97

Please sign in to comment.