If you use this library, and want to be notified about important changes, please sign up to our mailing list. NOTE: A lot of methods in this class require Region Code strings. These must be provided using ISO 3166-1 two-letter country-code format. These should be in upper-case. The list of the codes can be found here: http://www.iso.org/iso/country_codes/iso_3166_code_lists/country_names_and_code_elements.htm

Author: Shaopeng Jia
Author: Lara Rennie
 public function testDenormalize()
 {
     $obj = $this->numberUtil->parse('+31508100210', PhoneNumberUtil::UNKNOWN_REGION);
     $str = '+31508100210';
     self::assertEquals($obj, $this->normalizer->denormalize($str, 'json'));
     self::assertEquals($obj, $this->normalizer->denormalize($str, 'xml'));
 }
Exemplo n.º 2
1
 public function testChineseCarrierLookup()
 {
     $number = $this->phoneUtil->parse("+86 150 3657 7264", "CN");
     $carrier = PhoneNumberToCarrierMapper::getInstance();
     $location = $carrier->getNameForNumber($number, "en");
     $this->assertEquals("China Mobile", $location);
 }
Exemplo n.º 3
0
 public function testIsValidNumberForRegion()
 {
     $number = "+33 6 76 83 51 85";
     $region = "DE";
     $phoneNumber = $this->phoneUtil->parse($number, $region);
     $this->assertFalse($this->phoneUtil->isValidNumberForRegion($phoneNumber, "DE"));
 }
Exemplo n.º 4
0
 public function testKWMobileNumber()
 {
     $number = "51440519";
     $phoneNumber = $this->phoneUtil->parse($number, "KW");
     $this->assertTrue($this->phoneUtil->isValidNumber($phoneNumber));
     $this->assertEquals(PhoneNumberType::MOBILE, $this->phoneUtil->getNumberType($phoneNumber));
 }
Exemplo n.º 5
0
 public function filter($value)
 {
     try {
         $NumberProto = $this->libPhoneNumber->parse($value, $this->getCountry());
     } catch (NumberParseException $e) {
         return $value;
     }
     return $this->libPhoneNumber->format($NumberProto, PhoneNumberFormat::E164);
 }
