You are here

public function MobileNumber::__construct in Mobile Number 7

MobileNumber constructor.

Parameters

string $number: Number.

null|string $country: Country.

array $types: Allowed phone number types.

Throws

\Exception

File

src/MobileNumber.php, line 81

Class

MobileNumber
Class MobileNumber handles mobile number validation and verification.

Code

public function __construct($number, $country = NULL, $types = array(
  1 => 1,
  2 => 2,
)) {
  if (!$number) {
    throw new \Exception('Empty number', $this::ERROR_NO_NUMBER);
  }
  $this->libUtil = PhoneNumberUtil::getInstance();
  try {
    $phone_number = $this->libUtil
      ->parse($number, $country);
  } catch (\Exception $e) {
    throw new \Exception('Invalid number', $this::ERROR_INVALID_NUMBER);
  }
  if ($types) {
    if (!in_array($this->libUtil
      ->getNumberType($phone_number), $types)) {
      throw new \Exception('Not a mobile number', $this::ERROR_WRONG_TYPE);
    }
  }
  $this->country = $this->libUtil
    ->getRegionCodeForNumber($phone_number);
  $national_number = $phone_number
    ->getNationalNumber();
  $prefix = $this->libUtil
    ->getNddPrefixForRegion($this->country, TRUE);
  $this->localNumber = $prefix . $national_number;
  if ($country && $this->country != $country) {
    throw new \Exception('Wrong country', $this::ERROR_WRONG_COUNTRY);
  }
  $this->callableNumber = $this->libUtil
    ->format($phone_number, PhoneNumberFormat::E164);
  $this->libPhoneNumber = $phone_number;
  $this->verificationToken = '';
}