File indexing completed on 2024-04-28 16:42:50

0001 // SPDX-FileCopyrightText: 2021 Jonah BrĂ¼chert <jbb@kaidan.im>
0002 //
0003 // SPDX-License-Identifier: GPL-2.0-only OR GPL-3.0-only OR LicenseRef-KDE-Accepted-GPL
0004 
0005 #include "phone-number-utils.h"
0006 
0007 #include <QChar>
0008 #include <QLocale>
0009 
0010 #include <phonenumbers/phonenumberutil.h>
0011 
0012 using namespace ::i18n::phonenumbers;
0013 
0014 namespace phoneNumberUtils
0015 {
0016 const std::string localeCountryCode()
0017 {
0018     const QLocale locale;
0019     const QStringList qcountry = locale.name().split(u'_');
0020     const QString &countrycode(qcountry.constLast());
0021     return countrycode.toStdString();
0022 }
0023 
0024 NormalizeResult normalizeNumber(const std::string &numberString, PhoneNumberFormat format, const std::string &country)
0025 {
0026     std::string countryToCheck = country;
0027     if (countryToCheck.empty()) {
0028         countryToCheck = localeCountryCode();
0029     }
0030     PhoneNumber phoneNumber;
0031     auto error = PhoneNumberUtil::GetInstance()->Parse(numberString, countryToCheck, &phoneNumber);
0032 
0033     if (error != PhoneNumberUtil::NO_PARSING_ERROR) {
0034         return ErrorType(error);
0035     }
0036 
0037     std::string formattedNumber;
0038     PhoneNumberUtil::GetInstance()->Format(phoneNumber, PhoneNumberUtil::PhoneNumberFormat(format), &formattedNumber);
0039     return formattedNumber;
0040 }
0041 
0042 QString normalizeNumber(const QString &numberString, PhoneNumberFormat format, const std::string &country)
0043 {
0044     auto res = normalizeNumber(numberString.toStdString(), format, country);
0045     if (std::holds_alternative<std::string>(res)) {
0046         return QString::fromStdString(std::get<std::string>(res));
0047     }
0048 
0049     return numberString;
0050 }
0051 }