2014-07-12 21:20:43 +02:00
|
|
|
<?php
|
2015-06-08 16:47:14 +02:00
|
|
|
|
2015-06-08 17:09:25 +02:00
|
|
|
/*
|
2023-02-17 05:13:51 +01:00
|
|
|
* Copyright (c) Alexandre Gomes Gaigalas <alganet@gmail.com>
|
|
|
|
* SPDX-License-Identifier: MIT
|
2015-06-08 17:09:25 +02:00
|
|
|
*/
|
|
|
|
|
2017-11-19 19:01:31 +01:00
|
|
|
declare(strict_types=1);
|
|
|
|
|
2014-07-12 21:20:43 +02:00
|
|
|
namespace Respect\Validation\Rules;
|
|
|
|
|
2023-02-18 22:09:26 +01:00
|
|
|
use libphonenumber\NumberParseException;
|
|
|
|
use libphonenumber\PhoneNumberUtil;
|
|
|
|
use Respect\Validation\Exceptions\ComponentException;
|
|
|
|
|
|
|
|
use function class_exists;
|
|
|
|
use function is_null;
|
2018-09-16 16:01:49 +02:00
|
|
|
use function is_scalar;
|
|
|
|
use function sprintf;
|
|
|
|
|
2018-11-25 17:56:04 +01:00
|
|
|
/**
|
2019-02-10 19:09:01 +01:00
|
|
|
* Validates whether the input is a valid phone number.
|
|
|
|
*
|
2023-02-18 22:09:26 +01:00
|
|
|
* Validates an international or country-specific telephone number
|
2019-02-10 19:09:01 +01:00
|
|
|
*
|
2023-02-18 22:09:26 +01:00
|
|
|
* @author Alexandre Gomes Gaigalas <alganet@gmail.com>
|
2018-11-25 17:56:04 +01:00
|
|
|
*/
|
2019-02-10 19:09:01 +01:00
|
|
|
final class Phone extends AbstractRule
|
2014-07-12 21:20:43 +02:00
|
|
|
{
|
2023-02-18 22:09:26 +01:00
|
|
|
/**
|
|
|
|
* @var ?string
|
|
|
|
*/
|
|
|
|
private $countryCode;
|
|
|
|
|
2019-02-07 21:22:10 +01:00
|
|
|
/**
|
2019-04-05 14:33:00 +02:00
|
|
|
* {@inheritDoc}
|
2019-02-07 21:22:10 +01:00
|
|
|
*/
|
2023-02-18 22:09:26 +01:00
|
|
|
public function __construct(?string $countryCode = null)
|
2017-10-17 08:52:25 +02:00
|
|
|
{
|
2023-02-18 22:09:26 +01:00
|
|
|
$this->countryCode = $countryCode;
|
|
|
|
|
|
|
|
if (!is_null($countryCode) && !(new CountryCode())->validate($countryCode)) {
|
|
|
|
throw new ComponentException(
|
|
|
|
sprintf(
|
|
|
|
'Invalid country code %s',
|
|
|
|
$countryCode
|
|
|
|
)
|
|
|
|
);
|
2017-10-17 08:52:25 +02:00
|
|
|
}
|
|
|
|
|
2023-02-18 22:09:26 +01:00
|
|
|
if (!class_exists(PhoneNumberUtil::class)) {
|
|
|
|
throw new ComponentException('The phone validator requires giggsey/libphonenumber-for-php');
|
|
|
|
}
|
2014-07-12 21:20:43 +02:00
|
|
|
}
|
2019-05-11 19:59:12 +02:00
|
|
|
|
2023-02-18 22:09:26 +01:00
|
|
|
/**
|
|
|
|
* {@inheritDoc}
|
|
|
|
*/
|
|
|
|
public function validate($input): bool
|
2019-05-11 19:59:12 +02:00
|
|
|
{
|
2023-02-18 22:09:26 +01:00
|
|
|
if (!is_scalar($input)) {
|
|
|
|
return false;
|
|
|
|
}
|
|
|
|
|
|
|
|
try {
|
|
|
|
return PhoneNumberUtil::getInstance()->isValidNumber(
|
|
|
|
PhoneNumberUtil::getInstance()->parse((string) $input, $this->countryCode)
|
|
|
|
);
|
|
|
|
} catch (NumberParseException $e) {
|
|
|
|
return false;
|
|
|
|
}
|
2019-05-11 19:59:12 +02:00
|
|
|
}
|
2015-01-08 03:15:35 +01:00
|
|
|
}
|