You are here

public function CpfService::generate in CPF 8

Generates a valid CPF number.

File

src/CpfService.php, line 58

Class

CpfService
Defines the CpfService service, for CPF module.

Namespace

Drupal\cpf

Code

public function generate() {
  $cpf = '';
  $n = [
    rand(0, 9),
    rand(0, 9),
    rand(0, 9),
    rand(0, 9),
    rand(0, 9),
    rand(0, 9),
    rand(0, 9),
    rand(0, 9),
    rand(0, 9),
  ];
  $n[9] = $n[8] * 2 + $n[7] * 3 + $n[6] * 4 + $n[5] * 5 + $n[4] * 6;
  $n[9] += $n[3] * 7 + $n[2] * 8 + $n[1] * 9 + $n[0] * 10;
  $n[9] = 11 - $n[9] % 11;
  $n[9] = $n[9] >= 10 ? 0 : $n[9];
  $n[10] = $n[9] * 2 + $n[8] * 3 + $n[7] * 4 + $n[6] * 5 + $n[5] * 6;
  $n[10] += $n[4] * 7 + $n[3] * 8 + $n[2] * 9 + $n[1] * 10 + $n[0] * 11;
  $n[10] = 11 - $n[10] % 11;
  $n[10] = $n[10] >= 10 ? 0 : $n[10];
  $cpf = implode('', $n);
  return $cpf;
}