parse() public method

It will accept a number in any format (E164, national, international etc), assuming it can interpreted with the defaultRegion supplied. It also attempts to convert any alpha characters into digits if it thinks this is a vanity number of the type "1800 MICROSOFT".

This method will throw a {@link NumberParseException} if the number is not considered to be a possible number. Note that validation of whether the number is actually a valid number for a particular region is not performed. This can be done separately with {@link #isValidnumber}.

public parse ( string $numberToParse, string $defaultRegion, PhoneNumber $phoneNumber = null, boolean $keepRawInput = false ) : PhoneNumber
$numberToParse string number that we are attempting to parse. This can contain formatting such as +, ( and -, as well as a phone number extension.
$defaultRegion string region that we are expecting the number to be from. This is only used if the number being parsed is not written in international format. The country_code for the number in this case would be stored as that of the default region supplied. If the number is guaranteed to start with a '+' followed by the country calling code, then "ZZ" or null can be supplied.
$phoneNumber PhoneNumber
$keepRawInput boolean
return PhoneNumber a phone number proto buffer filled with the parsed number
 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);
 }
 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'));
 }
 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"));
 }
 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));
 }
 public function testSerializingPhoneNumber()
 {
     $number = "+441174900000";
     $region = "GB";
     $phoneNumber = $this->phoneUtil->parse($number, $region);
     $serializedString = serialize($phoneNumber);
     $phoneObject2 = unserialize($serializedString);
     $this->assertTrue($phoneObject2->equals($phoneNumber));
 }
 public function filter($value)
 {
     try {
         $NumberProto = $this->libPhoneNumber->parse($value, $this->getCountry());
     } catch (NumberParseException $e) {
         return $value;
     }
     return $this->libPhoneNumber->format($NumberProto, PhoneNumberFormat::E164);
 }
 public function testLongerNumber()
 {
     $number = "12345678901234567";
     $phoneNumber = $this->phoneUtil->parse($number, "DE");
     $this->assertEquals('+4912345678901234567', $this->phoneUtil->format($phoneNumber, PhoneNumberFormat::E164));
     $this->assertEquals('+49 12345678901234567', $this->phoneUtil->format($phoneNumber, PhoneNumberFormat::INTERNATIONAL));
     $this->assertEquals('12345678901234567', $this->phoneUtil->format($phoneNumber, PhoneNumberFormat::NATIONAL));
     $this->assertEquals('011 49 12345678901234567', $this->phoneUtil->formatOutOfCountryCallingNumber($phoneNumber, 'US'));
     $this->assertEquals('00 49 12345678901234567', $this->phoneUtil->formatOutOfCountryCallingNumber($phoneNumber, 'CH'));
 }
 /**
  * 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;
 }
 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 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");
     }
     $number = $this->phoneUtil->getExampleNumberForType($regionCode, PhoneNumberType::FIXED_LINE_OR_MOBILE);
     $phoneNumber = $this->phoneUtil->parse($number, 'ZZ');
     $this->assertContains($regionCode, CountryCodeToRegionCodeMap::$countryCodeToRegionCodeMap[$phoneNumber->getCountryCode()]);
     $this->assertEquals($regionCode, $this->phoneUtil->getRegionCodeForNumber($number));
     $this->assertEquals($countryName, $this->geocoder->getDescriptionForValidNumber($phoneNumber, 'en', 'ZZ'), "Checking {$number} is part of {$countryName}");
 }
Beispiel #11
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;
 }
 /**
  * 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.
 }
 public function testInvalidNumber()
 {
     $number = '123401234512345';
     $phoneObject = $this->phoneUtil->parse($number, 'GB');
     $valid = $this->phoneUtil->isValidNumber($phoneObject);
     $this->assertFalse($valid, "Checking phone number is invalid");
 }
Beispiel #14
0
 /**
  * Parse msisdn
  * @param  string $number
  * @return Instance
  * @author Andraz <*****@*****.**>
  */
 public function parse($number)
 {
     try {
         $phoneNumber = $this->numberUtil->parse($number, null);
     } catch (NumberParseException $e) {
         $this->valid = false;
         return $this;
     }
     if (!($this->valid = $this->numberUtil->isValidNumber($phoneNumber))) {
         return $this;
     }
     $this->countryDiallingCode = (int) $phoneNumber->getCountryCode();
     $this->countryIdentifier = $this->numberUtil->getRegionCodeForNumber($phoneNumber);
     $this->mnoIdentifier = $this->carrierMapper->getNameForNumber($phoneNumber, 'en_US');
     $this->subscriberNumber = $phoneNumber->getNationalNumber();
     return $this;
 }
 /**
  * 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 parseAndFormat($phoneNumber, $defaultRegion, $format = PhoneNumberFormat::INTERNATIONAL)
 {
     if ($phoneNumber instanceof PhoneNumber) {
         return $this->format($phoneNumber, $format);
     }
     $phoneNumber = $this->phoneNumberUtil->parse($phoneNumber, $defaultRegion);
     return $this->format($phoneNumber, $format);
 }
 /**
  * @param string $number
  * @param string $regionCode
  * @return PhoneNumber
  */
 private function parse($number, $regionCode)
 {
     try {
         return $this->phoneUtil->parse($number, $regionCode);
     } catch (NumberParseException $e) {
         $this->fail("Test input data should always parse correctly: " . $number . " (" . $regionCode . ")");
     }
 }
 /**
  * @dataProvider transformProvider
  */
 public function testTransform(array $countryChoices, $actual, $expected)
 {
     $transformer = new PhoneNumberToArrayTransformer($countryChoices);
     if (is_array($actual)) {
         try {
             $phoneNumber = $this->phoneNumberUtil->parse($actual['number'], $actual['country']);
         } catch (NumberParseException $e) {
             $phoneNumber = $actual['number'];
         }
     } else {
         $phoneNumber = $actual['number'];
     }
     try {
         $transformed = $transformer->transform($phoneNumber);
     } catch (TransformationFailedException $e) {
         $transformed = self::TRANSFORMATION_FAILED;
     }
     $this->assertSame($expected, $transformed);
 }