Exemplo n.º 6
0
 public function testSerializingPhoneNumber()
 {
     $number = "+441174900000";
     $region = "GB";
     $phoneNumber = $this->phoneUtil->parse($number, $region);
     $serializedString = serialize($phoneNumber);
     $phoneObject2 = unserialize($serializedString);
     $this->assertTrue($phoneObject2->equals($phoneNumber));
 }
 /**
  * @dataProvider localeList
  * @param string $regionCode
  * @param string $countryName
  */
 public function testLocales($regionCode, $countryName)
 {
     if (!in_array($regionCode, $this->phoneUtil->getSupportedRegions())) {
         $this->markTestSkipped("{$regionCode} is not supported");
     }
     $phoneNumber = $this->phoneUtil->getExampleNumberForType($regionCode, PhoneNumberType::FIXED_LINE_OR_MOBILE);
     $this->assertContains($regionCode, CountryCodeToRegionCodeMap::$countryCodeToRegionCodeMap[$phoneNumber->getCountryCode()]);
     $this->assertEquals($regionCode, $this->phoneUtil->getRegionCodeForNumber($phoneNumber));
     $this->assertEquals($countryName, $this->geocoder->getDescriptionForValidNumber($phoneNumber, 'en', 'ZZ'), "Checking {$phoneNumber} is part of {$countryName}");
 }
 /**
  * As per {@link #getTimeZonesForGeographicalNumber(PhoneNumber)} but explicitly checks
  * the validity of the number passed in.
  *
  * @param $number PhoneNumber the phone number for which we want to get the time zones to which it belongs
  * @return array a list of the corresponding time zones or a single element list with the default
  *     unknown time zone if no other time zone was found or if the number was invalid
  */
 public function getTimeZonesForNumber(PhoneNumber $number)
 {
     $numberType = $this->phoneUtil->getNumberType($number);
     if ($numberType === PhoneNumberType::UNKNOWN) {
         return $this->unknownTimeZoneList;
     } elseif (!$this->canBeGeocoded($numberType)) {
         return $this->getCountryLevelTimeZonesforNumber($number);
     }
     return $this->getTimeZonesForGeographicalNumber($number);
 }
 /**
  * Returns a plain phonenumber readable for mobile devices
  *
  * @param string $phoneNumber Formatted Phone Number
  * @return string
  */
 public function render($phoneNumber)
 {
     $plainPhoneNumber = '';
     if ($phoneNumber) {
         /** @var \libphonenumber\PhoneNumber $plainPhoneNumberPrototype */
         $plainPhoneNumberPrototype = $this->phoneNumberUtility->parse($phoneNumber, 'DE');
         $plainPhoneNumber = $this->phoneNumberUtility->format($plainPhoneNumberPrototype, \libphonenumber\PhoneNumberFormat::RFC3966);
     }
     return $plainPhoneNumber;
 }
 /**
  * As per {@link #getTimeZonesForGeographicalNumber(PhoneNumber)} but explicitly checks
  * the validity of the number passed in.
  *
  * @param $number PhoneNumber the phone number for which we want to get the time zones to which it belongs
  * @return array a list of the corresponding time zones or a single element list with the default
  *     unknown time zone if no other time zone was found or if the number was invalid
  */
 public function getTimeZonesForNumber(PhoneNumber $number)
 {
     $numberType = $this->phoneUtil->getNumberType($number);
     if ($numberType === PhoneNumberType::UNKNOWN) {
         return $this->unknownTimeZoneList;
     } elseif (!!PhoneNumberUtil::getInstance()->isNumberGeographical($numberType, $number->getCountryCode())) {
         return $this->getCountryLevelTimeZonesforNumber($number);
     }
     return $this->getTimeZonesForGeographicalNumber($number);
 }
 /**
  * Format a phone number.
  *
  * @param PhoneNumber $phoneNumber Phone number.
  * @param int|string  $format      Format, or format constant name.
  *
  * @return string Formatted phone number.
  *
  * @throws InvalidArgumentException If an argument is invalid.
  */
 public function format(PhoneNumber $phoneNumber, $format = PhoneNumberFormat::INTERNATIONAL)
 {
     if (true === is_string($format)) {
         $constant = '\\libphonenumber\\PhoneNumberFormat::' . $format;
         if (false === defined($constant)) {
             throw new InvalidArgumentException('The format must be either a constant value or name in libphonenumber\\PhoneNumberFormat');
         }
         $format = constant('\\libphonenumber\\PhoneNumberFormat::' . $format);
     }
     return $this->phoneNumberUtil->format($phoneNumber, $format);
 }
