Skip to content

Commit 7ec6856

Browse files
authored
Merge pull request #37 from MrEko/add-cns-validator
Adicionando validação do Cartão Nacional de Saúde
2 parents 2e19e5e + 72b99d6 commit 7ec6856

File tree

3 files changed

+54
-1
lines changed

3 files changed

+54
-1
lines changed

src/validator-docs/Validator.php

+22
Original file line numberDiff line numberDiff line change
@@ -191,4 +191,26 @@ protected function validateNis($attribute, $value)
191191

192192
return ($nis[10] == (((10 * $d) % 11) % 10));
193193
}
194+
195+
protected function validateCns($attribute, $value)
196+
{
197+
// Remove não numericos
198+
$cns = preg_replace('/[^\d]/', '', $value);
199+
200+
// CNS definitivo começam em 1 ou 2 / CNS provisórios em 7, 8 ou 9
201+
if (preg_match("/[1-2][0-9]{10}00[0-1][0-9]/", $cns) || preg_match("/[7-9][0-9]{14}/", $cns)) {
202+
return $this->somaPonderadaCns($cns) % 11 == 0;
203+
}
204+
return false;
205+
}
206+
207+
private function somaPonderadaCns($value) {
208+
$soma = 0;
209+
210+
for ($i = 0; $i < strlen($value); $i++) {
211+
$soma += $value[$i] * (15 - $i);
212+
}
213+
214+
return $soma;
215+
}
194216
}

src/validator-docs/ValidatorProvider.php

+1
Original file line numberDiff line numberDiff line change
@@ -42,6 +42,7 @@ protected function getMessages()
4242
'cpf' => 'CPF inválido',
4343
'cpf_cnpj' => 'CPF ou CNPJ inválido',
4444
'nis' => 'PIS/PASEP/NIT/NIS inválido',
45+
'cns' => 'Cartão Nacional de Saúde inválido',
4546
'formato_cnpj' => 'Formato inválido para CNPJ',
4647
'formato_cpf' => 'Formato inválido para CPF',
4748
'formato_cpf_cnpj' => 'Formato inválido para CPF ou CNPJ',

tests/TestValidator.php

+31-1
Original file line numberDiff line numberDiff line change
@@ -145,7 +145,7 @@ public function testTituloEleitor()
145145

146146
$this->assertTrue($incorrect->fails());
147147
}
148-
148+
149149
public function testNis()
150150
{
151151
$correct = \Validator::make(
@@ -180,4 +180,34 @@ public function testNisFormato()
180180
$this->assertTrue($incorrect->fails());
181181
}
182182

183+
public function testCns()
184+
{
185+
// Definitiva
186+
$correct = \Validator::make(
187+
['certo' => '116 3876 9194 0009'],
188+
['certo' => 'cns']
189+
);
190+
191+
$incorrect = \Validator::make(
192+
['errado' => '116 5698 9194 0009'],
193+
['errado' => 'cns']
194+
);
195+
196+
$this->assertTrue($correct->passes());
197+
$this->assertTrue($incorrect->fails());
198+
199+
// Provisoria
200+
$correct = \Validator::make(
201+
['certo' => '892 1623 5477 0008'],
202+
['certo' => 'cns']
203+
);
204+
205+
$incorrect = \Validator::make(
206+
['errado' => '892 2641 5477 0008'],
207+
['errado' => 'cns']
208+
);
209+
210+
$this->assertTrue($correct->passes());
211+
$this->assertTrue($incorrect->fails());
212+
}
183213
}

0 commit comments

Comments
 (0)