CPFValidator::isCPFValid()   B
last analyzed

Complexity

Conditions 11
Paths 36

Size

Total Lines 31
Code Lines 19

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 132

Importance

Changes 0
Metric Value
cc 11
eloc 19
nc 36
nop 1
dl 0
loc 31
ccs 0
cts 27
cp 0
crap 132
rs 7.3166
c 0
b 0
f 0

How to fix   Complexity   

Long Method

Small methods make your code easier to understand, in particular if combined with a good name. Besides, if your method is small, finding a good name is usually much easier.

For example, if you find yourself adding comments to a method's body, this is usually a good sign to extract the commented part to a new method, and use the comment as a starting point when coming up with a good name for this new method.

Commonly applied refactorings include:

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