Exemplo n.º 12
0
 public function testTooShortNumber()
 {
     try {
         $this->phoneUtil->parse("+441", "GB");
     } catch (\Exception $e) {
         $this->assertEquals("libphonenumber\\NumberParseException", get_class($e));
         $this->assertEquals("The string supplied is too short to be a phone number.", $e->getMessage());
         $this->assertEquals(3, $e->getCode());
         $this->assertEquals("Error type: 3. The string supplied is too short to be a phone number.", (string) $e);
     }
 }
 /**
  * @dataProvider reverseTransformProvider
  */
 public function testReverseTransform($defaultRegion, $actual, $expected)
 {
     $transformer = new PhoneNumberToStringTransformer($defaultRegion);
     try {
         $transformed = $transformer->reverseTransform($actual);
     } catch (TransformationFailedException $e) {
         $transformed = self::TRANSFORMATION_FAILED;
     }
     if ($transformed instanceof PhoneNumber) {
         $transformed = $this->phoneNumberUtil->format($transformed, PhoneNumberFormat::E164);
     }
     $this->assertSame($expected, $transformed);
 }
 /**
  * Returns the description of the geographical area the {@code number} corresponds to. This method
  * distinguishes the case of an invalid prefix and a prefix for which the name is not available in
  * the current language. If the description is not available in the current language an empty
  * string is returned. If no description was found for the provided number, null is returned.
  *
  * @internal param \libphonenumber\PhoneNumber $number the phone number to look up
  * @param \libphonenumber\PhoneNumber $phoneNumber
  * @return string|null bla the description of the geographical area
  */
 public function lookup(PhoneNumber $phoneNumber)
 {
     if (count($this->areaCodeMapStorage) == 0) {
         return null;
     }
     $phonePrefix = $phoneNumber->getCountryCode() . $this->phoneUtil->getNationalSignificantNumber($phoneNumber);
     while (strlen($phonePrefix) > 0) {
         if (array_key_exists($phonePrefix, $this->areaCodeMapStorage)) {
             return $this->areaCodeMapStorage[$phonePrefix];
         }
         $phonePrefix = substr($phonePrefix, 0, -1);
     }
     return null;
 }
 /**
  * {@inheritdoc}
  */
 public function buildForm(FormBuilderInterface $builder, array $options)
 {
     if (self::WIDGET_COUNTRY_CHOICE === $options['widget']) {
         $util = PhoneNumberUtil::getInstance();
         $countries = array();
         if (is_array($options['country_choices'])) {
             foreach ($options['country_choices'] as $country) {
                 $code = $util->getCountryCodeForRegion($country);
                 if ($code) {
                     $countries[$country] = $code;
                 }
             }
         }
         if (empty($countries)) {
             foreach ($util->getSupportedRegions() as $country) {
                 $countries[$country] = $util->getCountryCodeForRegion($country);
             }
         }
         $countryChoices = array();
         foreach (Intl::getRegionBundle()->getCountryNames() as $region => $name) {
             if (false === isset($countries[$region])) {
                 continue;
             }
             $countryChoices[$region] = sprintf('%s (+%s)', $name, $countries[$region]);
         }
         $countryOptions = $numberOptions = array('error_bubbling' => true, 'required' => $options['required'], 'disabled' => $options['disabled'], 'translation_domain' => $options['translation_domain']);
         $countryOptions['required'] = true;
         $countryOptions['choices'] = $countryChoices;
         $countryOptions['preferred_choices'] = $options['preferred_country_choices'];
         $countryOptions['choice_translation_domain'] = false;
         $builder->add('country', 'choice', $countryOptions)->add('number', 'text', $numberOptions)->addViewTransformer(new PhoneNumberToArrayTransformer(array_keys($countryChoices)));
     } else {
         $builder->addViewTransformer(new PhoneNumberToStringTransformer($options['default_region'], $options['format']));
     }
 }
 public static function setUpBeforeClass()
 {
     PhoneNumberUtil::resetInstance();
     self::$AO_MOBILE1 = new PhoneNumber();
     self::$AO_MOBILE1->setCountryCode(244)->setNationalNumber(917654321);
     self::$AO_MOBILE2 = new PhoneNumber();
     self::$AO_MOBILE2->setCountryCode(244)->setNationalNumber(927654321);
     self::$AO_FIXED1 = new PhoneNumber();
     self::$AO_FIXED1->setCountryCode(244)->setNationalNumber(22254321);
     self::$AO_FIXED2 = new PhoneNumber();
     self::$AO_FIXED2->setCountryCode(244)->setNationalNumber(26254321);
     self::$AO_INVALID_NUMBER = new PhoneNumber();
     self::$AO_INVALID_NUMBER->setCountryCode(244)->setNationalNumber(101234);
     self::$UK_MOBILE1 = new PhoneNumber();
     self::$UK_MOBILE1->setCountryCode(44)->setNationalNumber(7387654321);
     self::$UK_MOBILE2 = new PhoneNumber();
     self::$UK_MOBILE2->setCountryCode(44)->setNationalNumber(7487654321);
     self::$UK_FIXED1 = new PhoneNumber();
     self::$UK_FIXED1->setCountryCode(44)->setNationalNumber(1123456789);
     self::$UK_FIXED2 = new PhoneNumber();
     self::$UK_FIXED2->setCountryCode(44)->setNationalNumber(2987654321);
     self::$UK_INVALID_NUMBER = new PhoneNumber();
     self::$UK_INVALID_NUMBER->setCountryCode(44)->setNationalNumber(7301234);
     self::$UK_PAGER = new PhoneNumber();
     self::$UK_PAGER->setCountryCode(44)->setNationalNumber(7601234567);
     self::$US_FIXED_OR_MOBILE = new PhoneNumber();
     self::$US_FIXED_OR_MOBILE->setCountryCode(1)->setNationalNumber(6502123456);
     self::$NUMBER_WITH_INVALID_COUNTRY_CODE = new PhoneNumber();
     self::$NUMBER_WITH_INVALID_COUNTRY_CODE->setCountryCode(999)->setNationalNumber(2423651234);
     self::$INTERNATIONAL_TOLL_FREE = new PhoneNumber();
     self::$INTERNATIONAL_TOLL_FREE->setCountryCode(800)->setNationalNumber(12345678);
 }
Exemplo n.º 17
0
 /**
  * Validates a phone number.
  */
 public function validatePhone($attribute, $value, $parameters, $validator)
 {
     $this->attribute = $attribute;
     $this->data = $validator->getData();
     $this->parameters = array_map('strtoupper', $parameters);
     $this->determineCountries();
     $this->determineTypes();
     $this->checkLeftoverParameters();
     $phoneUtil = PhoneNumberUtil::getInstance();
     // Perform validation.
     foreach ($this->allowedCountries as $country) {
         try {
             // For default countries or country field, the following throws NumberParseException if
             // not parsed correctly against the supplied country.
             // For automatic detection: tries to discover the country code using from the number itself.
             $phoneProto = $phoneUtil->parse($value, $country);
             // For automatic detection, the number should have a country code.
             // Check if type is allowed.
             if ($phoneProto->hasCountryCode() && empty($this->allowedTypes) || in_array($phoneUtil->getNumberType($phoneProto), $this->allowedTypes)) {
                 // Automatic detection:
                 if ($country == 'ZZ') {
                     // Validate if the international phone number is valid for its contained country.
                     return $phoneUtil->isValidNumber($phoneProto);
                 }
                 // Force validation of number against the specified country.
                 return $phoneUtil->isValidNumberForRegion($phoneProto, $country);
             }
         } catch (NumberParseException $e) {
             // Proceed to default validation error.
         }
     }
     return false;
 }
 /**
  * Gets the name of the carrier for the given phone number only when it is 'safe' to display to
  * users. A carrier name is considered safe if the number is valid and for a region that doesn't
  * support
  * {@linkplain http://en.wikipedia.org/wiki/Mobile_number_portability mobile number portability}.
  *
  * @param $number PhoneNumber the phone number for which we want to get a carrier name
  * @param $languageCode String the language code in which the name should be written
  * @return string a carrier name that is safe to display to users, or the empty string
  */
 public function getSafeDisplayName(PhoneNumber $number, $languageCode)
 {
     if ($this->phoneUtil->isMobileNumberPortableRegion($this->phoneUtil->getRegionCodeForNumber($number))) {
         return "";
     }
     return $this->getNameForNumber($number, $languageCode);
 }
Exemplo n.º 19
0
 /**
  * @expectedException \libphonenumber\NumberParseException
  * @expectedExceptionCode 1
  * @expectedExceptionMessage The string supplied did not seem to be a phone number.
  */
 public function testIssue76()
 {
     $number = '*****@*****.**';
     $region = 'DE';
     $util = PhoneNumberUtil::getInstance();
     $util->parse($number, $region);
 }
Exemplo n.º 20
0
 public function getTargetPhoneNumber($defaultRegion)
 {
     if ($this->getTargetUri() === null || !preg_match('/^sip:(\\d+)@/', $this->getTargetUri(), $matches)) {
         return null;
     }
     return PhoneNumberUtil::getInstance()->parse($matches[1], $defaultRegion);
 }
Exemplo n.º 21
0
 /**
  * Performs the actual validation of the phone number.
  *
  * @param mixed $number
  * @param null  $country
  * @return bool
  */
 protected function isValidNumber($number, $country = null)
 {
     try {
         // Throws NumberParseException if not parsed correctly against the supplied country.
         // If no country was given, tries to discover the country code from the number itself.
         $phoneNumber = $this->lib->parse($number, $country);
         // Lenient validation; doesn't need a country code.
         if ($this->lenient) {
             return $this->lib->isPossibleNumber($phoneNumber);
         }
         // For automatic detection, the number should have a country code.
         // Check if type is allowed.
         if ($phoneNumber->hasCountryCode() && (empty($this->types) || in_array($this->lib->getNumberType($phoneNumber), $this->types))) {
             // Automatic detection:
             if ($this->autodetect) {
                 // Validate if the international phone number is valid for its contained country.
                 return $this->lib->isValidNumber($phoneNumber);
             }
             // Validate number against the specified country.
             return $this->lib->isValidNumberForRegion($phoneNumber, $country);
         }
     } catch (NumberParseException $e) {
         // Proceed to default validation error.
     }
     return false;
 }
