HighSpeaker/vendor/workerman/validation/library/Rules/Phone.php

74 lines
1.7 KiB
PHP
Raw Normal View History

2022-12-24 19:40:40 +05:30
<?php
/*
2024-01-31 19:45:08 +05:30
* Copyright (c) Alexandre Gomes Gaigalas <alganet@gmail.com>
* SPDX-License-Identifier: MIT
2022-12-24 19:40:40 +05:30
*/
declare(strict_types=1);
namespace Respect\Validation\Rules;
2024-01-31 19:45:08 +05:30
use libphonenumber\NumberParseException;
use libphonenumber\PhoneNumberUtil;
use Respect\Validation\Exceptions\ComponentException;
use function class_exists;
use function is_null;
2022-12-24 19:40:40 +05:30
use function is_scalar;
use function sprintf;
/**
* Validates whether the input is a valid phone number.
*
2024-01-31 19:45:08 +05:30
* Validates an international or country-specific telephone number
2022-12-24 19:40:40 +05:30
*
2024-01-31 19:45:08 +05:30
* @author Alexandre Gomes Gaigalas <alganet@gmail.com>
2022-12-24 19:40:40 +05:30
*/
final class Phone extends AbstractRule
{
2024-01-31 19:45:08 +05:30
/**
* @var ?string
*/
private $countryCode;
2022-12-24 19:40:40 +05:30
/**
* {@inheritDoc}
*/
2024-01-31 19:45:08 +05:30
public function __construct(?string $countryCode = null)
2022-12-24 19:40:40 +05:30
{
2024-01-31 19:45:08 +05:30
$this->countryCode = $countryCode;
if (!is_null($countryCode) && !(new CountryCode())->validate($countryCode)) {
throw new ComponentException(
sprintf(
'Invalid country code %s',
$countryCode
)
);
2022-12-24 19:40:40 +05:30
}
2024-01-31 19:45:08 +05:30
if (!class_exists(PhoneNumberUtil::class)) {
throw new ComponentException('The phone validator requires giggsey/libphonenumber-for-php');
}
2022-12-24 19:40:40 +05:30
}
2024-01-31 19:45:08 +05:30
/**
* {@inheritDoc}
*/
public function validate($input): bool
2022-12-24 19:40:40 +05:30
{
2024-01-31 19:45:08 +05:30
if (!is_scalar($input)) {
return false;
}
try {
return PhoneNumberUtil::getInstance()->isValidNumber(
PhoneNumberUtil::getInstance()->parse((string) $input, $this->countryCode)
);
} catch (NumberParseException $e) {
return false;
}
2022-12-24 19:40:40 +05:30
}
}