respect-validation/library/Rules/NfeAccessKey.php
Henrique Moody f52097075b
Increase PHPStan level to 2
Signed-off-by: Henrique Moody <henriquemoody@gmail.com>
2019-02-04 00:29:13 +01:00

59 lines
1.4 KiB
PHP

<?php
/*
* This file is part of Respect/Validation.
*
* (c) Alexandre Gomes Gaigalas <alexandre@gaigalas.net>
*
* For the full copyright and license information, please view the "LICENSE.md"
* file that was distributed with this source code.
*/
declare(strict_types=1);
namespace Respect\Validation\Rules;
use function array_map;
use function str_split;
/**
* Rule restrict to Brasil.
*
* Valida chave de acesso de NFe.
* Mais especificamente, relacionada ao DANFE.
*
* @author Andrey Knupp Vital <andreykvital@gmail.com>
* @author Henrique Moody <henriquemoody@gmail.com>
*/
class NfeAccessKey extends AbstractRule
{
/**
* @see Manual de Integração do Contribuinte v4.0.1 (http://www.nfe.fazenda.gov.br)
*
* @param string $input access key
*
* @return bool
*/
public function validate($input): bool
{
if (44 !== mb_strlen($input)) {
return false;
}
$digits = array_map('intval', str_split($input));
$w = [];
for ($i = 0, $z = 5, $m = 43; $i <= $m; ++$i) {
$z = ($i < $m) ? 1 == ($z - 1) ? 9 : ($z - 1) : 0;
$w[] = $z;
}
for ($i = 0, $s = 0, $k = 44; $i < $k; ++$i) {
$s += $digits[$i] * $w[$i];
}
$s -= (11 * floor($s / 11));
$v = (0 == $s || 1 == $s) ? 0 : (11 - $s);
return $v == $digits[43];
}
}