Pesel.php 1.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051
  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 preg_match;
  10. /**
  11. * Validates PESEL (Polish human identification number).
  12. *
  13. * @author Danilo Correa <danilosilva87@gmail.com>
  14. * @author Henrique Moody <henriquemoody@gmail.com>
  15. * @author Tomasz Regdos <tomek@regdos.com>
  16. */
  17. final class Pesel extends AbstractRule
  18. {
  19. /**
  20. * {@inheritDoc}
  21. */
  22. public function validate($input): bool
  23. {
  24. if (!is_scalar($input)) {
  25. return false;
  26. }
  27. $stringInput = (string) $input;
  28. if (!preg_match('/^\d{11}$/', (string) $stringInput)) {
  29. return false;
  30. }
  31. $weights = [1, 3, 7, 9, 1, 3, 7, 9, 1, 3];
  32. $targetControlNumber = $stringInput[10];
  33. $calculateControlNumber = 0;
  34. for ($i = 0; $i < 10; ++$i) {
  35. $calculateControlNumber += (int) $stringInput[$i] * $weights[$i];
  36. }
  37. $calculateControlNumber = (10 - $calculateControlNumber % 10) % 10;
  38. return $targetControlNumber == $calculateControlNumber;
  39. }
  40. }