NfeAccessKey.php 1.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556
  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 floor;
  10. use function mb_strlen;
  11. use function str_split;
  12. /**
  13. * Validates the access key of the Brazilian electronic invoice (NFe).
  14. *
  15. *
  16. * (pt-br) Valida chave de acesso de NFe, mais especificamente, relacionada ao DANFE.
  17. *
  18. * @see (pt-br) Manual de Integração do Contribuinte v4.0.1 em http://www.nfe.fazenda.gov.br
  19. *
  20. * @author Andrey Knupp Vital <andreykvital@gmail.com>
  21. * @author Danilo Correa <danilosilva87@gmail.com>
  22. * @author Henrique Moody <henriquemoody@gmail.com>
  23. */
  24. final class NfeAccessKey extends AbstractRule
  25. {
  26. /**
  27. * {@inheritDoc}
  28. */
  29. public function validate($input): bool
  30. {
  31. if (mb_strlen($input) !== 44) {
  32. return false;
  33. }
  34. $digits = array_map('intval', str_split($input));
  35. $w = [];
  36. for ($i = 0, $z = 5, $m = 43; $i <= $m; ++$i) {
  37. $z = $i < $m ? $z - 1 == 1 ? 9 : $z - 1 : 0;
  38. $w[] = $z;
  39. }
  40. for ($i = 0, $s = 0, $k = 44; $i < $k; ++$i) {
  41. $s += $digits[$i] * $w[$i];
  42. }
  43. $s -= 11 * floor($s / 11);
  44. $v = $s == 0 || $s == 1 ? 0 : 11 - $s;
  45. return $v == $digits[43];
  46. }
  47. }