Phone.php 1.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273
  1. <?php
  2. /*
  3. * Copyright (c) Alexandre Gomes Gaigalas <alganet@gmail.com>
  4. * SPDX-License-Identifier: MIT
  5. */
  6. declare(strict_types=1);
  7. namespace Respect\Validation\Rules;
  8. use libphonenumber\NumberParseException;
  9. use libphonenumber\PhoneNumberUtil;
  10. use Respect\Validation\Exceptions\ComponentException;
  11. use function class_exists;
  12. use function is_null;
  13. use function is_scalar;
  14. use function sprintf;
  15. /**
  16. * Validates whether the input is a valid phone number.
  17. *
  18. * Validates an international or country-specific telephone number
  19. *
  20. * @author Alexandre Gomes Gaigalas <alganet@gmail.com>
  21. */
  22. final class Phone extends AbstractRule
  23. {
  24. /**
  25. * @var ?string
  26. */
  27. private $countryCode;
  28. /**
  29. * {@inheritDoc}
  30. */
  31. public function __construct(?string $countryCode = null)
  32. {
  33. $this->countryCode = $countryCode;
  34. if (!is_null($countryCode) && !(new CountryCode())->validate($countryCode)) {
  35. throw new ComponentException(
  36. sprintf(
  37. 'Invalid country code %s',
  38. $countryCode
  39. )
  40. );
  41. }
  42. if (!class_exists(PhoneNumberUtil::class)) {
  43. throw new ComponentException('The phone validator requires giggsey/libphonenumber-for-php');
  44. }
  45. }
  46. /**
  47. * {@inheritDoc}
  48. */
  49. public function validate($input): bool
  50. {
  51. if (!is_scalar($input)) {
  52. return false;
  53. }
  54. try {
  55. return PhoneNumberUtil::getInstance()->isValidNumber(
  56. PhoneNumberUtil::getInstance()->parse((string) $input, $this->countryCode)
  57. );
  58. } catch (NumberParseException $e) {
  59. return false;
  60. }
  61. }
  62. }