1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
namespace LoginCidadao\ValidationBundle\Validator\Constraints; |
4
|
|
|
|
5
|
|
|
use Symfony\Component\Validator\Constraint; |
6
|
|
|
use Symfony\Component\Validator\ConstraintValidator; |
7
|
|
|
|
8
|
|
|
/** |
9
|
|
|
* @Annotation |
10
|
|
|
*/ |
11
|
|
|
class CPFValidator extends ConstraintValidator |
12
|
|
|
{ |
13
|
|
|
|
14
|
|
|
/** |
15
|
|
|
* @param string $cpf |
16
|
|
|
* @return boolean |
17
|
|
|
*/ |
18
|
|
|
public static function isCPFValid($cpf) |
19
|
|
|
{ |
20
|
|
|
$cpf = preg_replace('/[^0-9]/', '', $cpf); |
21
|
|
|
if (!is_numeric($cpf)) { |
22
|
|
|
return false; |
23
|
|
|
} |
24
|
|
|
|
25
|
|
|
$check1 = 0; |
26
|
|
|
$check2 = 0; |
27
|
|
|
|
28
|
|
|
if (strlen($cpf) != 11 || preg_match('/([0-9])\\1{10}/', $cpf)) { |
29
|
|
|
return false; |
30
|
|
|
} |
31
|
|
|
|
32
|
|
|
for ($i = 0, $x = 10; $i <= 8; $i++, $x--) { |
33
|
|
|
$check1 += $cpf[$i] * $x; |
34
|
|
|
} |
35
|
|
|
for ($i = 0, $x = 11; $i <= 9; $i++, $x--) { |
36
|
|
|
$iStr = "$i"; |
37
|
|
|
if (str_repeat($iStr, 11) == $cpf) { |
38
|
|
|
return false; |
39
|
|
|
} |
40
|
|
|
$check2 += $cpf[$i] * $x; |
41
|
|
|
} |
42
|
|
|
|
43
|
|
|
$calc1 = (($check1 % 11) < 2) ? 0 : 11 - ($check1 % 11); |
44
|
|
|
$calc2 = (($check2 % 11) < 2) ? 0 : 11 - ($check2 % 11); |
45
|
|
|
if ($calc1 != $cpf[9] || $calc2 != $cpf[10]) { |
46
|
|
|
return false; |
47
|
|
|
} |
48
|
|
|
return true; |
49
|
|
|
} |
50
|
|
|
|
51
|
|
|
public static function checkLength($cpf) |
52
|
|
|
{ |
53
|
|
|
$cpf = preg_replace('/[^0-9]/', '', $cpf); |
54
|
|
|
return strlen($cpf) == 11; |
55
|
|
|
} |
56
|
|
|
|
57
|
|
|
public function validate($value, Constraint $constraint) |
58
|
|
|
{ |
59
|
|
|
if (!isset($value) || null === $value || '' === $value) { |
60
|
|
|
return; |
61
|
|
|
} |
62
|
|
|
if (!self::checkLength($value)) { |
63
|
|
|
$this->context->addViolation($constraint->lengthMessage); |
64
|
|
|
} |
65
|
|
|
if (!self::isCPFValid($value)) { |
66
|
|
|
$this->context->addViolation( |
67
|
|
|
$constraint->message, array('%string%' => $value) |
68
|
|
|
); |
69
|
|
|
} |
70
|
|
|
} |
71
|
|
|
|
72
|
|
|
} |
73
|
|
|
|