Cpf.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 intval;
  9. use function mb_strlen;
  10. use function preg_match;
  11. use function preg_replace;
  12. /**
  13. * Validates whether the input is a CPF (Brazilian Natural Persons Register) number.
  14. *
  15. * @author Alexandre Gomes Gaigalas <alganet@gmail.com>
  16. * @author Henrique Moody <henriquemoody@gmail.com>
  17. * @author Jair Henrique <jair.henrique@gmail.com>
  18. * @author Jayson Reis <santosdosreis@gmail.com>
  19. * @author Jean Pimentel <jeanfap@gmail.com>
  20. * @author William Espindola <oi@williamespindola.com.br>
  21. */
  22. final class Cpf extends AbstractRule
  23. {
  24. /**
  25. * {@inheritDoc}
  26. */
  27. public function validate($input): bool
  28. {
  29. // Code ported from jsfromhell.com
  30. $c = preg_replace('/\D/', '', $input);
  31. if (mb_strlen($c) != 11 || preg_match('/^' . $c[0] . '{11}$/', $c) || $c === '01234567890') {
  32. return false;
  33. }
  34. $n = 0;
  35. for ($s = 10, $i = 0; $s >= 2; ++$i, --$s) {
  36. $n += intval($c[$i]) * $s;
  37. }
  38. if ($c[9] != (($n %= 11) < 2 ? 0 : 11 - $n)) {
  39. return false;
  40. }
  41. $n = 0;
  42. for ($s = 11, $i = 0; $s >= 2; ++$i, --$s) {
  43. $n += intval($c[$i]) * $s;
  44. }
  45. $check = ($n %= 11) < 2 ? 0 : 11 - $n;
  46. return $c[10] == $check;
  47. }
  48. }