getInstance() публичный статический Метод

The {@link PhoneNumberUtil} is implemented as a singleton. Therefore, calling getInstance multiple times will only result in one instance being created.

public static getInstance ( string $baseFileLocation = self::META_DATA_FILE_PREFIX, array $countryCallingCodeToRegionCodeMap = null, libphonenumber\MetadataLoaderInterface $metadataLoader = null, libphonenumber\MetadataSourceInterface $metadataSource = null ) : PhoneNumberUtil
$baseFileLocation string
$countryCallingCodeToRegionCodeMap array
$metadataLoader libphonenumber\MetadataLoaderInterface
$metadataSource libphonenumber\MetadataSourceInterface
Результат PhoneNumberUtil instance
 /**
  * @param mixed $value
  * @return array|null
  */
 protected function validateValue($value)
 {
     $valid = false;
     $phoneUtil = PhoneNumberUtil::getInstance();
     try {
         $phoneProto = $phoneUtil->parse($value, null);
         // pe($phoneProto);
         if (!empty($this->region) && $this->region !== null) {
             if (is_array($this->region)) {
                 foreach ($this->region as $region) {
                     if ($phoneUtil->isValidNumberForRegion($phoneProto, $region)) {
                         $valid = true;
                         break;
                     }
                 }
             } else {
                 if ($phoneUtil->isValidNumberForRegion($phoneProto, $this->region)) {
                     $valid = true;
                 }
             }
         } else {
             if ($phoneUtil->isValidNumber($phoneProto)) {
                 $valid = true;
             }
         }
     } catch (NumberParseException $e) {
         var_dump($e);
     }
     return $valid ? null : [$this->message, []];
 }
Пример #2
0
 /**
  * Validate attribute
  *
  * @param \yii\base\Model $model
  * @param string $attribute
  *
  * @return bool|void
  */
 public function validateAttribute($model, $attribute)
 {
     $country = '';
     if ($this->country !== null) {
         $country = $this->country;
     } elseif ($this->countryAttribute !== null) {
         $country = $model->{$this->countryAttribute};
     } elseif ($this->countryCodeAttribute !== null) {
         $country = $model->{$this->countryCodeAttribute};
     }
     // if empty country and used strict mode
     if (empty($country) && $this->strict) {
         $this->addError($model, $attribute, Yii::t('app', $this->strictModeMessage));
         return false;
     }
     if (empty($country)) {
         return true;
     }
     $phoneUtil = PhoneNumberUtil::getInstance();
     try {
         $numberProto = $phoneUtil->parse($model->{$attribute}, $country);
         if ($phoneUtil->isValidNumber($numberProto)) {
             if ($this->format) {
                 $model->{$attribute} = $phoneUtil->format($numberProto, PhoneNumberFormat::INTERNATIONAL);
             }
             return true;
         } else {
             $this->addError($model, $attribute, Yii::t('app', $this->message));
             return false;
         }
     } catch (NumberParseException $e) {
         $this->addError($model, $attribute, Yii::t('app', $this->numberParseExceptionMessage));
     }
 }
 /**
  * Register the service provider.
  *
  * @return void
  */
 public function register()
 {
     // Make libphonenumber available in the application container.
     $this->app->singleton('libphonenumber', function ($app) {
         return PhoneNumberUtil::getInstance();
     });
 }
Пример #4
0
 public function __construct($options = [])
 {
     $this->libPhoneNumber = PhoneNumberUtil::getInstance();
     if (array_key_exists('country', $options)) {
         $this->setCountry($options['country']);
     }
 }
Пример #5
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;
 }
 protected function setUp()
 {
     $this->platform = $this->getMockBuilder('Doctrine\\DBAL\\Platforms\\AbstractPlatform')->setMethods(array('getVarcharTypeDeclarationSQL'))->getMockForAbstractClass();
     $this->platform->expects($this->any())->method('getVarcharTypeDeclarationSQL')->will($this->returnValue('DUMMYVARCHAR()'));
     $this->type = Type::getType('phone_number');
     $this->phoneNumberUtil = PhoneNumberUtil::getInstance();
 }
