Skip to content

Commit

Permalink
Merge pull request #54 from MrEko/arrumando-cnh
Browse files Browse the repository at this point in the history
Arrumando cnh
  • Loading branch information
geekcom authored Jan 13, 2020
2 parents 5464a7e + c8c5a10 commit 5e986bb
Show file tree
Hide file tree
Showing 2 changed files with 30 additions and 10 deletions.
33 changes: 23 additions & 10 deletions src/validator-docs/Rules/Cnh.php
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,8 @@
final class Cnh extends Sanitization
{
/**
* Trecho retirado do respect validation
* @author Evandro Kondrat
* Trecho reescrito com base no algoritmo passado pelo Detran-PR
*/
public function validateCnh($attribute, $value): bool
{
Expand All @@ -24,20 +25,32 @@ public function validateCnh($attribute, $value): bool
return false;
}

for ($c = $s1 = $s2 = 0, $p = 9; $c < 9; $c++, $p--) {
$s1 += (int) $value[$c] * $p;
$s2 += (int) $value[$c] * (10 - $p);
$parcial = substr($value, 0, 9);

for ($i = 0 , $j = 2, $s = 0; $i < mb_strlen($parcial); $i++, $j++) {
$s += (int) $parcial[$i] * $j;
}

$dv1 = $s1 % 11;
if ($value[9] != ($dv1 > 9) ? 0 : $dv1) {
return false;
$resto = $s % 11;
if ($resto <= 1) {
$dv1 = 0;
} else {
$dv1 = 11 - $resto;
}

$dv2 = $s2 % 11 - ($dv1 > 9 ? 2 : 0);
$parcial = $dv1.$parcial;

$check = $dv2 < 0 ? $dv2 + 11 : ($dv2 > 9 ? 0 : $dv2);
for ($i = 0, $j = 2, $s = 0; $i < mb_strlen($parcial); $i++, $j++) {
$s += (int) $parcial[$i] * $j;
}

$resto = $s % 11;
if ($resto <= 1) {
$dv2 = 0;
} else {
$dv2 = 11 - $resto;
}

return $value[10] == $check;
return $dv1.$dv2 == substr($value, -2);
}
}
7 changes: 7 additions & 0 deletions tests/TestValidator.php
Original file line number Diff line number Diff line change
Expand Up @@ -130,6 +130,13 @@ public function cnh()
$this->assertTrue($correct->passes());

$this->assertTrue($incorrect->fails());

$correct = \Validator::make(
['certo' => '04463004100'],
['certo' => 'cnh']
);

$this->assertTrue($correct->passes());
}

/** @test **/
Expand Down

0 comments on commit 5e986bb

Please sign in to comment.