Completed
Push — master ( 955a0b...b4506e )
by Adelar
02:56
created

Cpf   A

Complexity

Total Complexity 8

Size/Duplication

Total Lines 73
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 0

Test Coverage

Coverage 87.5%

Importance

Changes 5
Bugs 0 Features 0
Metric Value
wmc 8
c 5
b 0
f 0
lcom 1
cbo 0
dl 0
loc 73
ccs 14
cts 16
cp 0.875
rs 10

2 Methods

Rating   Name   Duplication   Size   Complexity  
C isValid() 0 29 7
A getMessages() 0 4 1
1
<?php
2
namespace CpfCnpjValidation;
3
4
use Zend\Validator\ValidatorInterface;
5
6
class Cpf implements ValidatorInterface
7
{
8
9
    private $invalidCpf = [
10
        '00000000000',
11
        '11111111111',
12
        '22222222222',
13
        '33333333333',
14
        '44444444444',
15
        '55555555555',
16
        '66666666666',
17
        '77777777777',
18
        '88888888888',
19
        '99999999999'
20
    ];
21
22
    /**
23
     * Returns true if and only if $value meets the validation requirements
24
     *
25
     * If $value fails validation, then this method returns false, and
26
     * getMessages() will return an array of messages that explain why the
27
     * validation failed.
28
     *
29
     * @param mixed $value            
30
     * @return bool
31
     * @throws Exception\RuntimeException If validation of $value is impossible
32
     */
33 3
    public function isValid($value)
34
    {
35
        if (empty($value)) {
36 3
            return false;
37
        }
38
        
39
        // Elimina possivel mascara
40
        $cpf = preg_replace('/[^0-9]/', '', (string) $value);
41 3
        
42 3
        if (strlen($cpf) > 11) {
43
            return false;
44
        }
45 3
        $cpf = str_pad($cpf, 11, '0', STR_PAD_LEFT);
46
        
47
        if (in_array($cpf, $this->invalidCpf)) {
48
            return false;
49
        }
50 3
        
51 1
        for ($t = 9; $t < 11; $t ++) {
52
            for ($d = 0, $c = 0; $c < $t; $c ++) {
53
                $d += $cpf{$c} * (($t + 1) - $c);
54
            }
55
            $d = ((10 * $d) % 11) % 10;
56 2
            if ($cpf{$c} != $d) {
57 2
                return false;
58 2
            }
59
        }
60 2
        return true;
61 2
    }
62 1
63
    /**
64
     * Returns an array of messages that explain why the most recent isValid()
65 1
     * call returned false.
66
     * The array keys are validation failure message identifiers,
67
     * and the array values are the corresponding human-readable message strings.
68
     *
69
     * If isValid() was never called or if the most recent isValid() call
70
     * returned true, then this method returns an empty array.
71
     *
72
     * @return array
73
     */
74
    public function getMessages()
75
    {
76
        return [];
77
    }
78
}
79