Пример #7
0
 public function unsubscribe($number)
 {
     $phoneUtil = PhoneNumberUtil::getInstance();
     $phoneNumber = $phoneUtil->parse($number, 'US');
     $number = $phoneUtil->format($phoneNumber, PhoneNumberFormat::E164);
     /** @var \Mautic\LeadBundle\Entity\LeadRepository $repo */
     $repo = $this->factory->getEntityManager()->getRepository('MauticLeadBundle:Lead');
     $args = array('filter' => array('force' => array(array('column' => 'mobile', 'expr' => 'eq', 'value' => $number))));
     $leads = $repo->getEntities($args);
     if (!empty($leads)) {
         $lead = array_shift($leads);
     } else {
         // Try to find the lead based on the given phone number
         $args['filter']['force'][0]['column'] = 'phone';
         $leads = $repo->getEntities($args);
         if (!empty($leads)) {
             $lead = array_shift($leads);
         } else {
             return false;
         }
     }
     /** @var \Mautic\LeadBundle\Model\LeadModel $leadModel */
     $leadModel = $this->factory->getModel('lead.lead');
     return $leadModel->addDncForLead($lead, 'sms', null, DoNotContact::UNSUBSCRIBED);
 }
Пример #8
0
 /**
  * @return mixed
  */
 public function getPhoneNumberService()
 {
     if ($this->phoneNumberService === null) {
         $this->phoneNumberService = PhoneNumberUtil::getInstance();
     }
     return $this->phoneNumberService;
 }
 /**
  * Register the service provider.
  *
  * @return void
  */
 public function register()
 {
     $this->app->singleton('libphonenumber', function ($app) {
         return PhoneNumberUtil::getInstance();
     });
     $this->app->alias('libphonenumber', 'libphonenumber\\PhoneNumberUtil');
 }
Пример #10
0
function phone_format($phone, $country, $format = null)
{
    $phoneUtil = \libphonenumber\PhoneNumberUtil::getInstance();
    $phoneProto = $phoneUtil->parse($phone, $country);
    $format = is_null($format) ? \libphonenumber\PhoneNumberFormat::INTERNATIONAL : $format;
    return $phoneUtil->format($phoneProto, $format);
}
Пример #11
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;
     }
 }
Пример #12
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);
 }
 /**
  * PhoneNumberModel constructor.
  * @param string $phone_number
  * @param string $country_code An ISO 3166-1 two letter country code
  */
 public function __construct($phone_number, $country_code)
 {
     $this->phoneUtil = PhoneNumberUtil::getInstance();
     $this->phoneNumberProto = phone_parse($phone_number, $country_code);
     $this->raw_input_country = $country_code;
     $this->parse();
 }
Пример #14
0
 public function setUp()
 {
     PhoneNumberUtil::resetInstance();
     PhoneNumberOfflineGeocoder::resetInstance();
     $this->phoneUtil = PhoneNumberUtil::getInstance();
     $this->geocoder = PhoneNumberOfflineGeocoder::getInstance();
 }
 /**
  * {@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']));
     }
 }
Пример #16
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);
 }
Пример #17
0
 /**
  * Validates a phone number field using libphonenumber.
  */
 public function phone($attribute, $value, $parameters, $validator)
 {
     $data = $validator->getData();
     // Check if we should validate using a default country or a *_country field.
     if (!empty($parameters)) {
         $countries = $parameters;
     } elseif (isset($data[$attribute . '_country'])) {
         $countries = array($data[$attribute . '_country']);
     } else {
         return FALSE;
     }
     // Filter out invalid countries.
     foreach ($countries as $key => $country) {
         if (!$this->phone_country($country)) {
             unset($countries[$key]);
         }
     }
     // Now try each country during validation.
     foreach ($countries as $country) {
         $phoneUtil = \libphonenumber\PhoneNumberUtil::getInstance();
         try {
             $phoneProto = $phoneUtil->parse($value, $country);
             if ($phoneUtil->isValidNumber($phoneProto)) {
                 return TRUE;
             }
         } catch (\libphonenumber\NumberParseException $e) {
         }
     }
     return FALSE;
 }
 /**
  * @param mixed $value
  * @return array|null
  */
 protected function validateValue($value)
 {
     $valid = false;
     $phoneUtil = PhoneNumberUtil::getInstance();
     try {
         $phoneProto = $phoneUtil->parse($value, null);
         if ($this->region !== null) {
             $regions = is_array($this->region) ? $this->region : [$this->region];
             foreach ($regions as $region) {
                 if ($phoneUtil->isValidNumberForRegion($phoneProto, $region)) {
                     $valid = true;
                     break;
                 }
             }
         } else {
             if ($phoneUtil->isValidNumber($phoneProto)) {
                 $valid = true;
             }
         }
         if ($this->type !== null) {
             if (PhoneNumberType::UNKNOWN != ($type = $phoneUtil->getNumberType($phoneProto))) {
                 $valid = $valid && $type == $this->type;
             }
         }
     } catch (NumberParseException $e) {
     }
     return $valid ? null : [$this->message, []];
 }
Пример #19
0
 public function __construct($ofService=null){
     $this->phoneUtil =  \libphonenumber\PhoneNumberUtil::getInstance();
     if($ofService==null) {
         $this->ofService = new OpenFireService();
     }else{
         $this->ofService = $ofService;
     }
 }
