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 groupedPhones(v) {
const country = gdChoice(v, 'country', ['BR', 'US', 'GB', 'PT']), presentation = gdChoice(v, 'presentation', ['national', 'international']), formatted = presentation === 'national' && gdMask(v);
const ddd = country === 'BR' ? gdChoice(v, 'ddd', BRAZIL_DDDS.map(String)) : '11', phoneType = country === 'BR' ? gdChoice(v, 'phoneType', ['mobile', 'landline']) : 'mobile';
return gdOutput(gdBatch(v, () => {
if (country === 'BR' && presentation === 'national')
return generateData('phone-br', { ddd, phoneType, formatted: String(formatted) });
const international = generateData('phone-international', { country, ddd, phoneType });
if (presentation === 'international')
return international;
if (country === 'US') {
const local = international.slice(2);
return formatted ? local.replace(/^(\d{3})(\d{3})(\d{4})$/, '($1) $2-$3') : local;
}
if (country === 'GB') {
const local = '0' + international.slice(3);
return formatted ? local.slice(0, 5) + ' ' + local.slice(5) : local;
}
const local = international.slice(4);
return formatted ? local.replace(/^(\d{3})(\d{3})(\d{3})$/, '$1 $2 $3') : local;
}));
}
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];
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 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 groupedPhones(values);
}
import json
import re
import secrets
def executar(values):
def legacy_brazil(count=1, ddd='11', phone_type='mobile', 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)))
if ddd not in [str(n) for n in [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]] or phone_type not in ('mobile', 'landline'):
raise ValueError('DDD ou tipo inválido')
phone = '9' + text(8) if phone_type == 'mobile' else str(secrets.randbelow(4) + 2) + text(7)
results.append(f'({ddd}) {phone[:-4]}-{phone[-4:]}')
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_international(count=1, country='US', ddd='11', phone_type='mobile'):
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)))
if country == 'US':
result = '+1202555' + str(secrets.randbelow(100) + 100).zfill(4)
elif country == 'GB':
result = '+447700900' + text(3)
elif country == 'PT':
result = '+3519' + secrets.choice('1236') + text(7)
elif country == 'BR':
if ddd not in [str(n) for n in [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]] or phone_type not in ('mobile', 'landline'):
raise ValueError('DDD ou tipo inválido')
result = '+55' + ddd + ('9' + text(8) if phone_type == 'mobile' else str(secrets.randbelow(4) + 2) + text(7))
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)
DDD = ["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"]
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, presentation = choice('country', ['BR', 'US', 'GB', 'PT']), choice('presentation', ['national', 'international'])
formatted = presentation == 'national' and mask()
ddd = choice('ddd', DDD) if country == 'BR' else '11'
phone_type = choice('phoneType', ['mobile', 'landline']) if country == 'BR' else 'mobile'
def phone():
if country == 'BR' and presentation == 'national':
return legacy_brazil(1, ddd=ddd, phone_type=phone_type, formatted=formatted)
international = legacy_international(1, country=country, ddd=ddd, phone_type=phone_type)
if presentation == 'international':
return international
if country == 'US':
local = international[2:]
return f'({local[:3]}) {local[3:6]}-{local[6:]}' if formatted else local
if country == 'GB':
local = '0' + international[3:]
return local[:5] + ' ' + local[5:] if formatted else local
local = international[4:]
return ' '.join([local[:3], local[3:6], local[6:]]) if formatted else local
return output(batch(phone))
<?php
function executar(array $values): array {
// PHP 8.1+ de 64 bits, JSON/PCRE/iconv; auxiliares locais, sem arquivos do projeto.
$legacy_brazil = function ($count = 1, $ddd = '11', $phoneType = 'mobile', $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 ($ddd, $phoneType) {
$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;
};
if (!in_array($ddd, array_map('strval', [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]), true) || !in_array($phoneType, ['mobile','landline'], true)) throw new InvalidArgumentException('DDD ou tipo inválido');
$phone = $phoneType === 'mobile' ? '9' . $text(8) : random_int(2,5) . $text(7);
$results[] = "(" . $ddd . ") " . substr($phone,0,-4) . "-" . substr($phone,-4);
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_international = function ($count = 1, $country = 'US', $ddd = '11', $phoneType = 'mobile') {
if (!is_int($count) || $count < 1 || $count > 100) throw new InvalidArgumentException('Quantidade: de 1 a 100');
$generate = function () use ($country, $ddd, $phoneType) {
$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;
};
// E.164: exemplo dos EUA, faixa fictícia 555-0100 a 0199.
if ($country === 'US') $result = '+1202555' . sprintf('%04d', random_int(100,199));
elseif ($country === 'GB') $result = '+447700900' . $text(3);
elseif ($country === 'PT') $result = '+3519' . '1236'[random_int(0,3)] . $text(7);
elseif ($country === 'BR') {
if (!in_array($ddd, array_map('strval', [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]), true) || !in_array($phoneType, ['mobile','landline'], true)) throw new InvalidArgumentException('DDD ou tipo inválido');
$result = '+55' . $ddd . ($phoneType === 'mobile' ? '9' . $text(8) : random_int(2,5) . $text(7));
} else throw new InvalidArgumentException('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);
};
$DDD = json_decode('["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"]', true, 512, JSON_THROW_ON_ERROR);
$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', ['BR', 'US', 'GB', 'PT']); $presentation = $choice('presentation', ['national', 'international']);
$formatted = $presentation === 'national' && $mask();
$ddd = $country === 'BR' ? $choice('ddd', $DDD) : '11';
$phoneType = $country === 'BR' ? $choice('phoneType', ['mobile', 'landline']) : 'mobile';
$phone = static function () use ($country, $presentation, $formatted, $ddd, $phoneType, $legacy_brazil, $legacy_international): string {
if ($country === 'BR' && $presentation === 'national') return $legacy_brazil(1, $ddd, $phoneType, $formatted);
$international = $legacy_international(1, $country, $ddd, $phoneType);
if ($presentation === 'international') return $international;
if ($country === 'US') { $local = substr($international, 2); return $formatted ? '(' . substr($local, 0, 3) . ') ' . substr($local, 3, 3) . '-' . substr($local, 6) : $local; }
if ($country === 'GB') { $local = '0' . substr($international, 3); return $formatted ? substr($local, 0, 5) . ' ' . substr($local, 5) : $local; }
$local = substr($international, 4);
return $formatted ? implode(' ', str_split($local, 3)) : $local;
};
return $output($batch($phone));
}