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 array_map; |
17
|
|
|
use function array_sum; |
18
|
|
|
use function count; |
19
|
|
|
use function is_scalar; |
20
|
|
|
use function preg_replace; |
21
|
|
|
|
22
|
|
|
/** |
23
|
|
|
* Validates if the input is a Brazilian National Registry of Legal Entities (CNPJ) number. |
24
|
|
|
* |
25
|
|
|
* @author Alexandre Gomes Gaigalas <[email protected]> |
26
|
|
|
* @author Henrique Moody <[email protected]> |
27
|
|
|
* @author Jayson Reis <[email protected]> |
28
|
|
|
* @author Nick Lombard <[email protected]> |
29
|
|
|
* @author Renato Moura <[email protected]> |
30
|
|
|
* @author William Espindola <[email protected]> |
31
|
|
|
*/ |
32
|
|
|
final class Cnpj extends AbstractRule |
33
|
|
|
{ |
34
|
|
|
/** |
35
|
|
|
* {@inheritdoc} |
36
|
|
|
*/ |
37
|
33 |
|
public function validate($input): bool |
38
|
|
|
{ |
39
|
33 |
|
if (!is_scalar($input)) { |
40
|
|
|
return false; |
41
|
|
|
} |
42
|
|
|
|
43
|
|
|
// Code ported from jsfromhell.com |
44
|
33 |
|
$bases = [6, 5, 4, 3, 2, 9, 8, 7, 6, 5, 4, 3, 2]; |
45
|
33 |
|
$digits = $this->getDigits((string) $input); |
46
|
|
|
|
47
|
33 |
|
if (array_sum($digits) < 1) { |
48
|
2 |
|
return false; |
49
|
|
|
} |
50
|
|
|
|
51
|
32 |
|
if (14 !== count($digits)) { |
52
|
5 |
|
return false; |
53
|
|
|
} |
54
|
|
|
|
55
|
27 |
|
$n = 0; |
56
|
27 |
|
for ($i = 0; $i < 12; ++$i) { |
57
|
27 |
|
$n += $digits[$i] * $bases[$i+1]; |
58
|
|
|
} |
59
|
|
|
|
60
|
27 |
|
if ($digits[12] != ((($n %= 11) < 2) ? 0 : 11 - $n)) { |
61
|
14 |
|
return false; |
62
|
|
|
} |
63
|
|
|
|
64
|
13 |
|
$n = 0; |
65
|
13 |
|
for ($i = 0; $i <= 12; ++$i) { |
66
|
13 |
|
$n += $digits[$i] * $bases[$i]; |
67
|
|
|
} |
68
|
|
|
|
69
|
13 |
|
if ($digits[13] != ((($n %= 11) < 2) ? 0 : 11 - $n)) { |
70
|
1 |
|
return false; |
71
|
|
|
} |
72
|
|
|
|
73
|
12 |
|
return true; |
74
|
|
|
} |
75
|
|
|
|
76
|
|
|
/** |
77
|
|
|
* @return int[] |
78
|
|
|
*/ |
79
|
33 |
|
private function getDigits(string $input): array |
80
|
|
|
{ |
81
|
33 |
|
return array_map( |
82
|
33 |
|
'intval', |
83
|
33 |
|
str_split( |
84
|
33 |
|
preg_replace('/\D/', '', $input) |
85
|
|
|
) |
86
|
|
|
); |
87
|
|
|
} |
88
|
|
|
} |
89
|
|
|
|