Base.php 1.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364
  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 Respect\Validation\Exceptions\ComponentException;
  9. use function is_null;
  10. use function mb_strlen;
  11. use function mb_substr;
  12. use function preg_match;
  13. use function sprintf;
  14. /**
  15. * Validate numbers in any base, even with non regular bases.
  16. *
  17. * @author Carlos André Ferrari <caferrari@gmail.com>
  18. * @author Henrique Moody <henriquemoody@gmail.com>
  19. * @author William Espindola <oi@williamespindola.com.br>
  20. */
  21. final class Base extends AbstractRule
  22. {
  23. /**
  24. * @var string
  25. */
  26. private $chars = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
  27. /**
  28. * @var int
  29. */
  30. private $base;
  31. /**
  32. * Initializes the Base rule.
  33. */
  34. public function __construct(int $base, ?string $chars = null)
  35. {
  36. if (!is_null($chars)) {
  37. $this->chars = $chars;
  38. }
  39. $max = mb_strlen($this->chars);
  40. if ($base > $max) {
  41. throw new ComponentException(sprintf('a base between 1 and %s is required', $max));
  42. }
  43. $this->base = $base;
  44. }
  45. /**
  46. * {@inheritDoc}
  47. */
  48. public function validate($input): bool
  49. {
  50. $valid = mb_substr($this->chars, 0, $this->base);
  51. return (bool) preg_match('@^[' . $valid . ']+$@', (string) $input);
  52. }
  53. }