Exemplo n.º 22
0
 /**
  * Clean phone number for Twilio
  * @param string $phone
  * @return string
  */
 protected function cleanPhone($phone, $useTimezone = true)
 {
     // if Phone number is not in E164 try to parse it
     if (!preg_match('/^\\+.\\d+$/', $phone)) {
         if ($useTimezone) {
             $phoneUtil = PhoneNumberUtil::getInstance();
             try {
                 // Get country code using configure timezone
                 $tz = Carbon::now()->getTimezone();
                 $country_code = array_get($tz->getLocation(), 'country_code', 'US');
                 // Parse phone number
                 $numberProto = $phoneUtil->parse($phone, $country_code);
                 // Return phone
                 return $phoneUtil->format($numberProto, PhoneNumberFormat::E164);
             } catch (\libphonenumber\NumberParseException $e) {
                 // Invalid phone let twilio complain :D
                 return '';
             }
         }
         // Just add missing plus sing
         return '+' . $phone;
     } else {
         return $phone;
     }
 }
Exemplo n.º 23
0
 /**
  * @return mixed
  */
 public function getPhoneNumberService()
 {
     if ($this->phoneNumberService === null) {
         $this->phoneNumberService = PhoneNumberUtil::getInstance();
     }
     return $this->phoneNumberService;
 }
 public function testInvalidNumber()
 {
     $number = '123401234512345';
     $phoneObject = $this->phoneUtil->parse($number, 'GB');
     $valid = $this->phoneUtil->isValidNumber($phoneObject);
     $this->assertFalse($valid, "Checking phone number is invalid");
 }
 public function testIsMobileNumberPortableRegion()
 {
     $this->assertTrue($this->phoneUtil->isMobileNumberPortableRegion(RegionCode::US));
     $this->assertTrue($this->phoneUtil->isMobileNumberPortableRegion(RegionCode::GB));
     $this->assertFalse($this->phoneUtil->isMobileNumberPortableRegion(RegionCode::AE));
     $this->assertFalse($this->phoneUtil->isMobileNumberPortableRegion(RegionCode::BS));
 }
 /**
  * Returns a text description for the given phone number, in the language provided. The
  * description might consist of the name of the country where the phone number is from, or the
  * name of the geographical area the phone number is from if more detailed information is
  * available.
  *
  * <p>This method assumes the validity of the number passed in has already been checked, and that
  * the number is suitable for geocoding. We consider fixed-line and mobile numbers possible
  * candidates for geocoding.
  *
  * <p>If $userRegion is set, we also consider the region of the user. If the phone number is from
  * the same region as the user, only a lower-level description will be returned, if one exists.
  * Otherwise, the phone number's region will be returned, with optionally some more detailed
  * information.
  *
  * <p>For example, for a user from the region "US" (United States), we would show "Mountain View,
  * CA" for a particular number, omitting the United States from the description. For a user from
  * the United Kingdom (region "GB"), for the same number we may show "Mountain View, CA, United
  * States" or even just "United States".
  *
  * @param PhoneNumber $number a valid phone number for which we want to get a text description
  * @param string $locale the language code for which the description should be written
  * @param string $userRegion the region code for a given user. This region will be omitted from the
  *     description if the phone number comes from this region. It is a two-letter uppercase ISO
  *     country code as defined by ISO 3166-1.
  * @return string a text description for the given language code for the given phone number
  */
 public function getDescriptionForValidNumber(PhoneNumber $number, $locale, $userRegion = null)
 {
     // If the user region matches the number's region, then we just show the lower-level
     // description, if one exists - if no description exists, we will show the region(country) name
     // for the number.
     $regionCode = $this->phoneUtil->getRegionCodeForNumber($number);
     if ($userRegion == null || $userRegion == $regionCode) {
         $languageStr = Locale::getPrimaryLanguage($locale);
         $scriptStr = "";
         $regionStr = Locale::getRegion($locale);
         $mobileToken = PhoneNumberUtil::getCountryMobileToken($number->getCountryCode());
         $nationalNumber = $this->phoneUtil->getNationalSignificantNumber($number);
         if ($mobileToken !== "" && !strncmp($nationalNumber, $mobileToken, strlen($mobileToken))) {
             // In some countries, eg. Argentina, mobile numbers have a mobile token before the national
             // destination code, this should be removed before geocoding.
             $nationalNumber = substr($nationalNumber, strlen($mobileToken));
             $region = $this->phoneUtil->getRegionCodeForCountryCode($number->getCountryCode());
             try {
                 $copiedNumber = $this->phoneUtil->parse($nationalNumber, $region);
             } catch (NumberParseException $e) {
                 // If this happens, just reuse what we had.
                 $copiedNumber = $number;
             }
             $areaDescription = $this->prefixFileReader->getDescriptionForNumber($copiedNumber, $languageStr, $scriptStr, $regionStr);
         } else {
             $areaDescription = $this->prefixFileReader->getDescriptionForNumber($number, $languageStr, $scriptStr, $regionStr);
         }
         return strlen($areaDescription) > 0 ? $areaDescription : $this->getCountryNameForNumber($number, $locale);
     }
     // Otherwise, we just show the region(country) name for now.
     return $this->getRegionDisplayName($regionCode, $locale);
     // TODO: Concatenate the lower-level and country-name information in an appropriate
     // way for each language.
 }
 /**
  * Register the service provider.
  *
  * @return void
  */
 public function register()
 {
     $this->app->singleton('libphonenumber', function ($app) {
         return PhoneNumberUtil::getInstance();
     });
     $this->app->alias('libphonenumber', 'libphonenumber\\PhoneNumberUtil');
 }
