Base64.php 812 B

12345678910111213141516171819202122232425262728293031323334353637383940
  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_string;
  9. use function mb_strlen;
  10. use function preg_match;
  11. /**
  12. * Validate if a string is Base64-encoded.
  13. *
  14. * @author Henrique Moody <henriquemoody@gmail.com>
  15. * @author Jens Segers <segers.jens@gmail.com>
  16. * @author William Espindola <oi@williamespindola.com.br>
  17. */
  18. final class Base64 extends AbstractRule
  19. {
  20. /**
  21. * {@inheritDoc}
  22. */
  23. public function validate($input): bool
  24. {
  25. if (!is_string($input)) {
  26. return false;
  27. }
  28. if (!preg_match('#^[A-Za-z0-9+/\n\r]+={0,2}$#', $input)) {
  29. return false;
  30. }
  31. return mb_strlen($input) % 4 === 0;
  32. }
  33. }