Nip.php 1.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354
  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 array_map;
  9. use function is_scalar;
  10. use function preg_match;
  11. use function str_split;
  12. /**
  13. * Validates whether the input is a Polish VAT identification number (NIP).
  14. *
  15. * @see https://en.wikipedia.org/wiki/VAT_identification_number
  16. *
  17. * @author Henrique Moody <henriquemoody@gmail.com>
  18. * @author Tomasz Regdos <tomek@regdos.com>
  19. */
  20. final class Nip extends AbstractRule
  21. {
  22. /**
  23. * {@inheritDoc}
  24. */
  25. public function validate($input): bool
  26. {
  27. if (!is_scalar($input)) {
  28. return false;
  29. }
  30. if (!preg_match('/^\d{10}$/', (string) $input)) {
  31. return false;
  32. }
  33. $weights = [6, 5, 7, 2, 3, 4, 5, 6, 7];
  34. $digits = array_map('intval', str_split((string) $input));
  35. $targetControlNumber = $digits[9];
  36. $calculateControlNumber = 0;
  37. for ($i = 0; $i < 9; ++$i) {
  38. $calculateControlNumber += $digits[$i] * $weights[$i];
  39. }
  40. $calculateControlNumber = $calculateControlNumber % 11;
  41. return $targetControlNumber == $calculateControlNumber;
  42. }
  43. }