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 groupedFiscal(v) {
const country = gdChoice(v, 'country', ['US', 'PT', 'DE', 'FR', 'IT']), kind = gdChoice(v, 'identifier', country === 'US' ? ['ssn'] : country === 'PT' ? ['nif', 'vat'] : ['vat']);
const nifType = kind === 'nif' ? gdChoice(v, 'nifType', ['person', 'company']) : 'company', formatted = kind === 'ssn' ? String(gdMask(v)) : 'false';
return gdOutput(gdBatch(v, () => generateData(kind, { country, nifType, formatted })));
}
function generateData(kind, options = {}) {
const formatted = options.formatted !== 'false';
switch (kind) {
case 'ssn': {
let area;
do {
area = secureInt(899) + 1;
} while (area === 666);
const parts = [String(area).padStart(3, '0'), String(secureInt(99) + 1).padStart(2, '0'), String(secureInt(9999) + 1).padStart(4, '0')];
return parts.join(formatted ? '-' : '');
}
case 'nif': {
const prefix = choose(options, 'nifType', ['person', 'company'], 'person') === 'company' ? '5' : String(secureInt(3) + 1);
const base = prefix + randomText(7);
return base + nifDigit(base);
}
case 'vat': {
const country = choose(options, 'country', ['PT', 'DE', 'FR', 'IT'], 'PT');
if (country === 'PT')
return 'PT' + generateData('nif', { nifType: 'company' });
if (country === 'DE') {
const base = String(secureInt(9) + 1) + randomText(7);
return 'DE' + base + germanVatDigit(base);
}
if (country === 'FR') {
const base = String(secureInt(9) + 1) + randomText(7);
const siren = base + luhnDigit(base);
return 'FR' + String((12 + 3 * (Number(siren) % 97)) % 97).padStart(2, '0') + siren;
}
const base = String(secureInt(9999999) + 1).padStart(7, '0') + String(secureInt(100) + 1).padStart(3, '0');
return 'IT' + base + luhnDigit(base);
}
case 'iban': {
const country = choose(options, 'country', ['PT', 'DE', 'GB'], 'DE');
let bban = randomText(18);
if (country === 'GB')
bban = randomText(4, 'ABCDEFGHIJKLMNOPQRSTUVWXYZ') + randomText(14);
if (country === 'PT') {
const base = randomText(19);
bban = base + String(98 - mod97(base + '00')).padStart(2, '0');
}
const iban = completeIban(country, bban);
return formatted ? iban.match(/.{1,4}/g).join(' ') : iban;
}
case 'passport': {
const country = choose(options, 'country', ['BR', 'PT', 'US'], 'BR');
// BR/PT: duas letras + seis dígitos. EUA: formato numérico legado.
return country === 'US' ? String(secureInt(9) + 1) + randomText(8) : randomText(2, 'ABCDEFGHIJKLMNOPQRSTUVWXYZ') + randomText(6);
}
case 'phone-br': {
const { ddd, local } = generateBrazilianPhone(options);
return formatted ? `(${ddd}) ${local.slice(0, -4)}-${local.slice(-4)}` : ddd + local;
}
case 'phone-international': {
const country = choose(options, 'country', ['BR', 'US', 'PT', 'GB'], 'US');
if (country === 'BR') {
const { ddd, local } = generateBrazilianPhone(options);
return '+55' + ddd + local;
}
if (country === 'US')
return '+1202555' + String(secureInt(100) + 100).padStart(4, '0');
if (country === 'GB')
return '+447700900' + String(secureInt(1000)).padStart(3, '0');
return '+3519' + randomText(1, '1236') + randomText(7);
}
case 'email': {
const domain = choose(options, 'domain', ['example.com', 'example.net', 'example.org'], 'example.com');
return 'dev.' + randomText(12, 'abcdefghijklmnopqrstuvwxyz0123456789') + '@' + domain;
}
case 'temporary-email': return 'temp.' + randomText(16, 'abcdefghijklmnopqrstuvwxyz0123456789') + '@example.net';
case 'cep': {
const value = randomText(8);
return formatted ? value.slice(0, 5) + '-' + value.slice(5) : value;
}
case 'address': {
const cityId = choose(options, 'city', ADDRESS_CITIES.map(city => city.id), 'SP');
const city = ADDRESS_CITIES.find(item => item.id === cityId);
const street = ['Rua Exemplo', 'Avenida de Teste', 'Travessa Modelo'][secureInt(3)];
const cep = city.prefix + randomText(5);
return JSON.stringify({ logradouro: street, numero: secureInt(9999) + 1, complemento: 'Apto ' + (secureInt(200) + 1), bairro: 'Bairro Exemplo', cidade: city.city, uf: city.state, cep: cep.slice(0, 5) + '-' + cep.slice(5), pais: 'Brasil' }, null, 2);
}
case 'coordinates': {
const precision = Number(options.precision ?? '6');
if (!Number.isInteger(precision) || precision < 0 || precision > 8)
throw new Error('Escolha entre 0 e 8 casas decimais.');
// Área uniforme sobre a esfera: latitude derivada de sin(latitude).
const latitude = Math.asin(secureInt(0x100000000) / 0x100000000 * 2 - 1) * 180 / Math.PI;
const longitude = secureInt(0x100000000) / 0x100000000 * 360 - 180;
return `${latitude.toFixed(precision)}, ${longitude.toFixed(precision)}`;
}
case 'uuid': return generateUuid(choose(options, 'version', ['1', '4', '7'], '4'));
case 'nanoid': {
const length = Number(options.length ?? '21');
if (!Number.isInteger(length) || length < 1 || length > 128)
throw new Error('O NanoID deve ter entre 1 e 128 caracteres.');
return randomText(length, URL_ALPHABET);
}
default: throw new Error('Gerador não suportado.');
}
}
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' }; }
const ADDRESS_CITIES = [
{ id: 'SP', city: 'São Paulo', state: 'SP', prefix: '010' },
{ id: 'RJ', city: 'Rio de Janeiro', state: 'RJ', prefix: '200' },
{ id: 'MG', city: 'Belo Horizonte', state: 'MG', prefix: '301' },
{ id: 'PR', city: 'Curitiba', state: 'PR', prefix: '800' },
{ id: 'RS', city: 'Porto Alegre', state: 'RS', prefix: '900' },
{ id: 'BA', city: 'Salvador', state: 'BA', prefix: '400' },
{ id: 'PE', city: 'Recife', state: 'PE', prefix: '500' },
{ id: 'DF', city: 'Brasília', state: 'DF', prefix: '700' },
];
const URL_ALPHABET = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ_abcdefghijklmnopqrstuvwxyz-';
function secureInt(maximum) {
if (!Number.isSafeInteger(maximum) || maximum < 1 || maximum > 0x100000000)
throw new Error('Intervalo aleatório inválido.');
const buffer = new Uint32Array(1);
const limit = Math.floor(0x100000000 / maximum) * maximum;
do {
crypto.getRandomValues(buffer);
} while (buffer[0] >= limit);
return buffer[0] % maximum;
}
function randomText(length, alphabet = '0123456789') {
if (!Number.isInteger(length) || length < 1 || length > 256 || !alphabet)
throw new Error('Comprimento ou alfabeto inválido.');
return Array.from({ length }, () => alphabet[secureInt(alphabet.length)]).join('');
}
function luhnDigit(base) {
if (!/^\d+$/.test(base))
throw new Error('A base deve conter somente dígitos.');
const total = [...base].reverse().reduce((sum, character, index) => {
const value = Number(character) * (index % 2 === 0 ? 2 : 1);
return sum + (value > 9 ? value - 9 : value);
}, 0);
return String((10 - total % 10) % 10);
}
function nifDigit(base) {
if (!/^\d{8}$/.test(base))
throw new Error('A base do NIF deve conter oito dígitos.');
const remainder = [...base].reduce((sum, c, i) => sum + Number(c) * (9 - i), 0) % 11;
return String(remainder < 2 ? 0 : 11 - remainder);
}
function germanVatDigit(base) {
if (!/^[1-9]\d{7}$/.test(base))
throw new Error('Base de VAT alemão inválida.');
let product = 10;
for (const character of base)
product = (((product + Number(character)) % 10 || 10) * 2) % 11;
return String((11 - product) % 10);
}
function mod97(value) {
if (!/^[A-Z0-9]+$/.test(value))
throw new Error('Use letras maiúsculas e dígitos no IBAN.');
let remainder = 0;
for (const character of value) {
const decimal = /[A-Z]/.test(character) ? String(character.charCodeAt(0) - 55) : character;
for (const digit of decimal)
remainder = (remainder * 10 + Number(digit)) % 97;
}
return remainder;
}
function completeIban(country, bban) {
const patterns = { DE: /^\d{18}$/, PT: /^\d{21}$/, GB: /^[A-Z]{4}\d{14}$/ };
if (!patterns[country]?.test(bban))
throw new Error('País ou estrutura de IBAN não suportado.');
return country + String(98 - mod97(bban + country + '00')).padStart(2, '0') + bban;
}
function generateUuid(version, now = Date.now()) {
if (!Number.isSafeInteger(now) || now < 0 || now > 281474976710655)
throw new Error('Timestamp inválido.');
const bytes = crypto.getRandomValues(new Uint8Array(16));
if (version === '4')
bytes[6] = (bytes[6] & 15) | 64;
else if (version === '7') {
let timestamp = BigInt(now);
for (let index = 5; index >= 0; index--) {
bytes[index] = Number(timestamp & BigInt(255));
timestamp >>= BigInt(8);
}
bytes[6] = (bytes[6] & 15) | 112;
}
else if (version === '1') {
if (!uuidNodeInitialized) {
crypto.getRandomValues(uuidNode);
uuidNode[0] |= 1; // Multicast: nó aleatório, sem MAC do dispositivo.
v1Sequence = secureInt(16384);
uuidNodeInitialized = true;
}
let timestamp = BigInt(now) * BigInt(10000) + BigInt('122192928000000000');
if (timestamp <= lastV1Timestamp) {
if (timestamp < lastV1Timestamp - BigInt(10000))
v1Sequence = (v1Sequence + 1) & 16383;
timestamp = lastV1Timestamp + BigInt(1);
}
lastV1Timestamp = timestamp;
const low = Number(timestamp & BigInt('0xffffffff'));
bytes[0] = low >>> 24;
bytes[1] = low >>> 16;
bytes[2] = low >>> 8;
bytes[3] = low;
const mid = Number((timestamp >> BigInt(32)) & BigInt('0xffff'));
bytes[4] = mid >>> 8;
bytes[5] = mid;
const high = Number((timestamp >> BigInt(48)) & BigInt('0xfff'));
bytes[6] = (high >>> 8) | 16;
bytes[7] = high;
bytes[8] = v1Sequence >>> 8;
bytes[9] = v1Sequence;
bytes.set(uuidNode, 10);
}
else
throw new Error('Escolha UUID v1, v4 ou v7.');
bytes[8] = (bytes[8] & 63) | 128;
return uuidString(bytes);
}
function choose(options, key, allowed, fallback) {
const value = options[key] ?? fallback;
if (!allowed.includes(value))
throw new Error(`Opção inválida: ${key}.`);
return value;
}
function generateBrazilianPhone(options) {
const ddd = options.ddd ?? '11';
if (!BRAZIL_DDDS.includes(Number(ddd)))
throw new Error('DDD inválido.');
const type = choose(options, 'phoneType', ['mobile', 'landline'], 'mobile');
const local = type === 'mobile' ? '9' + randomText(8) : String(secureInt(4) + 2) + randomText(7);
return { ddd, local };
}
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; }
const BRAZIL_DDDS = [11, 12, 13, 14, 15, 16, 17, 18, 19, 21, 22, 24, 27, 28, 31, 32, 33, 34, 35, 37, 38, 41, 42, 43, 44, 45, 46, 47, 48, 49, 51, 53, 54, 55, 61, 62, 63, 64, 65, 66, 67, 68, 69, 71, 73, 74, 75, 77, 79, 81, 82, 83, 84, 85, 86, 87, 88, 89, 91, 92, 93, 94, 95, 96, 97, 98, 99];
const uuidNode = new Uint8Array(6);
let uuidNodeInitialized = false;
let lastV1Timestamp = BigInt(0);
let v1Sequence = 0;
function uuidString(bytes) {
const hex = [...bytes].map(byte => byte.toString(16).padStart(2, '0')).join('');
return `${hex.slice(0, 8)}-${hex.slice(8, 12)}-${hex.slice(12, 16)}-${hex.slice(16, 20)}-${hex.slice(20)}`;
}
for (const value of Object.values(values)) gdText(value);
return groupedFiscal(values);
}
import json
import re
import secrets
def executar(values):
def legacy_ssn(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 text(n, alphabet='0123456789'):
return ''.join((secrets.choice(alphabet) for _ in range(n)))
while True:
area = secrets.randbelow(899) + 1
if area != 666:
break
results.append(f'{area:03d}-{secrets.randbelow(99) + 1:02d}-{secrets.randbelow(9999) + 1:04d}')
return results[0] if len(results) == 1 else results
values = []
for _ in range(count * 30):
value = generate()
if not formatted: value = ''.join(c for c in value if c.isdigit())
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_vat(count=1, country='PT'):
if type(count) is not int or not 1 <= count <= 100:
raise ValueError('Quantidade: de 1 a 100')
def generate():
results = []
def text(n, alphabet='0123456789'):
return ''.join((secrets.choice(alphabet) for _ in range(n)))
def nif(base):
r = sum((int(c) * (9 - i) for (i, c) in enumerate(base))) % 11
return base + str(0 if r < 2 else 11 - r)
def luhn(base):
total = 0
for (i, c) in enumerate(reversed(base)):
n = int(c) * (2 if i % 2 == 0 else 1)
total += n - 9 if n > 9 else n
return base + str((10 - total % 10) % 10)
if country == 'PT':
result = 'PT' + nif('5' + text(7))
elif country == 'DE':
base = str(secrets.randbelow(9) + 1) + text(7)
p = 10
for c in base:
p = ((p + int(c)) % 10 or 10) * 2 % 11
result = 'DE' + base + str((11 - p) % 10)
elif country == 'FR':
siren = luhn(str(secrets.randbelow(9) + 1) + text(7))
result = 'FR' + str((12 + 3 * (int(siren) % 97)) % 97).zfill(2) + siren
elif country == 'IT':
base = str(secrets.randbelow(9999999) + 1).zfill(7) + str(secrets.randbelow(100) + 1).zfill(3)
result = 'IT' + luhn(base)
else:
raise ValueError('País não suportado')
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_nif(count=1, nif_type='person'):
if type(count) is not int or not 1 <= count <= 100:
raise ValueError('Quantidade: de 1 a 100')
def generate():
results = []
def text(n, alphabet='0123456789'):
return ''.join((secrets.choice(alphabet) for _ in range(n)))
def nif(base):
r = sum((int(c) * (9 - i) for (i, c) in enumerate(base))) % 11
return base + str(0 if r < 2 else 11 - r)
if nif_type not in ('person', 'company'):
raise ValueError('Tipo inválido')
results.append(nif(('5' if nif_type == 'company' else str(secrets.randbelow(3) + 1)) + text(7)))
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 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')
country = choice('country', ['US', 'PT', 'DE', 'FR', 'IT'])
kind = choice('identifier', ['ssn'] if country == 'US' else ['nif', 'vat'] if country == 'PT' else ['vat'])
nif_type = choice('nifType', ['person', 'company']) if kind == 'nif' else 'company'
formatted = mask() if kind == 'ssn' else False
generators = {'ssn': lambda: legacy_ssn(1, formatted=formatted), 'vat': lambda: legacy_vat(1, country=country), 'nif': lambda: legacy_nif(1, nif_type=nif_type)}
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_ssn = 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 = [];
$text = function($n, $alphabet = "0123456789") use (&$text) {
$result = "";
for ($i = 0; $i < $n; $i++) $result .= $alphabet[random_int(0, strlen($alphabet)-1)];
return $result;
};
do { $area = random_int(1,899); } while ($area === 666);
$results[] = sprintf("%03d-%02d-%04d", $area, random_int(1,99), random_int(1,9999));
return count($results) === 1 ? $results[0] : $results;
};
$values = [];
for ($attempts = 0; count($values) < $count && $attempts < $count * 30; $attempts++) {
$value = $generate();
if (!$formatted) $value = preg_replace('/[^0-9]/', '', $value);
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_vat = function ($count = 1, $country = 'PT') {
if (!is_int($count) || $count < 1 || $count > 100) throw new InvalidArgumentException('Quantidade: de 1 a 100');
$generate = function () use ($country) {
$results = [];
$text = function($n, $alphabet = "0123456789") use (&$text, &$nif, &$luhn) {
$result = "";
for ($i = 0; $i < $n; $i++) $result .= $alphabet[random_int(0, strlen($alphabet)-1)];
return $result;
};
$nif = function($base) use (&$text, &$nif, &$luhn) {
$sum = 0;
foreach (str_split($base) as $i => $c) $sum += (int)$c * (9-$i);
$r = $sum % 11;
return $base . ($r < 2 ? 0 : 11-$r);
};
$luhn = function($base) use (&$text, &$nif, &$luhn) {
$total = 0;
foreach (str_split(strrev($base)) as $i => $c) {
$n = (int)$c * ($i%2 === 0 ? 2 : 1);
$total += $n > 9 ? $n-9 : $n;
}
return $base . ((10-$total%10)%10);
};
// PT, DE, FR, IT
if ($country === "PT") $result = "PT" . $nif("5" . $text(7));
elseif ($country === "DE") {
$base = random_int(1,9) . $text(7); $p = 10;
foreach (str_split($base) as $c) $p = ((($p+(int)$c)%10 ?: 10)*2)%11;
$result = "DE" . $base . ((11-$p)%10);
} elseif ($country === "FR") {
$siren = $luhn(random_int(1,9) . $text(7));
$result = "FR" . str_pad((string)((12+3*((int)$siren%97))%97),2,"0",STR_PAD_LEFT) . $siren;
} elseif ($country === "IT") {
$base = sprintf("%07d%03d",random_int(1,9999999),random_int(1,100));
$result = "IT" . $luhn($base);
} else throw new Exception("País não suportado");
$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_nif = function ($count = 1, $nifType = 'person') {
if (!is_int($count) || $count < 1 || $count > 100) throw new InvalidArgumentException('Quantidade: de 1 a 100');
$generate = function () use ($nifType) {
$results = [];
$text = function($n, $alphabet = "0123456789") use (&$text, &$nif) {
$result = "";
for ($i = 0; $i < $n; $i++) $result .= $alphabet[random_int(0, strlen($alphabet)-1)];
return $result;
};
$nif = function($base) use (&$text, &$nif) {
$sum = 0;
foreach (str_split($base) as $i => $c) $sum += (int)$c * (9-$i);
$r = $sum % 11;
return $base . ($r < 2 ? 0 : 11-$r);
};
if (!in_array($nifType, ['person','company'], true)) throw new InvalidArgumentException('Tipo inválido');
$results[] = $nif(($nifType === 'company' ? '5' : (string)random_int(1,3)) . $text(7));
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);
};
$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.');
}
$country = $choice('country', ['US', 'PT', 'DE', 'FR', 'IT']);
$kind = $choice('identifier', $country === 'US' ? ['ssn'] : ($country === 'PT' ? ['nif', 'vat'] : ['vat']));
$nifType = $kind === 'nif' ? $choice('nifType', ['person', 'company']) : 'company';
$formatted = $kind === 'ssn' && $mask();
$generators = ['ssn' => static fn() => $legacy_ssn(1, $formatted), 'vat' => static fn() => $legacy_vat(1, $country), 'nif' => static fn() => $legacy_nif(1, $nifType)];
return $output($batch($generators[$kind]));
}