Created
April 30, 2025 18:20
-
-
Save EduardoSP6/3e1c04ed689247c7fe2e7193e82ed2c3 to your computer and use it in GitHub Desktop.
CNPJ Validator PHP
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
namespace App\Domain\Shared\Validators; | |
class CnpjValidator | |
{ | |
public static function execute(string $cnpj): bool | |
{ | |
$cnpj = str_pad($cnpj, 14, '0', STR_PAD_LEFT); | |
if (strlen($cnpj) != 14) { | |
return false; | |
} | |
// check if all digits are the same like: 11111111111111 | |
if (preg_match('/(\d)\1{13}/', $cnpj)) | |
return false; | |
// check the first verification digit | |
/** | |
* @var int $i | |
* @var int $j | |
* @var int $sum | |
* @var int $sum2 | |
* @var float $rest | |
*/ | |
for ($i = 0, $j = 5, $sum = 0; $i < 12; $i++) { | |
$sum += ((int)$cnpj[$i] * $j); | |
$j = ($j == 2) ? 9 : $j - 1; | |
} | |
$rest = $sum % 11; | |
if ($cnpj[12] != ($rest < 2 ? 0 : 11 - $rest)) | |
return false; | |
// check the second verification digit | |
for ($i = 0, $j = 6, $sum2 = 0; $i < 13; $i++) { | |
$sum2 += ((int)$cnpj[$i] * $j); | |
$j = ($j == 2) ? 9 : ($j - 1); | |
} | |
$rest = $sum2 % 11; | |
return $cnpj[13] == ($rest < 2 ? 0 : 11 - $rest); | |
} | |
} | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment