1 /*
2 * Copyright (c) 2021-2022 Huawei Device Co., Ltd.
3 * Licensed under the Apache License, Version 2.0 (the "License");
4 * you may not use this file except in compliance with the License.
5 * You may obtain a copy of the License at
6 *
7 * http://www.apache.org/licenses/LICENSE-2.0
8 *
9 * Unless required by applicable law or agreed to in writing, software
10 * distributed under the License is distributed on an "AS IS" BASIS,
11 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 * See the License for the specific language governing permissions and
13 * limitations under the License.
14 */
15
16 #include "phone_number_format.h"
17
18 namespace OHOS {
19 namespace Global {
20 namespace I18n {
21 using i18n::phonenumbers::PhoneNumberUtil;
22
PhoneNumberFormat(const std::string & countryTag,const std::map<std::string,std::string> & options)23 PhoneNumberFormat::PhoneNumberFormat(const std::string &countryTag,
24 const std::map<std::string, std::string> &options)
25 {
26 util = PhoneNumberUtil::GetInstance();
27 country = countryTag;
28
29 std::string type = "";
30 auto search = options.find("type");
31 if (search != options.end()) {
32 type = search->second;
33 }
34
35 std::map<std::string, PhoneNumberUtil::PhoneNumberFormat> type2PhoneNumberFormat = {
36 {"E164", PhoneNumberUtil::PhoneNumberFormat::E164},
37 {"RFC3966", PhoneNumberUtil::PhoneNumberFormat::RFC3966},
38 {"INTERNATIONAL", PhoneNumberUtil::PhoneNumberFormat::INTERNATIONAL},
39 {"NATIONAL", PhoneNumberUtil::PhoneNumberFormat::NATIONAL}
40 };
41
42 std::set<std::string> validType = {"E164", "RFC3966", "INTERNATIONAL", "NATIONAL"};
43 if (validType.find(type) != validType.end()) {
44 phoneNumberFormat = type2PhoneNumberFormat[type];
45 } else {
46 phoneNumberFormat = PhoneNumberUtil::PhoneNumberFormat::NATIONAL;
47 }
48 }
49
~PhoneNumberFormat()50 PhoneNumberFormat::~PhoneNumberFormat()
51 {
52 }
53
isValidPhoneNumber(const std::string & number) const54 bool PhoneNumberFormat::isValidPhoneNumber(const std::string &number) const
55 {
56 i18n::phonenumbers::PhoneNumber phoneNumber;
57 PhoneNumberUtil::ErrorType type = util->Parse(number, country, &phoneNumber);
58 if (type != PhoneNumberUtil::ErrorType::NO_PARSING_ERROR) {
59 return false;
60 }
61 return util->IsValidNumber(phoneNumber);
62 }
63
format(const std::string & number) const64 std::string PhoneNumberFormat::format(const std::string &number) const
65 {
66 i18n::phonenumbers::PhoneNumber phoneNumber;
67 PhoneNumberUtil::ErrorType type = util->Parse(number, country, &phoneNumber);
68 if (type != PhoneNumberUtil::ErrorType::NO_PARSING_ERROR) {
69 return "";
70 }
71 std::string formatted_number;
72 util->Format(phoneNumber, phoneNumberFormat, &formatted_number);
73 return formatted_number;
74 }
75 } // namespace I18n
76 } // namespace Global
77 } // namespace OHOS