PhoneNumberUtil.php 1.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243
  1. <?php
  2. declare(strict_types=1);
  3. /**
  4. * SPDX-FileCopyrightText: 2023 Nextcloud GmbH and Nextcloud contributors
  5. * SPDX-License-Identifier: AGPL-3.0-or-later
  6. */
  7. namespace OC;
  8. use libphonenumber\NumberParseException;
  9. use libphonenumber\PhoneNumberFormat;
  10. use OCP\IPhoneNumberUtil;
  11. /**
  12. * @since 28.0.0
  13. */
  14. class PhoneNumberUtil implements IPhoneNumberUtil {
  15. /**
  16. * {@inheritDoc}
  17. */
  18. public function getCountryCodeForRegion(string $regionCode): ?int {
  19. $phoneUtil = \libphonenumber\PhoneNumberUtil::getInstance();
  20. $countryCode = $phoneUtil->getCountryCodeForRegion($regionCode);
  21. return $countryCode === 0 ? null : $countryCode;
  22. }
  23. /**
  24. * {@inheritDoc}
  25. */
  26. public function convertToStandardFormat(string $input, ?string $defaultRegion = null): ?string {
  27. $phoneUtil = \libphonenumber\PhoneNumberUtil::getInstance();
  28. try {
  29. $phoneNumber = $phoneUtil->parse($input, $defaultRegion);
  30. if ($phoneUtil->isValidNumber($phoneNumber)) {
  31. return $phoneUtil->format($phoneNumber, PhoneNumberFormat::E164);
  32. }
  33. } catch (NumberParseException) {
  34. }
  35. return null;
  36. }
  37. }