/
CgcAbstract.php
109 lines (95 loc) · 2.82 KB
/
CgcAbstract.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
<?php
namespace JS\Validator;
use Zend\Validator\AbstractValidator;
/**
* Classe CgcAbstract para validar tanto cpf quanto cnpj.
* Existem no pacote as classes Cpf e Cnpj que a extendem.
*/
abstract class CgcAbstract extends AbstractValidator {
/**
* Tamanho Inválido
* @var string
*/
const SIZE = 'size';
/**
* Números Expandidos
* @var string
*/
const EXPANDED = 'expanded';
/**
* Dígito Verificador
* @var string
*/
const DIGIT = 'digit';
/**
* Tamanho do Campo
* @var int
*/
protected $size = 0;
/**
* Modelos de Mensagens
* @var string
*/
protected $messageTemplates = [
self::SIZE => "'%value%' não possui tamanho esperado.",
self::EXPANDED => "'%value%' não possui um formato aceitável.",
self::DIGIT => "'%value%' não é um documento válido."
];
/**
* Modificadores de Dígitos
* @var array
*/
protected $modifiers = array();
protected $validIfEmpty = true;
public function __construct($options = null) {
parent::__construct($options);
if (array_key_exists('valid_if_empty', $options))
$this->validIfEmpty = $options['valid_if_empty'];
}
/**
* Validação Interna do Documento
* @param string $value Dados para Validação
* @return boolean Confirmação de Documento Válido
*/
protected function check($value) {
// Captura dos Modificadores
foreach ($this->modifiers as $modifier) {
$result = 0; // Resultado Inicial
$size = count($modifier); // Tamanho dos Modificadores
for ($i = 0; $i < $size; $i++) {
$result += $value[$i] * $modifier[$i]; // Somatório
}
$result = $result % 11;
$digit = ($result < 2 ? 0 : 11 - $result); // Dígito
// Verificação
if ($value[$size] != $digit) {
return false;
}
}
return true;
}
public function isValid($value) {
if (!$this->validIfEmpty && empty($value)) {
return true;
}
// Filtro de Dados
$data = preg_replace('/[^0-9]/', '', $value);
// Verificação de Tamanho
if (strlen($data) != $this->size) {
$this->error(self::SIZE, $value);
return false;
}
// Verificação de Dígitos Expandidos
if (str_repeat($data[0], $this->size) == $data) {
$this->error(self::EXPANDED, $value);
return false;
}
// Verificação de Dígitos
if (!$this->check($data)) {
$this->error(self::DIGIT, $value);
return false;
}
// Comparações Concluídas
return true; // Todas Verificações Executadas
}
}