Files
Antonio Lopes dos Santos afec302c3e
All checks were successful
build-api-image / build (push) Successful in 51s
init commit
2026-08-04 16:52:02 -03:00

88 lines
1.8 KiB
PHP

<?php
namespace App\Rules;
use Illuminate\Contracts\Validation\Rule;
class Cns implements Rule
{
/**
* Determine if the validation rule passes.
*
* @param string $attribute
* @param mixed $value
* @return bool
*/
public function passes($attribute, $value)
{
return self::isValid($value);
}
public static function isValid($value)
{
$cns = preg_replace('/[^0-9]/', '', $value);
if ((strlen(trim($cns))) != 15)
return false;
$acao = substr($cns, 0, 1);
switch ($acao)
{
case '1':
case '2': $ret = self::validaCNS($cns); break;
case '5':
case '7':
case '8':
case '9': $ret = self::validaCNS_PROVISORIO($cns); break;
default: $ret = false;
}
return $ret;
}
private static function validaCNS($cns)
{
$pis = substr($cns,0,11);
$soma = 0;
for ( $i = 0, $j = strlen($pis), $k = 15; $i < $j; $i++, $k-- )
{
$soma += $pis[$i] * $k;
}
$dv = 11 - fmod($soma, 11);
$dv = ($dv != 11) ? $dv : '0';
if ( $dv == 10 )
{
$soma += 2;
$dv = 11 - fmod($soma, 11);
$resultado = $pis.'001'.$dv;
}
else
{
$resultado = $pis.'000'.$dv;
}
return $cns == $resultado;
}
private static function validaCNS_PROVISORIO($cns)
{
$soma = 0;
for ( $i = 0, $j = strlen($cns), $k = $j; $i < $j; $i++, $k-- )
{
$soma += $cns[$i] * $k;
}
return $soma % 11 == 0 && $j == 15;
}
/**
* Get the validation error message.
*
* @return string
*/
public function message()
{
return 'CNS Inválido.';
}
}