You are here

public function MobileNumberUtil::testMobileNumber in Mobile Number 8

Same name and namespace in other branches
  1. 2.0.x src/MobileNumberUtil.php \Drupal\mobile_number\MobileNumberUtil::testMobileNumber()

Test mobile number validity.

Parameters

string $number: Number.

null|string $country: Country.

array $types: Mobile number types to verify as defined in \libphonenumber\PhoneNumberType.

Return value

\libphonenumber\PhoneNumber Libphonenumber Phone number object.

Throws

\Drupal\mobile_number\Exception\MobileNumberException Thrown if mobile number is not valid.

Overrides MobileNumberUtilInterface::testMobileNumber

1 call to MobileNumberUtil::testMobileNumber()
MobileNumberUtil::getMobileNumber in src/MobileNumberUtil.php
Get mobile number object.

File

src/MobileNumberUtil.php, line 123

Class

MobileNumberUtil
Turns a render array into a HTML string.

Namespace

Drupal\mobile_number

Code

public function testMobileNumber($number, $country = NULL, $types = [
  1 => 1,
  2 => 2,
]) {
  if (!$number) {
    throw new MobileNumberException('Empty number', MobileNumberException::ERROR_NO_NUMBER);
  }
  try {

    /** @var \libphonenumber\PhoneNumber $phone_number */
    $phone_number = $this->libUtil
      ->parse($number, $country);
  } catch (NumberParseException $e) {
    throw new MobileNumberException('Invalid number or unknown country', MobileNumberException::ERROR_INVALID_NUMBER);
  }
  if ($types) {
    if (!in_array($this->libUtil
      ->getNumberType($phone_number), $types)) {
      throw new MobileNumberException('Not a mobile number', MobileNumberException::ERROR_WRONG_TYPE);
    }
  }
  $mcountry = $this->libUtil
    ->getRegionCodeForNumber($phone_number);
  if ($country && $mcountry != $country) {
    throw new MobileNumberException('Mismatch country with the number\'s prefix', MobileNumberException::ERROR_WRONG_COUNTRY);
  }
  return $phone_number;
}