Regex.php 921 B

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748
  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 function is_scalar;
  9. use function preg_match;
  10. /**
  11. * Validates whether the input matches a defined regular expression.
  12. *
  13. * @author Alexandre Gomes Gaigalas <alganet@gmail.com>
  14. * @author Danilo Correa <danilosilva87@gmail.com>
  15. * @author Henrique Moody <henriquemoody@gmail.com>
  16. */
  17. final class Regex extends AbstractRule
  18. {
  19. /**
  20. * @var string
  21. */
  22. private $regex;
  23. /**
  24. * Initializes the rule.
  25. */
  26. public function __construct(string $regex)
  27. {
  28. $this->regex = $regex;
  29. }
  30. /**
  31. * {@inheritDoc}
  32. */
  33. public function validate($input): bool
  34. {
  35. if (!is_scalar($input)) {
  36. return false;
  37. }
  38. return preg_match($this->regex, (string) $input) > 0;
  39. }
  40. }