Pis.php 1.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253
  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_match;
  11. use function preg_replace;
  12. /**
  13. * Validates a Brazilian PIS/NIS number.
  14. *
  15. * @author Bruno Koga <brunokoga187@gmail.com>
  16. * @author Danilo Correa <danilosilva87@gmail.com>
  17. * @author Henrique Moody <henriquemoody@gmail.com>
  18. */
  19. final class Pis extends AbstractRule
  20. {
  21. /**
  22. * {@inheritDoc}
  23. */
  24. public function validate($input): bool
  25. {
  26. if (!is_scalar($input)) {
  27. return false;
  28. }
  29. $digits = (string) preg_replace('/\D/', '', (string) $input);
  30. if (mb_strlen($digits) != 11 || preg_match('/^' . $digits[0] . '{11}$/', $digits)) {
  31. return false;
  32. }
  33. $multipliers = [3, 2, 9, 8, 7, 6, 5, 4, 3, 2];
  34. $summation = 0;
  35. for ($position = 0; $position < 10; ++$position) {
  36. $summation += (int) $digits[$position] * $multipliers[$position];
  37. }
  38. $checkDigit = (int) $digits[10];
  39. $modulo = $summation % 11;
  40. return $checkDigit === ($modulo < 2 ? 0 : 11 - $modulo);
  41. }
  42. }