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

74 lines
1.7 KiB
PHP
Raw Normal View History

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