aboutsummaryrefslogtreecommitdiffstats
path: root/lib/private/PhoneNumberUtil.php
blob: e53c7a51a1bb954e2777b747aaaa0fb56a7ce833 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
<?php

declare(strict_types=1);
/**
 * SPDX-FileCopyrightText: 2023 Nextcloud GmbH and Nextcloud contributors
 * SPDX-License-Identifier: AGPL-3.0-or-later
 */

namespace OC;

use libphonenumber\NumberParseException;
use libphonenumber\PhoneNumberFormat;
use OCP\IPhoneNumberUtil;

/**
 * @since 28.0.0
 */
class PhoneNumberUtil implements IPhoneNumberUtil {
	/**
	 * {@inheritDoc}
	 */
	public function getCountryCodeForRegion(string $regionCode): ?int {
		$phoneUtil = \libphonenumber\PhoneNumberUtil::getInstance();
		$countryCode = $phoneUtil->getCountryCodeForRegion($regionCode);
		return $countryCode === 0 ? null : $countryCode;
	}

	/**
	 * {@inheritDoc}
	 */
	public function convertToStandardFormat(string $input, ?string $defaultRegion = null): ?string {
		$phoneUtil = \libphonenumber\PhoneNumberUtil::getInstance();
		try {
			$phoneNumber = $phoneUtil->parse($input, $defaultRegion);
			if ($phoneUtil->isValidNumber($phoneNumber)) {
				return $phoneUtil->format($phoneNumber, PhoneNumberFormat::E164);
			}
		} catch (NumberParseException) {
		}

		return null;
	}
}