Exemplo n.º 28
-1
 public function isValid($value)
 {
     if (!is_scalar($value)) {
         $this->error(self::INVALID);
         return false;
     }
     $country = $this->getCountry();
     $supportedCountries = $this->libPhoneNumber->getSupportedRegions();
     if (!in_array($country, $supportedCountries)) {
         $this->error(self::UNSUPPORTED);
         return false;
     }
     try {
         $numberProto = $this->libPhoneNumber->parse($value, $country);
     } catch (NumberParseException $e) {
         $this->error(self::INVALID_NUMBER);
         return false;
     }
     if (!$this->libPhoneNumber->isValidNumber($numberProto)) {
         $this->error(self::INVALID_NUMBER);
         return false;
     }
     $region = $this->libPhoneNumber->getRegionCodeForNumber($numberProto);
     if ($this->libPhoneNumber->isValidNumberForRegion($numberProto, $region)) {
         return true;
     }
     $this->error(self::NO_MATCH);
     return false;
 }
Exemplo n.º 29
-1
 public function testTKGeoLocation()
 {
     $number = '+6903010';
     $phoneNumber = $this->phoneUtil->parse($number, RegionCode::ZZ);
     $this->assertEquals('TK', $this->phoneUtil->getRegionCodeForNumber($phoneNumber));
     $this->assertEquals('Tokelau', $this->geocoder->getDescriptionForNumber($phoneNumber, 'en'));
 }
 /**
  * Deserialize a phone number from XML.
  *
  * @param XmlDeserializationVisitor $visitor Deserialization visitor.
  * @param SimpleXMLElement          $data    Data.
  * @param array                     $type    Type.
  *
  * @return PhoneNumber|null Phone number.
  */
 public function deserializePhoneNumberFromXml(XmlDeserializationVisitor $visitor, $data, array $type)
 {
     $attributes = $data->attributes();
     if (isset($attributes['nil'][0]) && (string) $attributes['nil'][0] === 'true' || isset($attributes['xsi:nil'][0]) && (string) $attributes['xsi:nil'][0] === 'true') {
         return null;
     }
     return $this->phoneNumberUtil->parse($data, PhoneNumberUtil::UNKNOWN_REGION);
 }