Coder Social home page Coder Social logo

phonenumber's Introduction

Brick\PhoneNumber

A phone number library for PHP.

Build Status Coverage Status Latest Stable Version Total Downloads License

This library is a thin wrapper around giggsey/libphonenumber-for-php, itself a port of Google's libphonenumber.

It provides an equivalent functionality, with the following implementation differences:

  • PhoneNumber is an immutable class; it can be safely passed around without having to worry about the risk for it to be changed;
  • PhoneNumber is not just a mere data container, but provides all the methods to parse, format and validate phone numbers; it transparently encapsulates PhoneNumberUtil;
  • PhoneNumberFormat and PhoneNumberType are native PHP enums.

Installation

This library is installable via Composer:

composer require brick/phonenumber

Requirements

This library requires PHP 8.1 or later.

For PHP 7.4 and PHP 8.0 support, use version 0.5. For PHP 7.1 support, use version 0.4. For PHP 5.6 and PHP 7.0 support, use version 0.1. Note that these PHP versions are EOL and not supported anymore. If you're still using one of these PHP versions, you should consider upgrading as soon as possible.

Project status & release process

While this library is still under development, it is well tested and should be stable enough to use in production environments.

The current releases are numbered 0.x.y. When a non-breaking change is introduced (adding new methods, optimizing existing code, etc.), y is incremented.

When a breaking change is introduced, a new 0.x version cycle is always started.

It is therefore safe to lock your project to a given release cycle, such as 0.6.*.

If you need to upgrade to a newer release cycle, check the release history for a list of changes introduced by each further 0.x.0 version.

Quick start

All the classes lie in the Brick\PhoneNumber namespace.

To obtain an instance of PhoneNumber, use the parse() method:

  • Using an international number: PhoneNumber::parse('+33123456789');
  • Using a national number and a country code: PhoneNumber::parse('01 23 45 67 89', 'FR');

Validating a number

The parse() method is quite permissive with numbers; it basically attempts to match a country code, and validates the length of the phone number for this country.

If a number is really malformed, it throws a PhoneNumberParseException:

use Brick\PhoneNumber\PhoneNumber;
use Brick\PhoneNumber\PhoneNumberParseException;

try {
    $number = PhoneNumber::parse('+333');
}
catch (PhoneNumberParseException $e) {
    // 'The string supplied is too short to be a phone number.'
}

In most cases, it is recommended to perform an extra step of validation with isValidNumber() or isPossibleNumber():

if (! $number->isPossibleNumber()) {
    // a more lenient and faster check than `isValidNumber()`
}

if (! $number->isValidNumber()) {
    // strict check relying on up-to-date metadata library
}

As a rule of thumb, do the following:

  • When the number comes from user input, do a full validation: parse() and catch PhoneNumberParseException, then call isValidNumber() (or isPossibleNumber() for a more lenient check) if no exception occurred;
  • When the number is later retrieved from your database, and has been validated before, you can just perform a blind parse().

Formatting a number

Basic formatting

You can use format() with a PhoneNumberFormat enum value:

$number = PhoneNumber::parse('+41446681800');
$number->format(PhoneNumberFormat::E164); // +41446681800
$number->format(PhoneNumberFormat::INTERNATIONAL); // +41 44 668 18 00
$number->format(PhoneNumberFormat::NATIONAL); // 044 668 18 00
$number->format(PhoneNumberFormat::RFC3966); // tel:+41-44-668-18-00

Formatting to call from another country

You may want to present a phone number to an audience in a specific country, with the correct international prefix when required. This is what formatForCallingFrom() does:

$number = PhoneNumber::parse('+447123456789');
$number->formatForCallingFrom('GB'); // 07123 456789
$number->formatForCallingFrom('FR'); // 00 44 7123 456789
$number->formatForCallingFrom('US'); // 011 44 7123 456789

Number types

In certain cases, it is possible to know the type of a phone number (fixed line, mobile phone, etc.), using the getNumberType() method, which returns a PhoneNumberType enum value:

PhoneNumber::parse('+336123456789')->getNumberType(); // PhoneNumberType::MOBILE
PhoneNumber::parse('+33123456789')->getNumberType(); // PhoneNumberType::FIXED_LINE

If the type is unknown, the PhoneNumberType::UNKNOWN value is returned. Check the PhoneNumberType enum for all possible values.

Number information

You can extract the following information from a phone number:

$number = PhoneNumber::parse('+447123456789');
echo $number->getRegionCode(); // GB
echo $number->getCountryCode(); // 44
echo $number->getNationalNumber(); // 7123456789

Example numbers

You can get an example number for a country code and an optional number type (defaults to fixed line). This can be useful to use as a placeholder in an input field, for example:

echo PhoneNumber::getExampleNumber('FR'); // +33123456789
echo PhoneNumber::getExampleNumber('FR', PhoneNumberType::MOBILE); // +33612345678

The return type of getExampleNumber() is a PhoneNumber instance, so you can format it as you like:

echo PhoneNumber::getExampleNumber('FR')->formatForCallingFrom('FR'); // 01 23 45 67 89

If no example phone number is available for the country code / number type combination, a PhoneNumberException is thrown.

Casting to string

Casting a PhoneNumber to string returns its E164 representation (+ followed by digits), so the following are equivalent:

(string) $phoneNumber
$phoneNumber->format(PhoneNumberFormat::E164)

You can serialize a PhoneNumber to string, then recover it using parse() without a country code:

$phoneNumber = PhoneNumber::parse('02079834000', 'GB');
$phoneNumberAsString = (string) $phoneNumber; // +442079834000
$phoneNumber2 = PhoneNumber::parse($phoneNumberAsString);

$phoneNumber2->isEqualTo($phoneNumber); // true

Doctrine mappings

You can use PhoneNumber objects in your Doctrine entities using the brick/phonenumber-doctrine package.

phonenumber's People

Contributors

andrew-demb avatar benmorel avatar johanadivare avatar svenluijten avatar xificurk avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

phonenumber's Issues

Netherlands Antilles Country Code: Missing or invalid default region

Hello!

When trying to parse phone numbers of the format 599 XXXX XXXX with country code AN, parse() raises a PhoneNumberParseException with the message Missing or invalid default region..

e.g.

try {
   $number = PhoneNumber::parse('59912345678', 'AN');
   echo $number->format(PhoneNumberFormat::E164);
} catch (PhoneNumberParseException $e) {
   echo $e->getMessage();
}

Netherlands Antilles was dissolved in 2010 - is this why phone numbers from this country are not supported by parse()?

The Netherlands Antilles Alpha-2 code was 'AN', and the Alpha-2 codes of most other countries seem to work with parse().

The country calling code of Netherlands Antilles was 599, and it is now in use in Curaçao and the Caribbean Netherlands.

My company has a lot of legacy customers whose phone numbers begin with 599 and whose country codes are AN. It would really help us out if AN was supported by parse().

Thanks for your time and maintaining this package 😄

Any plans to add geolocation?

Hi

I would like to use brick phoneumber, but it's missing geolocation features.
Are there any plans to add this in future releases?

Thanks

Can't catch exception

Hi,

I'm having trouble catching the exceptions using the following code.

try {
      $numberParsed = PhoneNumber::parse('+333', $region);
      $numberValid = PhoneNumber::parse('+333', $region)->isValidNumber();
		    
}catch (PhoneNumberParseException $e) {
      // 'The string supplied is too short to be a phone number.'
      error_log($e);
}

Throws the error

PHP Fatal error:  Uncaught libphonenumber\NumberParseException: The string supplied is too short to be a phone number. in /www/zendsvr6/htdocs/ridgwad/stream_dev_1/core/utils/composer/vendor/giggsey/libphonenumber-for-php/src/PhoneNumberUtil.php:1650
Stack trace:
#0 /www/zendsvr6/htdocs/ridgwad/stream_dev_1/core/utils/composer/vendor/giggsey/libphonenumber-for-php/src/PhoneNumberUtil.php(3023): libphonenumber\PhoneNumberUtil->parseHelper('+333', 'GB', false, true, Object(libphonenumber\PhoneNumber))

Any ideas what I'm doing wrong?

Getting error for Brazil Number

Array
(
[error] => No valid contact for +5575*******

)

I got this error when I tried searching this number. On some online searched I found that it's from Brazil but it's giving error here.

PhoneNumber::getGeographicalAreaCode().

many thanks, that helps
what i was after if you
$phoneNumber = PhoneNumber::parse('02079460585');
echo $phoneNumber->getGeographicalAreaCode(); // 20
echo $phoneNumber->getGeographicalAreaCodeLocation(); // London

$phoneNumber = PhoneNumber::parse('01993123452');
echo $phoneNumber->getGeographicalAreaCode(); // 01993
echo $phoneNumber->getGeographicalAreaCodeLocation(); // Witney

$phoneNumber = PhoneNumber::parse('0901254265');
echo $phoneNumber->getGeographicalAreaCode(); // 09
echo $phoneNumber->getGeographicalAreaCodeLocation(); // NGN
echo $phoneNumber->getNumberType(); // premium rate

basically trying to phase everything from
https://www.ofcom.org.uk/phones-telecoms-and-internet/advice-for-consumers/advice/telephone-area-codes-tool

many thanks

Syntax error in src/PhoneNumber.php

Hello,

Just wanted to warn you there is a syntax error on line 106 in the file.
A "?" symbol is making all crash.

Btw thanks for the plugin !
Cheers,
Thomas

[Bugfix] - Zero prefix

Hi guys
There is a particularly problematic bug in the parse functionality.
The function remove the zero numbers from the prefix.
Eg: 00391234567 --> 391234567
This is not a good behavior because in some countries the zero numbers in prefix are integral part of the phone number.
There is a way to fix this?

Thanks

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.