Beispiel #18
0
 protected function normalizePhoneNumber($number, $externalId, $defaultRegion)
 {
     try {
         $number = $this->phoneNumberUtil->parse($number, $defaultRegion);
     } catch (NumberParseException $e) {
         $this->logger->warning("Error parsing phone number from source '%s' for entry '%s' (code %d): %s", $this->source, $externalId, $e->getCode(), $e->getMessage());
         return null;
     }
     return $this->phoneNumberUtil->format($number, PhoneNumberFormat::E164);
 }
Beispiel #19
0
 /**
  * Parse the number.
  *
  * @access public
  * @param bool $exception
  * @return $this
  */
 public function parse($exception = true)
 {
     try {
         $this->parsedResult = $this->phoneUtil->parse($this->number, "NL");
     } catch (\Exception $e) {
         if ($exception) {
             throw $e;
         }
     }
     return $this;
 }
 /**
  * @dataProvider shortNumberRegionList
  */
 public function testCarrierSpecificShortNumbers($regionCode)
 {
     // Test the carrier-specific tag.
     $desc = $this->shortNumberInfo->getMetadataForRegion($regionCode)->getCarrierSpecific();
     if ($desc->hasExampleNumber()) {
         $exampleNumber = $desc->getExampleNumber();
         $carrierSpecificNumber = $this->phoneNumberUtil->parse($exampleNumber, $regionCode);
         if (!$this->shortNumberInfo->isPossibleShortNumberForRegion($carrierSpecificNumber, $regionCode) || !$this->shortNumberInfo->isCarrierSpecific($carrierSpecificNumber)) {
             $this->fail("Carrier-specific test failed for " . $regionCode);
         }
     }
 }
