JavaScript Python PHP
function executar(values) {
function gdText(value) { if (typeof value !== 'string' || value.length > 10000 || !value.isWellFormed())
throw new Error('Use texto Unicode válido de até 10 mil caracteres por campo.'); return value; }
function groupedDocuments(v) {
const kind = gdChoice(v, 'document', ['rg', 'cnh', 'titulo-eleitor', 'pis-pasep', 'renavam', 'certidao']), formatted = !['cnh', 'renavam'].includes(kind) && gdMask(v);
const electoralState = kind === 'titulo-eleitor' ? gdChoice(v, 'electoralState', ELECTORAL_STATES.map(([code]) => code)) : '01';
const certificateType = kind === 'certidao' ? gdChoice(v, 'certificateType', ['1', '2', '4']) : '1', year = kind === 'certidao' ? gdInt(v, 'year', 1900, new Date().getFullYear()) : 2024;
return gdOutput(gdBatch(v, () => generateDocument(kind, { formatted, electoralState, certificateType, year })));
}
const ELECTORAL_STATES = [
['01', 'SP'], ['02', 'MG'], ['03', 'RJ'], ['04', 'RS'], ['05', 'BA'],
['06', 'PR'], ['07', 'CE'], ['08', 'PE'], ['09', 'SC'], ['10', 'GO'],
['11', 'MA'], ['12', 'PB'], ['13', 'PA'], ['14', 'ES'], ['15', 'PI'],
['16', 'RN'], ['17', 'AL'], ['18', 'MT'], ['19', 'MS'], ['20', 'DF'],
['21', 'SE'], ['22', 'AM'], ['23', 'RO'], ['24', 'AC'], ['25', 'AP'],
['26', 'RR'], ['27', 'TO'], ['28', 'Exterior'],
];
function generateDocument(kind, options = {}) {
const state = options.state ?? 'SP';
let value;
for (;;) {
switch (kind) {
case 'cpf': {
const base = randomCharacters(9);
value = base + cpfChecksum(base);
break;
}
case 'cnpj': {
const alphabet = options.cnpjFormat === 'alphanumeric' ? '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ' : '0123456789';
let root = randomCharacters(8, alphabet);
if (options.cnpjFormat === 'alphanumeric' && !/[A-Z]/.test(root))
root = randomCharacters(1, 'ABCDEFGHIJKLMNOPQRSTUVWXYZ') + root.slice(1);
const base = root + '0001';
value = base + cnpjChecksum(base);
break;
}
case 'rg': {
const base = randomCharacters(8);
value = base + rgChecksum(base);
break;
}
case 'cnh': {
const base = randomCharacters(9);
const checksum = cnhChecksum(base);
if (checksum === null)
continue;
value = base + checksum;
break;
}
case 'titulo-eleitor': {
const base = randomCharacters(8) + (options.electoralState ?? '01');
value = base + electoralChecksum(base);
break;
}
case 'pis-pasep': {
const base = '1' + randomCharacters(9);
value = base + pisChecksum(base);
break;
}
case 'inscricao-estadual': {
// MG: código municipal 062 e ordem de estabelecimento 00.
const base = state === 'MG' ? '062' + randomCharacters(6) + '00' : state === 'RJ' ? randomCharacters(7) : randomCharacters(10);
value = completeStateRegistration(base, state);
break;
}
case 'renavam': {
const base = '00' + randomCharacters(8);
value = base + renavamChecksum(base);
break;
}
case 'certidao': {
const year = options.year ?? new Date().getFullYear();
if (!Number.isInteger(year) || year < 1900 || year > new Date().getFullYear())
throw new Error('Informe um ano entre 1900 e o ano atual.');
const type = options.certificateType ?? '1';
if (!['1', '2', '4'].includes(type))
throw new Error('Tipo de certidão inválido.');
// CNS aleatório: não há consulta à existência de uma serventia.
const base = String(randomInt(999999) + 1).padStart(6, '0') + '0155' + year + type
+ String(randomInt(99999) + 1).padStart(5, '0')
+ String(randomInt(300) + 1).padStart(3, '0')
+ String(randomInt(9999999) + 1).padStart(7, '0');
value = base + certificateChecksum(base);
break;
}
default: throw new Error('Documento não suportado.');
}
if (/^(.)\1+$/.test(value))
continue;
return options.formatted ? formatDocument(kind, value, state) : value;
}
}
function gdInt(v, key, min, max) { const raw = v[key], value = Number(raw); if (!/^-?\d+$/.test(raw ?? '') || !Number.isSafeInteger(value) || value < min || value > max)
throw new Error(`${key}: informe um inteiro entre ${min} e ${max}.`); return value; }
function gdChoice(v, key, choices) { if (!choices.includes(v[key]))
throw new Error(`Opção inválida: ${key}.`); return v[key]; }
function gdMask(v) { return gdChoice(v, 'formatted', ['true', 'false']) === 'true'; }
function gdBatch(v, make) {
const count = gdInt(v, 'count', 1, 100), values = new Set();
for (let attempts = 0; values.size < count && attempts < count * 100; attempts++)
values.add(make());
if (values.size !== count)
throw new Error('Não foi possível completar o lote sem repetições. Reduza a quantidade ou amplie o domínio.');
return [...values];
}
function gdOutput(values, json = false) { return { text: json ? JSON.stringify(values, null, 2) : values.join('\n'), file: json ? 'dados.json' : 'dados.txt' }; }
function cpfChecksum(base) {
assertBase(base, 9);
const first = mod11(base, [10, 9, 8, 7, 6, 5, 4, 3, 2]);
return `${first}${mod11(base + first, [11, 10, 9, 8, 7, 6, 5, 4, 3, 2])}`;
}
function cnpjChecksum(base) {
assertBase(base, 12, true);
const first = mod11(base, [5, 4, 3, 2, 9, 8, 7, 6, 5, 4, 3, 2], true);
return `${first}${mod11(base + first, [6, 5, 4, 3, 2, 9, 8, 7, 6, 5, 4, 3, 2], true)}`;
}
function rgChecksum(base) {
assertBase(base, 8);
const digit = (11 - weightedSum(base, [2, 3, 4, 5, 6, 7, 8, 9]) % 11) % 11;
return digit === 10 ? 'X' : String(digit);
}
function cnhChecksum(base) {
assertBase(base, 9);
const remainder = weightedSum(base, [9, 8, 7, 6, 5, 4, 3, 2, 1]) % 11;
const first = remainder === 10 ? 0 : remainder;
const secondRemainder = weightedSum(base, [1, 2, 3, 4, 5, 6, 7, 8, 9]) % 11;
const second = secondRemainder === 10 ? 0 : secondRemainder - (remainder === 10 ? 2 : 0);
// Evita bases que levam a um resultado negativo nas regras legadas de CNH.
return second < 0 ? null : `${first}${second}`;
}
function electoralChecksum(base) {
assertBase(base, 10);
const state = base.slice(8);
if (!ELECTORAL_STATES.some(([code]) => code === state))
throw new Error('Selecione uma UF eleitoral válida.');
const digit = (remainder) => remainder === 10 ? 0 : remainder === 0 && (state === '01' || state === '02') ? 1 : remainder;
const first = digit(weightedSum(base.slice(0, 8), [2, 3, 4, 5, 6, 7, 8, 9]) % 11);
return `${first}${digit(weightedSum(state + first, [7, 8, 9]) % 11)}`;
}
function pisChecksum(base) {
assertBase(base, 10);
return String(mod11(base, [3, 2, 9, 8, 7, 6, 5, 4, 3, 2]));
}
function renavamChecksum(base) {
assertBase(base, 10);
return String(mod11(base, [3, 2, 9, 8, 7, 6, 5, 4, 3, 2]));
}
function completeStateRegistration(base, state) {
if (state === 'SP') {
assertBase(base, 10);
const first = weightedSum(base.slice(0, 8), [1, 3, 4, 5, 6, 7, 8, 10]) % 11 % 10;
const partial = base.slice(0, 8) + first + base.slice(8);
return partial + (weightedSum(partial, [3, 2, 10, 9, 8, 7, 6, 5, 4, 3, 2]) % 11 % 10);
}
if (state === 'MG') {
assertBase(base, 11);
const expanded = base.slice(0, 3) + '0' + base.slice(3);
const sum = [...expanded].reduce((total, character, index) => {
const product = Number(character) * (index % 2 + 1);
return total + Math.floor(product / 10) + product % 10;
}, 0);
const first = (10 - sum % 10) % 10;
return base + first + mod11(base + first, [3, 2, 11, 10, 9, 8, 7, 6, 5, 4, 3, 2]);
}
if (state === 'RJ') {
assertBase(base, 7);
return base + mod11(base, [2, 7, 6, 5, 4, 3, 2]);
}
throw new Error('UF não suportada. Escolha SP, MG ou RJ.');
}
function certificateChecksum(base) {
assertBase(base, 30);
const firstRemainder = weightedSum(base, Array.from({ length: 30 }, (_, index) => (index + 2) % 11)) % 11;
const first = firstRemainder === 10 ? 1 : firstRemainder;
const second = weightedSum(base + first, Array.from({ length: 31 }, (_, index) => (index + 1) % 11)) % 11;
return `${first}${second === 10 ? 1 : second}`;
}
function randomInt(maximum) {
const values = new Uint32Array(1);
const limit = Math.floor(0x100000000 / maximum) * maximum;
do {
crypto.getRandomValues(values);
} while (values[0] >= limit);
return values[0] % maximum;
}
function randomCharacters(length, alphabet = '0123456789') {
return Array.from({ length }, () => alphabet[randomInt(alphabet.length)]).join('');
}
function formatDocument(kind, value, state = 'SP') {
switch (kind) {
case 'cpf': return value.replace(/^(\d{3})(\d{3})(\d{3})(\d{2})$/, '$1.$2.$3-$4');
case 'cnpj': return value.replace(/^(.{2})(.{3})(.{3})(.{4})(\d{2})$/, '$1.$2.$3/$4-$5');
case 'rg': return value.replace(/^(\d{2})(\d{3})(\d{3})([\dX])$/, '$1.$2.$3-$4');
case 'titulo-eleitor': return value.replace(/^(\d{4})(\d{4})(\d{4})$/, '$1 $2 $3');
case 'pis-pasep': return value.replace(/^(\d{3})(\d{5})(\d{2})(\d)$/, '$1.$2.$3-$4');
case 'inscricao-estadual':
if (state === 'SP')
return value.replace(/^(\d{3})(\d{3})(\d{3})(\d{3})$/, '$1.$2.$3.$4');
if (state === 'MG')
return value.replace(/^(\d{3})(\d{3})(\d{3})(\d{4})$/, '$1.$2.$3/$4');
return value.replace(/^(\d{2})(\d{3})(\d{2})(\d)$/, '$1.$2.$3-$4');
case 'certidao': return value.replace(/^(\d{6})(\d{2})(\d{2})(\d{4})(\d)(\d{5})(\d{3})(\d{7})(\d{2})$/, '$1 $2 $3 $4 $5 $6 $7 $8-$9');
default: return value;
}
}
function weightedSum(base, weights, alphanumeric = false) {
return [...base].reduce((sum, character, index) => sum + (alphanumeric ? character.charCodeAt(0) - 48 : Number(character)) * weights[index], 0);
}
function mod11(base, weights, alphanumeric = false) {
const remainder = weightedSum(base, weights, alphanumeric) % 11;
return remainder < 2 ? 0 : 11 - remainder;
}
function assertBase(base, length, alphanumeric = false) {
if (base.length !== length || !(alphanumeric ? /^[0-9A-Z]+$/ : /^\d+$/).test(base)) {
throw new Error(`A base deve ter ${length} ${alphanumeric ? 'caracteres de 0 a 9 ou A a Z' : 'dígitos'}.`);
}
}
for (const value of Object.values(values)) gdText(value);
return groupedDocuments(values);
}
import json
import re
import secrets
import datetime
from datetime import date
def executar(values):
def legacy_rg(count=1, formatted=True):
if type(count) is not int or not 1 <= count <= 100:
raise ValueError('Quantidade: de 1 a 100')
if type(formatted) is not bool: raise ValueError('Máscara deve ser booleana')
def generate():
results = []
def random_chars(n, alphabet='0123456789'):
return ''.join((secrets.choice(alphabet) for _ in range(n)))
def weighted_sum(base, weights, alpha=False):
return sum(((ord(c) - 48 if alpha else int(c)) * w for (c, w) in zip(base, weights)))
def dv(base, weights, alpha=False):
r = weighted_sum(base, weights, alpha) % 11
return 0 if r < 2 else 11 - r
base = random_chars(8)
digit = (11 - weighted_sum(base, [2, 3, 4, 5, 6, 7, 8, 9]) % 11) % 11
results.append(base + ('X' if digit == 10 else str(digit)))
return results[0] if len(results) == 1 else results
values = []
for _ in range(count * 30):
value = generate()
if formatted:
sizes, separators = [2,3,3,1], [".",".","-"]
cursor, parts = 0, []
for index, size in enumerate(sizes):
parts.append(value[cursor:cursor + size])
cursor += size
if index < len(separators):
parts.append(separators[index])
value = ''.join(parts)
if value not in values: values.append(value)
if len(values) == count: break
if len(values) != count: raise ValueError('Não foi possível completar o lote sem repetições')
return '\n'.join(values)
def legacy_cnh(count=1):
if type(count) is not int or not 1 <= count <= 100:
raise ValueError('Quantidade: de 1 a 100')
def generate():
results = []
def random_chars(n, alphabet='0123456789'):
return ''.join((secrets.choice(alphabet) for _ in range(n)))
def weighted_sum(base, weights, alpha=False):
return sum(((ord(c) - 48 if alpha else int(c)) * w for (c, w) in zip(base, weights)))
def dv(base, weights, alpha=False):
r = weighted_sum(base, weights, alpha) % 11
return 0 if r < 2 else 11 - r
while True:
base = random_chars(9)
r1 = weighted_sum(base, [9, 8, 7, 6, 5, 4, 3, 2, 1]) % 11
r2 = weighted_sum(base, [1, 2, 3, 4, 5, 6, 7, 8, 9]) % 11
d1 = 0 if r1 == 10 else r1
d2 = 0 if r2 == 10 else r2 - (2 if r1 == 10 else 0)
if d2 < 0:
continue
result = base + str(d1) + str(d2)
if len(set(result)) > 1:
break
results.append(result)
return results[0] if len(results) == 1 else results
values = []
for _ in range(count * 30):
value = generate()
if value not in values: values.append(value)
if len(values) == count: break
if len(values) != count: raise ValueError('Não foi possível completar o lote sem repetições')
return '\n'.join(values)
def legacy_title(count=1, uf='01', formatted=True):
if type(count) is not int or not 1 <= count <= 100:
raise ValueError('Quantidade: de 1 a 100')
if type(formatted) is not bool: raise ValueError('Máscara deve ser booleana')
def generate():
results = []
def random_chars(n, alphabet='0123456789'):
return ''.join((secrets.choice(alphabet) for _ in range(n)))
def weighted_sum(base, weights, alpha=False):
return sum(((ord(c) - 48 if alpha else int(c)) * w for (c, w) in zip(base, weights)))
def dv(base, weights, alpha=False):
r = weighted_sum(base, weights, alpha) % 11
return 0 if r < 2 else 11 - r
if uf not in [str(i).zfill(2) for i in range(1, 29)]:
raise ValueError('UF eleitoral inválida')
def digit(r):
return 0 if r == 10 else 1 if r == 0 and uf in ('01', '02') else r
base = random_chars(8)
d1 = str(digit(weighted_sum(base, [2, 3, 4, 5, 6, 7, 8, 9]) % 11))
d2 = str(digit(weighted_sum(uf + d1, [7, 8, 9]) % 11))
results.append(base + uf + d1 + d2)
return results[0] if len(results) == 1 else results
values = []
for _ in range(count * 30):
value = generate()
if formatted:
sizes, separators = [4,4,4], [" "," "]
cursor, parts = 0, []
for index, size in enumerate(sizes):
parts.append(value[cursor:cursor + size])
cursor += size
if index < len(separators):
parts.append(separators[index])
value = ''.join(parts)
if value not in values: values.append(value)
if len(values) == count: break
if len(values) != count: raise ValueError('Não foi possível completar o lote sem repetições')
return '\n'.join(values)
def legacy_pis(count=1, formatted=True):
if type(count) is not int or not 1 <= count <= 100:
raise ValueError('Quantidade: de 1 a 100')
if type(formatted) is not bool: raise ValueError('Máscara deve ser booleana')
def generate():
results = []
def random_chars(n, alphabet='0123456789'):
return ''.join((secrets.choice(alphabet) for _ in range(n)))
def weighted_sum(base, weights, alpha=False):
return sum(((ord(c) - 48 if alpha else int(c)) * w for (c, w) in zip(base, weights)))
def dv(base, weights, alpha=False):
r = weighted_sum(base, weights, alpha) % 11
return 0 if r < 2 else 11 - r
base = '1' + random_chars(9)
results.append(base + str(dv(base, [3, 2, 9, 8, 7, 6, 5, 4, 3, 2])))
return results[0] if len(results) == 1 else results
values = []
for _ in range(count * 30):
value = generate()
if formatted:
sizes, separators = [3,5,2,1], [".",".","-"]
cursor, parts = 0, []
for index, size in enumerate(sizes):
parts.append(value[cursor:cursor + size])
cursor += size
if index < len(separators):
parts.append(separators[index])
value = ''.join(parts)
if value not in values: values.append(value)
if len(values) == count: break
if len(values) != count: raise ValueError('Não foi possível completar o lote sem repetições')
return '\n'.join(values)
def legacy_renavam(count=1):
if type(count) is not int or not 1 <= count <= 100:
raise ValueError('Quantidade: de 1 a 100')
def generate():
results = []
def random_chars(n, alphabet='0123456789'):
return ''.join((secrets.choice(alphabet) for _ in range(n)))
def weighted_sum(base, weights, alpha=False):
return sum(((ord(c) - 48 if alpha else int(c)) * w for (c, w) in zip(base, weights)))
def dv(base, weights, alpha=False):
r = weighted_sum(base, weights, alpha) % 11
return 0 if r < 2 else 11 - r
base = '00' + random_chars(8)
results.append(base + str(dv(base, [3, 2, 9, 8, 7, 6, 5, 4, 3, 2])))
return results[0] if len(results) == 1 else results
values = []
for _ in range(count * 30):
value = generate()
if value not in values: values.append(value)
if len(values) == count: break
if len(values) != count: raise ValueError('Não foi possível completar o lote sem repetições')
return '\n'.join(values)
def legacy_certificate(count=1, type_code='1', year=None, formatted=True):
if type(count) is not int or not 1 <= count <= 100:
raise ValueError('Quantidade: de 1 a 100')
if type(formatted) is not bool: raise ValueError('Máscara deve ser booleana')
year = date.today().year if year is None else year
def generate():
results = []
def random_chars(n, alphabet='0123456789'):
return ''.join((secrets.choice(alphabet) for _ in range(n)))
def weighted_sum(base, weights, alpha=False):
return sum(((ord(c) - 48 if alpha else int(c)) * w for (c, w) in zip(base, weights)))
def dv(base, weights, alpha=False):
r = weighted_sum(base, weights, alpha) % 11
return 0 if r < 2 else 11 - r
if type_code not in ('1', '2', '4') or type(year) is not int or not 1900 <= year <= date.today().year:
raise ValueError('Tipo ou ano inválido')
def pad_random(maximum, size):
return str(secrets.randbelow(maximum) + 1).zfill(size)
base = pad_random(999999, 6) + '0155' + str(year) + type_code + pad_random(99999, 5) + pad_random(300, 3) + pad_random(9999999, 7)
r1 = weighted_sum(base, [(i + 2) % 11 for i in range(30)]) % 11
d1 = str(1 if r1 == 10 else r1)
r2 = weighted_sum(base + d1, [(i + 1) % 11 for i in range(31)]) % 11
results.append(base + d1 + str(1 if r2 == 10 else r2))
return results[0] if len(results) == 1 else results
values = []
for _ in range(count * 30):
value = generate()
if formatted:
sizes, separators = [6,2,2,4,1,5,3,7,2], [" "," "," "," "," "," "," ","-"]
cursor, parts = 0, []
for index, size in enumerate(sizes):
parts.append(value[cursor:cursor + size])
cursor += size
if index < len(separators):
parts.append(separators[index])
value = ''.join(parts)
if value not in values: values.append(value)
if len(values) == count: break
if len(values) != count: raise ValueError('Não foi possível completar o lote sem repetições')
return '\n'.join(values)
def integer(key, low, high):
raw = values.get(key, '')
if not re.fullmatch(r'-?[0-9]+', raw) or not low <= int(raw) <= high:
raise ValueError(f'{key}: informe um inteiro entre {low} e {high}.')
return int(raw)
def choice(key, allowed):
if values.get(key) not in allowed:
raise ValueError('Opção inválida: ' + key)
return values[key]
def mask():
return choice('formatted', ['true', 'false']) == 'true'
def batch(make):
count, result, seen = integer('count', 1, 100), [], set()
for _ in range(count * 100):
value = make()
if value not in seen:
seen.add(value)
result.append(value)
if len(result) == count:
return result
raise ValueError('Não foi possível completar o lote sem repetições. Reduza a quantidade ou amplie o domínio.')
def json_text(data):
return json.dumps(data, ensure_ascii=False, indent=2, allow_nan=False)
def output(data, as_json=False):
return {'text': json_text(data) if as_json else '\n'.join(data), 'file': 'dados.json' if as_json else 'dados.txt'}
for value in values.values():
if not isinstance(value, str) or len(value.encode('utf-16-le')) // 2 > 10000:
raise ValueError('Use texto Unicode válido de até 10 mil caracteres por campo.')
value.encode('utf-8')
kind = choice('document', ['rg', 'cnh', 'titulo-eleitor', 'pis-pasep', 'renavam', 'certidao'])
formatted = kind not in ['cnh', 'renavam'] and mask()
uf = choice('electoralState', [str(i).zfill(2) for i in range(1, 29)]) if kind == 'titulo-eleitor' else '01'
type_code = choice('certificateType', ['1', '2', '4']) if kind == 'certidao' else '1'
year = integer('year', 1900, datetime.datetime.now().year) if kind == 'certidao' else 2024
generators = {'rg': lambda: legacy_rg(1, formatted=formatted), 'cnh': lambda: legacy_cnh(1), 'titulo-eleitor': lambda: legacy_title(1, uf=uf, formatted=formatted), 'pis-pasep': lambda: legacy_pis(1, formatted=formatted), 'renavam': lambda: legacy_renavam(1), 'certidao': lambda: legacy_certificate(1, type_code=type_code, year=year, formatted=formatted)}
return output(batch(generators[kind]))
<?php
function executar(array $values): array {
// PHP 8.1+ de 64 bits, JSON/PCRE/iconv; auxiliares locais, sem arquivos do projeto.
$legacy_rg = function ($count = 1, $formatted = true) {
if (!is_int($count) || $count < 1 || $count > 100) throw new InvalidArgumentException('Quantidade: de 1 a 100');
if (!is_bool($formatted)) throw new InvalidArgumentException('Máscara deve ser booleana');
$generate = function () {
$results = [];
$random_chars = function($n, $alphabet = "0123456789") use (&$random_chars, &$weighted_sum, &$dv) {
$value = "";
for ($i = 0; $i < $n; $i++) {
$value .= $alphabet[random_int(0, strlen($alphabet) - 1)];
}
return $value;
};
$weighted_sum = function($base, $weights, $alpha = false) use (&$random_chars, &$weighted_sum, &$dv) {
$sum = 0;
foreach (str_split($base) as $i => $c) {
$sum += ($alpha ? ord($c) - 48 : (int) $c) * $weights[$i];
}
return $sum;
};
$dv = function($base, $weights, $alpha = false) use (&$random_chars, &$weighted_sum, &$dv) {
$r = $weighted_sum($base, $weights, $alpha) % 11;
return $r < 2 ? 0 : 11 - $r;
};
// RG legado: padrão SSP-SP.
$base = $random_chars(8);
$digit = (11 - $weighted_sum($base, [2,3,4,5,6,7,8,9]) % 11) % 11;
$results[] = $base . ($digit === 10 ? "X" : $digit);
return count($results) === 1 ? $results[0] : $results;
};
$values = [];
for ($attempts = 0; count($values) < $count && $attempts < $count * 30; $attempts++) {
$value = $generate();
if ($formatted) {
$sizes = [2,3,3,1]; $separators = [".",".","-"];
$cursor = 0; $parts = [];
foreach ($sizes as $index => $size) {
$parts[] = substr($value, $cursor, $size); $cursor += $size;
if (isset($separators[$index])) $parts[] = $separators[$index];
}
$value = implode('', $parts);
}
if (!in_array($value, $values, true)) $values[] = $value;
}
if (count($values) !== $count) throw new RuntimeException('Não foi possível completar o lote sem repetições');
return implode("\n", $values);
};
$legacy_cnh = function ($count = 1) {
if (!is_int($count) || $count < 1 || $count > 100) throw new InvalidArgumentException('Quantidade: de 1 a 100');
$generate = function () {
$results = [];
$random_chars = function($n, $alphabet = "0123456789") use (&$random_chars, &$weighted_sum, &$dv) {
$value = "";
for ($i = 0; $i < $n; $i++) {
$value .= $alphabet[random_int(0, strlen($alphabet) - 1)];
}
return $value;
};
$weighted_sum = function($base, $weights, $alpha = false) use (&$random_chars, &$weighted_sum, &$dv) {
$sum = 0;
foreach (str_split($base) as $i => $c) {
$sum += ($alpha ? ord($c) - 48 : (int) $c) * $weights[$i];
}
return $sum;
};
$dv = function($base, $weights, $alpha = false) use (&$random_chars, &$weighted_sum, &$dv) {
$r = $weighted_sum($base, $weights, $alpha) % 11;
return $r < 2 ? 0 : 11 - $r;
};
// Número de registro da CNH (11 dígitos).
while (true) {
$base = $random_chars(9);
$r1 = $weighted_sum($base, [9,8,7,6,5,4,3,2,1]) % 11;
$r2 = $weighted_sum($base, [1,2,3,4,5,6,7,8,9]) % 11;
$d1 = $r1 === 10 ? 0 : $r1;
$d2 = $r2 === 10 ? 0 : $r2 - ($r1 === 10 ? 2 : 0);
if ($d2 < 0) continue;
$result = $base . $d1 . $d2;
if (!preg_match('/^(\d)\1{10}$/', $result)) break;
}
$results[] = $result;
return count($results) === 1 ? $results[0] : $results;
};
$values = [];
for ($attempts = 0; count($values) < $count && $attempts < $count * 30; $attempts++) {
$value = $generate();
if (!in_array($value, $values, true)) $values[] = $value;
}
if (count($values) !== $count) throw new RuntimeException('Não foi possível completar o lote sem repetições');
return implode("\n", $values);
};
$legacy_title = function ($count = 1, $uf = '01', $formatted = true) {
if (!is_int($count) || $count < 1 || $count > 100) throw new InvalidArgumentException('Quantidade: de 1 a 100');
if (!is_bool($formatted)) throw new InvalidArgumentException('Máscara deve ser booleana');
$generate = function () use ($uf) {
$results = [];
$random_chars = function($n, $alphabet = "0123456789") use (&$random_chars, &$weighted_sum, &$dv) {
$value = "";
for ($i = 0; $i < $n; $i++) {
$value .= $alphabet[random_int(0, strlen($alphabet) - 1)];
}
return $value;
};
$weighted_sum = function($base, $weights, $alpha = false) use (&$random_chars, &$weighted_sum, &$dv) {
$sum = 0;
foreach (str_split($base) as $i => $c) {
$sum += ($alpha ? ord($c) - 48 : (int) $c) * $weights[$i];
}
return $sum;
};
$dv = function($base, $weights, $alpha = false) use (&$random_chars, &$weighted_sum, &$dv) {
$r = $weighted_sum($base, $weights, $alpha) % 11;
return $r < 2 ? 0 : 11 - $r;
};
if (!in_array($uf, array_map(fn($i) => sprintf('%02d', $i), range(1,28)), true)) throw new InvalidArgumentException('UF eleitoral inválida'); // SP=01, MG=02, RJ=03; exterior=28.
$digit = fn($r) => $r === 10 ? 0 : ($r === 0 && in_array($uf, ["01","02"]) ? 1 : $r);
$base = $random_chars(8);
$d1 = $digit($weighted_sum($base, [2,3,4,5,6,7,8,9]) % 11);
$d2 = $digit($weighted_sum($uf . $d1, [7,8,9]) % 11);
$results[] = $base . $uf . $d1 . $d2;
return count($results) === 1 ? $results[0] : $results;
};
$values = [];
for ($attempts = 0; count($values) < $count && $attempts < $count * 30; $attempts++) {
$value = $generate();
if ($formatted) {
$sizes = [4,4,4]; $separators = [" "," "];
$cursor = 0; $parts = [];
foreach ($sizes as $index => $size) {
$parts[] = substr($value, $cursor, $size); $cursor += $size;
if (isset($separators[$index])) $parts[] = $separators[$index];
}
$value = implode('', $parts);
}
if (!in_array($value, $values, true)) $values[] = $value;
}
if (count($values) !== $count) throw new RuntimeException('Não foi possível completar o lote sem repetições');
return implode("\n", $values);
};
$legacy_pis = function ($count = 1, $formatted = true) {
if (!is_int($count) || $count < 1 || $count > 100) throw new InvalidArgumentException('Quantidade: de 1 a 100');
if (!is_bool($formatted)) throw new InvalidArgumentException('Máscara deve ser booleana');
$generate = function () {
$results = [];
$random_chars = function($n, $alphabet = "0123456789") use (&$random_chars, &$weighted_sum, &$dv) {
$value = "";
for ($i = 0; $i < $n; $i++) {
$value .= $alphabet[random_int(0, strlen($alphabet) - 1)];
}
return $value;
};
$weighted_sum = function($base, $weights, $alpha = false) use (&$random_chars, &$weighted_sum, &$dv) {
$sum = 0;
foreach (str_split($base) as $i => $c) {
$sum += ($alpha ? ord($c) - 48 : (int) $c) * $weights[$i];
}
return $sum;
};
$dv = function($base, $weights, $alpha = false) use (&$random_chars, &$weighted_sum, &$dv) {
$r = $weighted_sum($base, $weights, $alpha) % 11;
return $r < 2 ? 0 : 11 - $r;
};
$base = "1" . $random_chars(9);
$results[] = $base . $dv($base, [3,2,9,8,7,6,5,4,3,2]);
return count($results) === 1 ? $results[0] : $results;
};
$values = [];
for ($attempts = 0; count($values) < $count && $attempts < $count * 30; $attempts++) {
$value = $generate();
if ($formatted) {
$sizes = [3,5,2,1]; $separators = [".",".","-"];
$cursor = 0; $parts = [];
foreach ($sizes as $index => $size) {
$parts[] = substr($value, $cursor, $size); $cursor += $size;
if (isset($separators[$index])) $parts[] = $separators[$index];
}
$value = implode('', $parts);
}
if (!in_array($value, $values, true)) $values[] = $value;
}
if (count($values) !== $count) throw new RuntimeException('Não foi possível completar o lote sem repetições');
return implode("\n", $values);
};
$legacy_renavam = function ($count = 1) {
if (!is_int($count) || $count < 1 || $count > 100) throw new InvalidArgumentException('Quantidade: de 1 a 100');
$generate = function () {
$results = [];
$random_chars = function($n, $alphabet = "0123456789") use (&$random_chars, &$weighted_sum, &$dv) {
$value = "";
for ($i = 0; $i < $n; $i++) {
$value .= $alphabet[random_int(0, strlen($alphabet) - 1)];
}
return $value;
};
$weighted_sum = function($base, $weights, $alpha = false) use (&$random_chars, &$weighted_sum, &$dv) {
$sum = 0;
foreach (str_split($base) as $i => $c) {
$sum += ($alpha ? ord($c) - 48 : (int) $c) * $weights[$i];
}
return $sum;
};
$dv = function($base, $weights, $alpha = false) use (&$random_chars, &$weighted_sum, &$dv) {
$r = $weighted_sum($base, $weights, $alpha) % 11;
return $r < 2 ? 0 : 11 - $r;
};
$base = "00" . $random_chars(8);
$results[] = $base . $dv($base, [3,2,9,8,7,6,5,4,3,2]);
return count($results) === 1 ? $results[0] : $results;
};
$values = [];
for ($attempts = 0; count($values) < $count && $attempts < $count * 30; $attempts++) {
$value = $generate();
if (!in_array($value, $values, true)) $values[] = $value;
}
if (count($values) !== $count) throw new RuntimeException('Não foi possível completar o lote sem repetições');
return implode("\n", $values);
};
$legacy_certificate = function ($count = 1, $type = '1', $year = null, $formatted = true) {
if (!is_int($count) || $count < 1 || $count > 100) throw new InvalidArgumentException('Quantidade: de 1 a 100');
if (!is_bool($formatted)) throw new InvalidArgumentException('Máscara deve ser booleana');
$generate = function () use ($type, $year) {
$results = [];
$random_chars = function($n, $alphabet = "0123456789") use (&$random_chars, &$weighted_sum, &$dv) {
$value = "";
for ($i = 0; $i < $n; $i++) {
$value .= $alphabet[random_int(0, strlen($alphabet) - 1)];
}
return $value;
};
$weighted_sum = function($base, $weights, $alpha = false) use (&$random_chars, &$weighted_sum, &$dv) {
$sum = 0;
foreach (str_split($base) as $i => $c) {
$sum += ($alpha ? ord($c) - 48 : (int) $c) * $weights[$i];
}
return $sum;
};
$dv = function($base, $weights, $alpha = false) use (&$random_chars, &$weighted_sum, &$dv) {
$r = $weighted_sum($base, $weights, $alpha) % 11;
return $r < 2 ? 0 : 11 - $r;
};
// Matrícula sintética: CNS aleatório, acervo 01, serviço 55.
// Tipo: 1=nascimento, 2=casamento, 4=óbito.
$year ??= (int)date('Y');
if (!in_array($type, ['1','2','4'], true) || !is_int($year) || $year < 1900 || $year > (int)date('Y')) throw new InvalidArgumentException('Tipo ou ano inválido');
$pad = fn($max, $size) => str_pad((string) random_int(1,$max), $size, "0", STR_PAD_LEFT);
$base = $pad(999999,6) . "0155" . $year . $type
. $pad(99999,5) . $pad(300,3) . $pad(9999999,7);
$w1 = array_map(fn($i) => ($i+2)%11, range(0,29));
$w2 = array_map(fn($i) => ($i+1)%11, range(0,30));
$r1 = $weighted_sum($base,$w1) % 11;
$d1 = $r1 === 10 ? 1 : $r1;
$r2 = $weighted_sum($base . $d1,$w2) % 11;
$results[] = $base . $d1 . ($r2 === 10 ? 1 : $r2);
return count($results) === 1 ? $results[0] : $results;
};
$values = [];
for ($attempts = 0; count($values) < $count && $attempts < $count * 30; $attempts++) {
$value = $generate();
if ($formatted) {
$sizes = [6,2,2,4,1,5,3,7,2]; $separators = [" "," "," "," "," "," "," ","-"];
$cursor = 0; $parts = [];
foreach ($sizes as $index => $size) {
$parts[] = substr($value, $cursor, $size); $cursor += $size;
if (isset($separators[$index])) $parts[] = $separators[$index];
}
$value = implode('', $parts);
}
if (!in_array($value, $values, true)) $values[] = $value;
}
if (count($values) !== $count) throw new RuntimeException('Não foi possível completar o lote sem repetições');
return implode("\n", $values);
};
$integer = static function (string $key, int $min, int $max) use ($values): int {
$raw = $values[$key] ?? '';
if (!preg_match('/^-?[0-9]+$/D', $raw) || strlen(ltrim($raw, '-0')) > 10 || (int)$raw < $min || (int)$raw > $max) throw new InvalidArgumentException("$key: informe um inteiro entre $min e $max.");
return (int)$raw;
};
$choice = static function (string $key, array $allowed) use ($values): string {
if (!in_array($values[$key] ?? null, $allowed, true)) throw new InvalidArgumentException('Opção inválida: ' . $key);
return $values[$key];
};
$mask = static fn(): bool => $choice('formatted', ['true', 'false']) === 'true';
$batch = static function (Closure $make) use ($integer): array {
$count = $integer('count', 1, 100); $rows = []; $seen = [];
for ($attempt = 0; $attempt < $count * 100; $attempt++) {
$value = $make(); $key = json_encode($value, JSON_THROW_ON_ERROR);
if (!isset($seen[$key])) { $seen[$key] = true; $rows[] = $value; }
if (count($rows) === $count) return $rows;
}
throw new InvalidArgumentException('Não foi possível completar o lote sem repetições. Reduza a quantidade ou amplie o domínio.');
};
$jsonText = static function ($value): string {
$text = json_encode($value, JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_LINE_TERMINATORS | JSON_THROW_ON_ERROR);
return preg_replace_callback('/^ +/m', static fn($m) => str_repeat(' ', intdiv(strlen($m[0]), 2)), $text);
};
$output = static fn(array $rows, bool $json = false): array => ['text' => $json ? $jsonText($rows) : implode("\n", $rows), 'file' => $json ? 'dados.json' : 'dados.txt'];
foreach ($values as $value) {
if (!is_string($value) || preg_match('//u', $value) !== 1 || strlen(iconv('UTF-8', 'UTF-16LE', $value)) / 2 > 10000) throw new InvalidArgumentException('Use texto Unicode válido de até 10 mil caracteres por campo.');
}
$kind = $choice('document', ['rg', 'cnh', 'titulo-eleitor', 'pis-pasep', 'renavam', 'certidao']);
$formatted = !in_array($kind, ['cnh', 'renavam'], true) && $mask();
$uf = $kind === 'titulo-eleitor' ? $choice('electoralState', array_map(static fn($n) => str_pad((string)$n, 2, '0', STR_PAD_LEFT), range(1, 28))) : '01';
$type = $kind === 'certidao' ? $choice('certificateType', ['1', '2', '4']) : '1';
$year = $kind === 'certidao' ? $integer('year', 1900, (int)date('Y')) : 2024;
$generators = ['rg' => static fn() => $legacy_rg(1, $formatted), 'cnh' => static fn() => $legacy_cnh(1), 'titulo-eleitor' => static fn() => $legacy_title(1, $uf, $formatted), 'pis-pasep' => static fn() => $legacy_pis(1, $formatted), 'renavam' => static fn() => $legacy_renavam(1), 'certidao' => static fn() => $legacy_certificate(1, $type, $year, $formatted)];
return $output($batch($generators[$kind]));
}