|
1
|
|
|
<?php |
|
2
|
|
|
|
|
3
|
|
|
/* |
|
4
|
|
|
* This file is part of Respect/Validation. |
|
5
|
|
|
* |
|
6
|
|
|
* (c) Alexandre Gomes Gaigalas <[email protected]> |
|
7
|
|
|
* |
|
8
|
|
|
* For the full copyright and license information, please view the "LICENSE.md" |
|
9
|
|
|
* file that was distributed with this source code. |
|
10
|
|
|
*/ |
|
11
|
|
|
|
|
12
|
|
|
declare(strict_types=1); |
|
13
|
|
|
|
|
14
|
|
|
namespace Respect\Validation\Rules; |
|
15
|
|
|
|
|
16
|
|
|
use function is_scalar; |
|
17
|
|
|
use function mb_strlen; |
|
18
|
|
|
use function preg_replace; |
|
19
|
|
|
|
|
20
|
|
|
/** |
|
21
|
|
|
* Validates if the input is a Brazilian National Registry of Legal Entities (CNPJ) number. |
|
22
|
|
|
* |
|
23
|
|
|
* @author Alexandre Gaigalas <[email protected]> |
|
24
|
|
|
* @author Henrique Moody <[email protected]> |
|
25
|
|
|
* @author Jayson Reis <[email protected]> |
|
26
|
|
|
* @author Renato Moura <[email protected]> |
|
27
|
|
|
* @author Nick Lombard <[email protected]> |
|
28
|
|
|
* @author William Espindola <[email protected]> |
|
29
|
|
|
*/ |
|
30
|
|
|
final class Cnpj extends AbstractRule |
|
31
|
|
|
{ |
|
32
|
|
|
/** |
|
33
|
|
|
* {@inheritdoc} |
|
34
|
|
|
*/ |
|
35
|
33 |
|
public function isValid($input): bool |
|
36
|
|
|
{ |
|
37
|
33 |
|
if (!is_scalar($input)) { |
|
38
|
|
|
return false; |
|
39
|
|
|
} |
|
40
|
|
|
|
|
41
|
|
|
// Code ported from jsfromhell.com |
|
42
|
33 |
|
$cleanInput = preg_replace('/\D/', '', $input); |
|
43
|
33 |
|
$b = [6, 5, 4, 3, 2, 9, 8, 7, 6, 5, 4, 3, 2]; |
|
44
|
|
|
|
|
45
|
33 |
|
if ($cleanInput < 1) { |
|
46
|
2 |
|
return false; |
|
47
|
|
|
} |
|
48
|
|
|
|
|
49
|
32 |
|
if (14 != mb_strlen($cleanInput)) { |
|
50
|
5 |
|
return false; |
|
51
|
|
|
} |
|
52
|
|
|
|
|
53
|
27 |
|
for ($i = 0, $n = 0; $i < 12; $n += $cleanInput[$i] * $b[++$i]); |
|
54
|
|
|
|
|
55
|
27 |
|
if ($cleanInput[12] != ((($n %= 11) < 2) ? 0 : 11 - $n)) { |
|
56
|
14 |
|
return false; |
|
57
|
|
|
} |
|
58
|
|
|
|
|
59
|
13 |
|
for ($i = 0, $n = 0; $i <= 12; $n += $cleanInput[$i] * $b[$i++]); |
|
60
|
|
|
|
|
61
|
13 |
|
if ($cleanInput[13] != ((($n %= 11) < 2) ? 0 : 11 - $n)) { |
|
62
|
1 |
|
return false; |
|
63
|
|
|
} |
|
64
|
|
|
|
|
65
|
12 |
|
return true; |
|
66
|
|
|
} |
|
67
|
|
|
} |
|
68
|
|
|
|