Cnh.php 1.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859
  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 mb_strlen;
  10. use function preg_replace;
  11. /**
  12. * Validates a Brazilian driver's license.
  13. *
  14. * @author Gabriel Pedro <gpedro@users.noreply.github.com>
  15. * @author Henrique Moody <henriquemoody@gmail.com>
  16. * @author Kinn Coelho Julião <kinncj@gmail.com>
  17. * @author William Espindola <oi@williamespindola.com.br>
  18. */
  19. final class Cnh extends AbstractRule
  20. {
  21. /**
  22. * {@inheritDoc}
  23. */
  24. public function validate($input): bool
  25. {
  26. if (!is_scalar($input)) {
  27. return false;
  28. }
  29. // Canonicalize input
  30. $input = (string) preg_replace('{\D}', '', (string) $input);
  31. // Validate length and invalid numbers
  32. if (mb_strlen($input) != 11 || ((int) $input === 0)) {
  33. return false;
  34. }
  35. // Validate check digits using a modulus 11 algorithm
  36. for ($c = $s1 = $s2 = 0, $p = 9; $c < 9; $c++, $p--) {
  37. $s1 += (int) $input[$c] * $p;
  38. $s2 += (int) $input[$c] * (10 - $p);
  39. }
  40. $dv1 = $s1 % 11;
  41. if ($input[9] != ($dv1 > 9) ? 0 : $dv1) {
  42. return false;
  43. }
  44. $dv2 = $s2 % 11 - ($dv1 > 9 ? 2 : 0);
  45. $check = $dv2 < 0 ? $dv2 + 11 : ($dv2 > 9 ? 0 : $dv2);
  46. return $input[10] == $check;
  47. }
  48. }