2011-09-04 00:20:02 +02:00
|
|
|
<?php
|
|
|
|
|
|
|
|
namespace Respect\Validation\Rules;
|
|
|
|
|
|
|
|
use Respect\Validation\Rules\Length;
|
|
|
|
|
2011-09-06 04:34:00 +02:00
|
|
|
class CPF extends AbstractRule
|
|
|
|
{
|
2011-09-04 00:20:02 +02:00
|
|
|
|
2011-09-06 04:34:00 +02:00
|
|
|
public function validate($input)
|
|
|
|
{
|
2011-09-04 00:20:02 +02:00
|
|
|
|
|
|
|
$input = $this->clean($input);
|
|
|
|
|
2011-09-06 04:34:00 +02:00
|
|
|
if ($this->hasInvalidLength($input))
|
2011-09-04 00:20:02 +02:00
|
|
|
return false;
|
|
|
|
|
2011-09-06 04:34:00 +02:00
|
|
|
if ($this->isSequenceOfNumber($input))
|
2011-09-04 00:20:02 +02:00
|
|
|
return false;
|
|
|
|
|
|
|
|
if ($this->processNumber($input))
|
|
|
|
return true;
|
|
|
|
|
|
|
|
return false;
|
|
|
|
}
|
|
|
|
|
|
|
|
private function processNumber($input)
|
|
|
|
{
|
|
|
|
$verify = array('firstDigit' => 0,
|
|
|
|
'secondDigit' => 0,
|
|
|
|
);
|
|
|
|
|
|
|
|
$multiple = 10;
|
|
|
|
|
|
|
|
for ($i = 0; $i < 9; $i++)
|
|
|
|
$verify['firstDigit'] += ($multiple-- * (int) $input[$i]);
|
|
|
|
|
|
|
|
$verify['firstDigit'] = 11 - ($verify['firstDigit'] % 11);
|
|
|
|
|
|
|
|
if ($verify['firstDigit'] >= 10)
|
|
|
|
$verify['firstDigit'] = 0;
|
|
|
|
|
|
|
|
$multiple = 11;
|
|
|
|
|
|
|
|
for ($i = 0; $i < 9; $i++)
|
|
|
|
$verify['secondDigit'] += ($multiple-- * (int) $input[$i]);
|
|
|
|
|
|
|
|
$verify['secondDigit'] += (2 * $verify['firstDigit']);
|
|
|
|
$verify['secondDigit'] = 11 - ($verify['secondDigit'] % 11);
|
|
|
|
|
|
|
|
if ($verify['secondDigit'] >= 10)
|
|
|
|
$verify['secondDigit'] = 0;
|
|
|
|
|
|
|
|
$digits = substr($input, (strlen($input) - 2), 2);
|
|
|
|
|
|
|
|
if (strcmp("{$verify['firstDigit']}{$verify['secondDigit']}", $digits) === 0)
|
|
|
|
return true;
|
|
|
|
|
|
|
|
return false;
|
|
|
|
}
|
|
|
|
|
|
|
|
private function hasInvalidLength($input)
|
|
|
|
{
|
|
|
|
$vl = new Length(11,11);
|
|
|
|
return !$vl->assert($input);
|
|
|
|
}
|
|
|
|
|
|
|
|
private function isSequenceOfNumber($input=null)
|
2011-09-06 04:34:00 +02:00
|
|
|
{
|
2011-09-04 00:20:02 +02:00
|
|
|
for ($i = 0; $i <= 9; $i++)
|
|
|
|
if (strcmp($input, str_pad('', strlen($input), $i)) === 0)
|
|
|
|
return true;
|
|
|
|
|
|
|
|
return false;
|
|
|
|
}
|
|
|
|
|
|
|
|
private function clean($input=null)
|
|
|
|
{
|
|
|
|
return preg_replace("/\.|-/", "", $input);
|
|
|
|
}
|
|
|
|
|
|
|
|
}
|