|
1
|
|
|
<?php |
|
2
|
|
|
declare(strict_types=1); |
|
3
|
|
|
|
|
4
|
|
|
namespace BrenoRoosevelt\Validation\Rules\Brazilian; |
|
5
|
|
|
|
|
6
|
|
|
use BrenoRoosevelt\Validation\AbstractValidation; |
|
7
|
|
|
|
|
8
|
|
|
abstract class DigitoVerificador extends AbstractValidation |
|
9
|
|
|
{ |
|
10
|
|
|
public function __construct(?string $message = 'Dígito verificador inválido') |
|
11
|
|
|
{ |
|
12
|
|
|
parent::__construct($message); |
|
13
|
|
|
} |
|
14
|
|
|
|
|
15
|
|
|
public function evaluate($input, array $context = []): bool |
|
16
|
|
|
{ |
|
17
|
|
|
$numbers = preg_replace('/\D/', '', (string) $input); |
|
18
|
|
|
$number = substr($numbers, 0, -1); |
|
19
|
|
|
$digit = (int) substr($numbers, -1); |
|
20
|
|
|
return $digit === $this->getDigit($number); |
|
21
|
|
|
} |
|
22
|
|
|
|
|
23
|
|
|
public static function mod11($input): int |
|
24
|
|
|
{ |
|
25
|
|
|
$numbers = array_reverse(str_split((string) $input)); |
|
|
|
|
|
|
26
|
|
|
$factor = [2, 3, 4, 5, 6, 7, 8, 9]; |
|
27
|
|
|
$size = count($factor); |
|
28
|
|
|
$i = $sum = 0; |
|
29
|
|
|
foreach ($numbers as $number) { |
|
30
|
|
|
$sum += $number * $factor[$i++ % $size]; |
|
31
|
|
|
} |
|
32
|
|
|
|
|
33
|
|
|
return 11 - (($sum * 10 ) % 11); |
|
34
|
|
|
} |
|
35
|
|
|
|
|
36
|
|
|
public static function mod10($input): int |
|
37
|
|
|
{ |
|
38
|
|
|
$numbers = array_reverse(str_split((string) $input)); |
|
|
|
|
|
|
39
|
|
|
$factor = [2, 1]; |
|
40
|
|
|
$size = count($factor); |
|
41
|
|
|
$i = $sum = 0; |
|
42
|
|
|
foreach ($numbers as $number) { |
|
43
|
|
|
$num = $number * $factor[$i++ % $size]; |
|
44
|
|
|
$sum += array_sum(str_split((string) $num)); |
|
|
|
|
|
|
45
|
|
|
} |
|
46
|
|
|
|
|
47
|
|
|
return 10 - ($sum % 10); |
|
48
|
|
|
} |
|
49
|
|
|
|
|
50
|
|
|
public static function checkCpfCnpjDigits(string $document): bool |
|
51
|
|
|
{ |
|
52
|
|
|
$document = preg_replace('/\D/', '', $document); |
|
53
|
|
|
$number = substr($document, 0, -2); |
|
54
|
|
|
$digits = substr($document, -2); |
|
55
|
|
|
|
|
56
|
|
|
$digit1 = DigitoVerificador::mod11($number); |
|
57
|
|
|
$digit2 = DigitoVerificador::mod11($number . $digit1); |
|
58
|
|
|
|
|
59
|
|
|
return $digits === ($digit1 . $digit2); |
|
60
|
|
|
} |
|
61
|
|
|
|
|
62
|
|
|
abstract protected function getDigit($number): int; |
|
63
|
|
|
} |
|
64
|
|
|
|