Пример #20
0
 /**
  * Test if construct set number util
  * @return void
  * @author Andraz <*****@*****.**>
  */
 public function test_construct()
 {
     $numberUtil = PhoneNumberUtil::getInstance();
     $carrierMapper = PhoneNumberToCarrierMapper::getInstance();
     $instance = new Instance($numberUtil, $carrierMapper);
     $this->assertInstanceOf('libphonenumber\\PhoneNumberUtil', $instance->getNumberUtil());
     $this->assertInstanceOf('libphonenumber\\PhoneNumberToCarrierMapper', $instance->getCarrierMapper());
 }
Пример #21
0
 private function getExampleNumber($region)
 {
     $phoneUtil = PhoneNumberUtil::getInstance();
     $exampleNumber = $phoneUtil->getExampleNumber($region);
     // Reset PhoneNumberUtil just to make sure that doesn't interfere
     PhoneNumberUtil::resetInstance();
     return $exampleNumber;
 }
 public function setUp()
 {
     self::$plusSymbol = pack('H*', 'efbc8b');
     PhoneNumberUtil::resetInstance();
     ShortNumberInfo::resetInstance();
     $this->phoneUtil = PhoneNumberUtil::getInstance(PhoneNumberUtilTest::TEST_META_DATA_FILE_PREFIX, CountryCodeToRegionCodeMapForTesting::$countryCodeToRegionCodeMapForTesting);
     $this->shortInfo = ShortNumberInfo::getInstance();
 }
Пример #23
0
 public function setUp()
 {
     PhoneNumberUtil::resetInstance();
     $this->phoneUtil = PhoneNumberUtil::getInstance();
     if (extension_loaded('intl')) {
         $this->geocoder = PhoneNumberOfflineGeocoder::getInstance();
     }
 }
 private function __construct($phonePrefixDataDirectory)
 {
     if (!extension_loaded('intl')) {
         throw new \RuntimeException('The intl extension must be installed');
     }
     $this->phoneUtil = PhoneNumberUtil::getInstance();
     $this->prefixFileReader = new PrefixFileReader(dirname(__FILE__) . $phonePrefixDataDirectory);
 }
Пример #25
0
 function __construct()
 {
     $this->authId = trim($this->getConnectorParam('auth_id'));
     $this->authToken = trim($this->getConnectorParam('auth_token'));
     $this->srcPhone = trim($this->getConnectorParam('src_phone'));
     $this->logger = LoggerManager::getLogger();
     $this->service = Bickart\Plivo\PlivoService::make($this->authId, $this->authToken);
     $this->phoneUtil = \libphonenumber\PhoneNumberUtil::getInstance();
 }
Пример #26
0
 public function setUp()
 {
     if (!extension_loaded('intl')) {
         $this->markTestSkipped('The intl extension must be installed');
     }
     PhoneNumberUtil::resetInstance();
     $this->phoneUtil = PhoneNumberUtil::getInstance();
     $this->geocoder = PhoneNumberOfflineGeocoder::getInstance();
 }
 /**
  * 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);
 }
Пример #28
0
 public function __construct($source, $AppName, AppLogger $logger, IConfig $config, IDBConnection $db, AppSettings $appSettings)
 {
     $this->appName = $AppName;
     $this->config = $config;
     $this->source = $source;
     $this->appSettings = $appSettings;
     $this->db = $db;
     $this->logger = $logger;
     $this->phoneNumberUtil = PhoneNumberUtil::getInstance();
 }
Пример #29
0
 public function __construct($region = '')
 {
     if (!class_exists('\\libphonenumber\\PhoneNumberUtil')) {
         throw new \RuntimeException('giggsey/libphonenumber-for-php library not installed');
     }
     if (!empty($region)) {
         $this->setDefaultRegion($region);
     }
     $this->instance = \libphonenumber\PhoneNumberUtil::getInstance();
 }
Пример #30
0
 /**
  * Set the value of Numéro de téléphone concernant le profil
  *
  * @param string|null professional_phone_number
  * @throws InvalidPhoneNumberException
  *
  * @return self
  */
 public function setPhoneNumber($phone_number)
 {
     $phone_util = PhoneNumberUtil::getInstance();
     $phone_number_parsed = $phone_util->parse($phone_number, "FR");
     if (!$phone_util->isValidNumber($phone_number_parsed)) {
         throw new InvalidPhoneNumberException("Format du numéro de téléphone professionnel incorrect.");
     }
     $this->phone_number = $phone_util->format($phone_number_parsed, PhoneNumberFormat::NATIONAL);
     return $this;
 }