Skip to content

Commit 884e8a7

Browse files
committed
feat: Add Support for Alphanumeric CNPJ
Adds validation and tests for new CNPJ registrations, which will accept alphanumeric characters starting from July 2026. The change was instituted through "Instrução Normativa RFB nº 2.119/2022."
1 parent d8e31db commit 884e8a7

2 files changed

Lines changed: 21 additions & 4 deletions

File tree

src/Validators/Cnpj.php

Lines changed: 16 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -34,6 +34,8 @@
3434
)]
3535
final class Cnpj extends Simple
3636
{
37+
private const int BASE_ASCII = 48;
38+
3739
public function isValid(mixed $input): bool
3840
{
3941
if (!is_scalar($input)) {
@@ -42,7 +44,8 @@ public function isValid(mixed $input): bool
4244

4345
// Code ported from jsfromhell.com
4446
$bases = [6, 5, 4, 3, 2, 9, 8, 7, 6, 5, 4, 3, 2];
45-
$digits = $this->getDigits((string) $input);
47+
$chars = $this->getChars((string) $input);
48+
$digits = $this->transformToAscii($chars);
4649

4750
if (array_sum($digits) < 1) {
4851
return false;
@@ -72,13 +75,22 @@ public function isValid(mixed $input): bool
7275
}
7376

7477
/** @return int[] */
75-
private function getDigits(string $input): array
78+
private function getChars(string $input): array
7679
{
7780
return array_map(
78-
'intval',
81+
'strtoupper',
7982
str_split(
80-
(string) preg_replace('/\D/', '', $input),
83+
(string) preg_replace('/[\W_]/', '', $input),
8184
),
8285
);
8386
}
87+
88+
/** @return int[] */
89+
private function transformToAscii(array $input): array
90+
{
91+
return array_map(
92+
fn (string $character) => ord($character) - self::BASE_ASCII,
93+
$input
94+
);
95+
}
8496
}

tests/unit/Validators/CnpjTest.php

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -39,11 +39,14 @@ public static function providerForValidInput(): iterable
3939
[$validator, '24.760.428/0001-09'],
4040
[$validator, '27.355.204/0001-00'],
4141
[$validator, '36.310.327/0001-07'],
42+
[$validator, '12.ABC.345/01DE-35'],
43+
[$validator, '12.ABC.345/01DE_35'],
4244
[$validator, '38175021000110'],
4345
[$validator, '37550610000179'],
4446
[$validator, '12774546000189'],
4547
[$validator, '77456211000168'],
4648
[$validator, '02023077000102'],
49+
[$validator, '12ABC34501DE35'],
4750
];
4851
}
4952

@@ -75,6 +78,8 @@ public static function providerForInvalidInput(): iterable
7578
[$validator, '992999999999929384'],
7679
[$validator, '99-010-0.'],
7780
[$validator, null],
81+
[$validator, '12ABC34501DE00'],
82+
[$validator, '12ABC34501DEFG'],
7883
];
7984
}
8085
}

0 commit comments

Comments
 (0)