first commit
This commit is contained in:
@@ -0,0 +1,89 @@
|
||||
<?php
|
||||
namespace WorkbloomERP\Utils;
|
||||
|
||||
class ValidateUtil {
|
||||
public static function cpf(?string $cpf): bool {
|
||||
if ($cpf == null) {
|
||||
return false;
|
||||
}
|
||||
// Remove tudo que não for número
|
||||
$cpf = preg_replace('/\D/', '', $cpf);
|
||||
// Precisa ter 11 dígitos
|
||||
if (strlen($cpf) !== 11) {
|
||||
return false;
|
||||
}
|
||||
// Bloqueia CPFs com todos os dígitos iguais (11111111111, 00000000000, etc)
|
||||
if (preg_match('/^(\d)\1{10}$/', $cpf)) {
|
||||
return false;
|
||||
}
|
||||
// Valida primeiro dígito verificador
|
||||
for ($t = 9; $t < 11; $t++) {
|
||||
$soma = 0;
|
||||
for ($i = 0; $i < $t; $i++) {
|
||||
$soma += $cpf[$i] * (($t + 1) - $i);
|
||||
}
|
||||
$digito = ((10 * $soma) % 11) % 10;
|
||||
if ($cpf[$t] != $digito) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
public static function cnpj(?string $cnpj): bool {
|
||||
if ($cnpj == null) {
|
||||
return false;
|
||||
}
|
||||
// Remove máscara
|
||||
$cnpj = strtoupper(preg_replace('/[^A-Z0-9]/', '', $cnpj));
|
||||
// Tamanho fixo
|
||||
if (strlen($cnpj) !== 14) {
|
||||
return false;
|
||||
}
|
||||
|
||||
// Bloqueia CNPJs com todos os dígitos iguais (11111111111111, 00000000000000, etc)
|
||||
if (preg_match('/^(\d)\1{13}$/', $cnpj)) {
|
||||
return false;
|
||||
}
|
||||
|
||||
// Regex: 12 alfanum + 2 numéricos
|
||||
if (!preg_match('/^[A-Z0-9]{12}[0-9]{2}$/', $cnpj)) {
|
||||
return false;
|
||||
}
|
||||
|
||||
// Converte para valores numéricos
|
||||
$valores = [];
|
||||
for ($i = 0; $i < 14; $i++) {
|
||||
$char = $cnpj[$i];
|
||||
if (ctype_digit($char)) {
|
||||
$valores[$i] = (int)$char;
|
||||
} else {
|
||||
$valores[$i] = ord($char) - 48;
|
||||
}
|
||||
}
|
||||
|
||||
// === Primeiro DV ===
|
||||
$pesos1 = [5,4,3,2,9,8,7,6,5,4,3,2];
|
||||
$soma = 0;
|
||||
for ($i = 0; $i < 12; $i++) {
|
||||
$soma += $valores[$i] * $pesos1[$i];
|
||||
}
|
||||
|
||||
$resto = $soma % 11;
|
||||
$dv1 = ($resto < 2) ? 0 : 11 - $resto;
|
||||
if ($dv1 !== $valores[12]) {
|
||||
return false;
|
||||
}
|
||||
|
||||
// === Segundo DV ===
|
||||
$pesos2 = [6,5,4,3,2,9,8,7,6,5,4,3,2];
|
||||
$soma = 0;
|
||||
for ($i = 0; $i < 13; $i++) {
|
||||
$soma += $valores[$i] * $pesos2[$i];
|
||||
}
|
||||
|
||||
$resto = $soma % 11;
|
||||
$dv2 = ($resto < 2) ? 0 : 11 - $resto;
|
||||
return $dv2 === $valores[13];
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user