settermjd/laminas-twilio-phone-number-validator

A laminas-validator class that validates phone numbers using Twilio's Verify API

1.3.2 2025-01-28 23:10 UTC

This package is auto-updated.

Last update: 2025-01-28 23:13:29 UTC


README

Build Status

This is a custom laminas-validator class that checks if a phone number is valid by using Twilio's Lookup API.

Overview

The package provides a custom laminas-validator class that checks if a phone number is valid by using Twilio's Lookup API, providing a simple way of validating phone numbers are valid, based on communications provider data, accessed through Twilio.

Requirements

To use the application, you'll need the following:

Getting Started

Add the Package as a Project Dependency

To use the package in your project, first, either add it in composer.json's require attribute, as in the example below.

"require": {
    "settermjd/laminas-twilio-phone-number-validator": "^1.0"
}

Or, use composer require to add it:

composer require settermjd/laminas-twilio-phone-number-validator

How to Use the Validator

You can use it directly, as in the following example, to validate a phone number.

use Settermjd\Validator\VerifyPhoneNumber;
use Twilio\Rest\Client;

$validator = new VerifyPhoneNumber(new Client(
    `<YOUR_TWILIO_ACCOUNT_SID>`,
    `<YOUR_TWILIO_AUTH_TOKEN>`,
));

if ($validator->isValid($email)) {
    // The phone number is valid, so do what you want knowing that.
} else {
    // The phone number is not valid, so show the reasons why.
    foreach ($validator->getMessages() as $messageId => $message) {
        printf("Validation failure '%s': %s\n", $messageId, $message);
    }
}

Or, you can use it in conjunction with laminas-inputfilter, as in the following example.

use Laminas\InputFilter\InputFilter;
use Laminas\InputFilter\Input;
use Laminas\Validator;
use Settermjd\Validator\VerifyPhoneNumber;
use Twilio\Rest\Client;

$phoneNumber = new Input('phone_number');
$phoneNumber->getValidatorChain()
          ->attach(
          new VerifyPhoneNumber(
              new Client(
                  `<TWILIO_ACCOUNT_SID>`,
                  `<TWILIO_AUTH_TOKEN>`,
              )
          )
    );

$inputFilter = new InputFilter();
$inputFilter->add($phoneNumber);

$inputFilter->setData($_POST);
if ($inputFilter->isValid()) {
    echo "The form is valid\n";
} else {
    echo "The form is not valid\n";
    foreach ($inputFilter->getInvalidInput() as $error) {
        print_r($error->getMessages());
    }
}

In both of the above examples, the VerifyPhoneNumber validator is initialised with a Twilio\Rest\Client object, which in turn is initialised with a Twilio Account SID and Auth Token. To retrieve these, open the Twilio Console in your browser of choice, then copy the Account SID and Auth Token from the Account Info, as you can see in the screenshot below.

The Account Info panel of the Twilio Console, showing a user's Account SID, Auth Token, and phone number, where the Account SID and phone number have been partially or completely redacted.

Caution

Use a package such as PHP Dotenv to keep credentials, such as the Twilio Account SID and Auth Token out of code, and avoid them accidentally being tracked by Git (or your version control tool of choice), or your deployment tool's secrets manager is strongly encouraged.

Supply query parameters

The previous example didn't supply any query parameters. They allow you to retrieve additional data during the lookup, such as when the SIM was last swapped, and whether call forwarding is enabled.

Caution

Be aware that some query parameters, such as in Fields require data packages which will incur charges on your account. Please double-check your code before running it so that you don't accidentally incur excessive unintended Lookup charges.

Filter and validate query parameters

To ensure that the query parameters provided to the validator are valid, you can use the QueryParametersInputFilter. This is a custom laminas-inputfilter class which ensures that the query parameter data provided is valid, and doesn't contain malicious information or values unsupported by the Lookup API.

use Laminas\InputFilter\InputFilter;
use Laminas\InputFilter\Input;
use Laminas\Validator;
use Settermjd\InputFilter\QueryParametersInputFilter;
use Settermjd\Validator\VerifyPhoneNumber;
use Twilio\Rest\Client;

$inputFilter = new QueryParametersInputFilter();
$inputFilter->setData($suppliedQueryParameters);
if ($inputFilter->isValid()) {
    $validator = new VerifyPhoneNumber(
        twilioClient: new Client(
            `<YOUR_TWILIO_ACCOUNT_SID>`,
            `<YOUR_TWILIO_AUTH_TOKEN>`,
        ),
        queryParameters: $inputFilter->getValues(),
    );

    if ($validator->isValid($email)) {
        // The phone number is valid, so do what you want knowing that.
    } else {
        // The phone number is not valid, so show the reasons why.
        foreach ($validator->getMessages() as $messageId => $message) {
            printf("Validation failure '%s': %s\n", $messageId, $message);
        }
    }
}

In the example above, the query parameters ($suppliedQueryParameters) are checked with QueryParametersInputFilter. If the data is valid, then the VerifyPhoneNumber validator is instantiated and used; that code is exactly the same as in the first example above.

Add Caching Support

The validator is PSR-16-compliant. So, if you want to further enhance performance, when initialising a VerifyPhoneNumber object, provide an object that implements CacheInterface as the third argument; the example below uses laminas-cache.

use Laminas\Cache\Psr\SimpleCache\SimpleCacheDecorator;
use Laminas\Cache\Service\StorageAdapterFactoryInterface;
use Psr\Container\ContainerInterface;
use Settermjd\Validator\VerifyPhoneNumber;
use Twilio\Rest\Client;

/** @var ContainerInterface $container */
$container = null; // can be any configured PSR-11 container

$storageFactory = $container->get(StorageAdapterFactoryInterface::class);
$storage = $storageFactory->create('apc');

$validator = new VerifyPhoneNumber(
    twilioClient: new Client(`<YOUR_TWILIO_ACCOUNT_SID>`, `<YOUR_TWILIO_AUTH_TOKEN>`), 
    cache: new SimpleCacheDecorator($storage),
);

If you're not sure which PSR-16 implementation to use, check out the full list of providers on Packagist.

Contributing

If you want to contribute to the project, whether you have found issues with it or just want to improve it, here's how:

  • Issues: ask questions and submit your feature requests, bug reports, etc
  • Pull requests: send your improvements

Did You Find the Project Useful?

If the project was useful, and you want to say thank you and/or support its active development, here's how:

  • Add a GitHub Star to the project
  • Write an interesting article about the project wherever you blog