Beispiel #21
0
 /**
  * @param string $number
  * @param string $country
  * @param string|NULL $locale
  * @param string|NULL $userCountry
  *
  * @return string
  *
  * @throws Exceptions\NoValidCountryException
  * @throws Exceptions\NoValidPhoneException
  */
 public function getLocation($number, $country = 'AUTO', $locale = NULL, $userCountry = NULL)
 {
     if ($this->isValid((string) $number, $country)) {
         $country = strtoupper($country);
         if ($userCountry !== NULL) {
             // Check for valid user country
             $userCountry = $this->validateCountry($userCountry);
         }
         // Parse phone number
         $parsed = $this->phoneNumberUtil->parse((string) $number, $country);
         // Determine locale
         $locale = $locale === NULL && $this->translator && method_exists($this->translator, 'getLocale') ? $this->translator->getLocale() : 'en_US';
         // Get phone number location
         return $this->phoneNumberGeocoder->getDescriptionForNumber($parsed, $locale, $userCountry);
     } else {
         throw new Exceptions\NoValidPhoneException('Provided phone number "' . $number . '" is not valid phone number. Provide valid phone number.');
     }
 }
 public function testParseItalianLeadingZeros()
 {
     // Test the number "011".
     $oneZero = new PhoneNumber();
     $oneZero->setCountryCode(61)->setNationalNumber(11)->setItalianLeadingZero(true);
     $this->assertEquals($oneZero, $this->phoneUtil->parse("011", RegionCode::AU));
     // Test the number "001".
     $twoZeros = new PhoneNumber();
     $twoZeros->setCountryCode(61)->setNationalNumber(1)->setItalianLeadingZero(true)->setNumberOfLeadingZeros(2);
     $this->assertEquals($twoZeros, $this->phoneUtil->parse("001", RegionCode::AU));
     // Test the number "000". This number has 2 leading zeros.
     $stillTwoZeros = new PhoneNumber();
     $stillTwoZeros->setCountryCode(61)->setNationalNumber(0)->setItalianLeadingZero(true)->setNumberOfLeadingZeros(2);
     $this->assertEquals($stillTwoZeros, $this->phoneUtil->parse("000", RegionCode::AU));
     // Test the number "0000". This number has 3 leading zeros.
     $threeZeros = new PhoneNumber();
     $threeZeros->setCountryCode(61)->setNationalNumber(0)->setItalianLeadingZero(true)->setNumberOfLeadingZeros(3);
     $this->assertEquals($threeZeros, $this->phoneUtil->parse("0000", RegionCode::AU));
 }
 public function testParseNationalNumber()
 {
     // National prefix attached.
     $this->assertEquals(self::$nzNumber, $this->phoneUtil->parse("033316005", RegionCode::NZ));
     $this->assertEquals(self::$nzNumber, $this->phoneUtil->parse("33316005", RegionCode::NZ));
     // National prefix attached and some formatting present.
     $this->assertEquals(self::$nzNumber, $this->phoneUtil->parse("03-331 6005", RegionCode::NZ));
     $this->assertEquals(self::$nzNumber, $this->phoneUtil->parse("03 331 6005", RegionCode::NZ));
     // Testing international prefixes.
     // Should strip country calling code.
     $this->assertEquals(self::$nzNumber, $this->phoneUtil->parse("0064 3 331 6005", RegionCode::NZ));
     // Try again, but this time we have an international number with Region Code US. It should
     // recognise the country calling code and parse accordingly.
     $this->assertEquals(self::$nzNumber, $this->phoneUtil->parse("01164 3 331 6005", RegionCode::US));
     $this->assertEquals(self::$nzNumber, $this->phoneUtil->parse("+64 3 331 6005", RegionCode::US));
     // We should ignore the leading plus here, since it is not followed by a valid country code but
     // instead is followed by the IDD for the US.
     $this->assertEquals(self::$nzNumber, $this->phoneUtil->parse("+01164 3 331 6005", RegionCode::US));
     $this->assertEquals(self::$nzNumber, $this->phoneUtil->parse("+0064 3 331 6005", RegionCode::NZ));
     $this->assertEquals(self::$nzNumber, $this->phoneUtil->parse("+ 00 64 3 331 6005", RegionCode::NZ));
     $nzNumber = new PhoneNumber();
     $nzNumber->setCountryCode(64)->setNationalNumber(64123456);
     $this->assertEquals($nzNumber, $this->phoneUtil->parse("64(0)64123456", RegionCode::NZ));
     // Check that using a "/" is fine in a phone number.
     $this->assertEquals(self::$deNumber, $this->phoneUtil->parse("301/23456", RegionCode::DE));
     $usNumber = new PhoneNumber();
     // Check it doesn't use the '1' as a country calling code when parsing if the phone number was
     // already possible.
     $usNumber->setCountryCode(1)->setNationalNumber(1234567890);
     $this->assertEquals($usNumber, $this->phoneUtil->parse("123-456-7890", RegionCode::US));
     // Test star numbers. Although this is not strictly valid, we would like to make sure we can
     // parse the output we produce when formatting the number.
     $this->assertEquals(self::$jpStarNumber, $this->phoneUtil->parse("+81 *2345", RegionCode::JP));
     // Test national number bigger than max 32-bit signed integer
     $inNumber = new PhoneNumber();
     $inNumber->setCountryCode(55)->setNationalNumber(9876543210);
     $this->assertEquals($inNumber, $this->phoneUtil->parse("9876543210", RegionCode::BR));
 }
 public function testIsleOfManLocale()
 {
     $number = "447624806000";
     $phoneNumber = $this->phoneUtil->parse($number, 'GB');
     $this->assertEquals("Isle of Man", $this->geocoder->getDescriptionForNumber($phoneNumber, 'en'));
 }
 public function testParseUSNumber()
 {
     $number = $this->phoneNumberUtil->parse('011543549480042', 'US');
     $this->assertEquals("+543549480042", $this->phoneNumberUtil->format($number, PhoneNumberFormat::E164));
 }
 public function testConvertToPHPValueWithAPhoneNumberInstance()
 {
     $expectedPhoneNumber = $this->phoneNumberUtil->parse('+441234567890', PhoneNumberUtil::UNKNOWN_REGION);
     $phoneNumber = $this->type->convertToPHPValue($expectedPhoneNumber, $this->platform);
     $this->assertEquals($expectedPhoneNumber, $phoneNumber);
 }
Beispiel #27
0
 public function testParseUSNumber()
 {
     $number = $this->phoneNumberUtil->parse('0351-152-303-473', 'AR');
     $this->assertEquals("+5493512303473", $this->phoneNumberUtil->format($number, PhoneNumberFormat::E164));
 }
 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'));
 }
 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;
 }
 /**
  * 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);
 }