PolishIdCard.php 1.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263
  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 ord;
  10. use function preg_match;
  11. /**
  12. * Validates whether the input is a Polish identity card (Dowód Osobisty).
  13. *
  14. * @see https://en.wikipedia.org/wiki/Polish_identity_card
  15. *
  16. * @author Henrique Moody <henriquemoody@gmail.com>
  17. */
  18. final class PolishIdCard extends AbstractRule
  19. {
  20. private const ASCII_CODE_0 = 48;
  21. private const ASCII_CODE_7 = 55;
  22. private const ASCII_CODE_9 = 57;
  23. private const ASCII_CODE_A = 65;
  24. /**
  25. * {@inheritDoc}
  26. */
  27. public function validate($input): bool
  28. {
  29. if (!is_scalar($input)) {
  30. return false;
  31. }
  32. $input = (string) $input;
  33. if (!preg_match('/^[A-Z0-9]{9}$/', $input)) {
  34. return false;
  35. }
  36. $weights = [7, 3, 1, 0, 7, 3, 1, 7, 3];
  37. $weightedSum = 0;
  38. for ($i = 0; $i < 9; ++$i) {
  39. $code = ord($input[$i]);
  40. if ($i < 3 && $code <= self::ASCII_CODE_9) {
  41. return false;
  42. }
  43. if ($i > 2 && $code >= self::ASCII_CODE_A) {
  44. return false;
  45. }
  46. $difference = $code <= self::ASCII_CODE_9 ? self::ASCII_CODE_0 : self::ASCII_CODE_7;
  47. $weightedSum += ($code - $difference) * $weights[$i];
  48. }
  49. return $weightedSum % 10 == $input[3];
  50. }
  51. }