Skip to content

Commit

Permalink
Merge pull request #10 from asterion/main
Browse files Browse the repository at this point in the history
fix: generate correct RUT
  • Loading branch information
astersnake authored Jun 30, 2024
2 parents 7fe2d58 + e717288 commit f492cab
Show file tree
Hide file tree
Showing 2 changed files with 57 additions and 7 deletions.
38 changes: 31 additions & 7 deletions src/Provider/es_CL/Person.php
Original file line number Diff line number Diff line change
Expand Up @@ -46,14 +46,38 @@ public function rut(int $length = 8): string
for($i = 0; $i < $length; $i++) {
$rut .= mt_rand(0, 9);
}

$dv = 11 - ($rut % 11);
if ($dv == 10) {
$dv = 'K';
} elseif ($dv == 11) {
$dv = 0;
}

$dv = self::getVd((int)$rut);

return "{$rut}-{$dv}";
}

/**
* Returns the Verification Digit from a RUT number.
* https://github.com/Laragear/Rut/blob/a4f6812a889c67115a6c7f2d7e0782ec4807061f/src/Rut.php#L446
*
* @param int $num
* @return string
*/
public static function getVd(int $num): string
{
$i = 2;
$sum = 0;

foreach (array_reverse(str_split((string) $num)) as $v) {
if ($i === 8) {
$i = 2;
}
$sum += (int) $v * $i;
$i++;
}

$digit = 11 - ($sum % 11);

return (string) match ($digit) {
11 => 0,
10 => 'K',
default => $digit,
};
}
}
26 changes: 26 additions & 0 deletions tests/ExampleTest.php
Original file line number Diff line number Diff line change
@@ -1,5 +1,31 @@
<?php

$faker = \Faker\Factory::create('es_CL');

it('can test', function () {
expect(true)->toBeTrue();
});

it('can generate', function () use ($faker) {
$rut = $faker->rut();

expect(preg_match('/[\dkK-]/', $faker->rut()))->toBe(1);
});

it('can return vd number', function () {

$dv = \Faker\Provider\es_CL\Person::getVd(99737415);

expect($dv)->toBe('0');

$dv = \Faker\Provider\es_CL\Person::getVd(22339845);

expect($dv)->toBe('6');
});

it('can return vd k', function () {

$dv = \Faker\Provider\es_CL\Person::getVd(77789188);

expect($dv)->toBe('K');
});

0 comments on commit f492cab

Please sign in to comment.