Simplified the CpfValidator

I just simplified the code to it be smaller, more faster and more readable
This commit is contained in:
Carlos André Ferrari 2011-09-25 09:05:58 -03:00
parent fac8662f3a
commit 28821672c9

View file

@ -7,60 +7,44 @@ class Cpf extends AbstractRule
public function validate($input)
{
$input = preg_replace('([^0-9])', '', $input);
$input = preg_replace('[^0-9]', '', $input);
if (strlen($input) != 11)
return false;
if ($this->isSequenceOfNumber($input))
return false;
if ($this->processNumber($input))
return true;
return false;
return $this->processNumber($input);
}
private function processNumber($input)
{
$verify = array('firstDigit' => 0, 'secondDigit' => 0);
$multiple = 10;
$firstDigit = $secondDigit = 0;
for ($i = 0; $i < 9; $i++)
$verify['firstDigit'] += ($multiple-- * (int) $input[$i]);
$firstDigit += ($multiple-- * (int) $input[$i]);
$verify['firstDigit'] = 11 - ($verify['firstDigit'] % 11);
if ($verify['firstDigit'] >= 10)
$verify['firstDigit'] = 0;
$firstDigit = 11 - ($firstDigit % 11);
$firstDigit >= 10 && $firstDigit = 0;
$multiple = 11;
for ($i = 0; $i < 9; $i++)
$verify['secondDigit'] += ($multiple-- * (int) $input[$i]);
$secondDigit += ($multiple-- * (int) $input[$i]);
$verify['secondDigit'] += (2 * $verify['firstDigit']);
$verify['secondDigit'] = 11 - ($verify['secondDigit'] % 11);
$secondDigit += (2 * $firstDigit);
$secondDigit = 11 - ($secondDigit % 11);
if ($verify['secondDigit'] >= 10)
$verify['secondDigit'] = 0;
$secondDigit >= 10 && $secondDigit = 0;
$digits = substr($input, -2);
$digits = substr($input, (strlen($input) - 2), 2);
if (strcmp("{$verify['firstDigit']}{$verify['secondDigit']}", $digits) === 0)
return true;
return false;
return ("{$firstDigit}{$secondDigit}" === $digits);
}
private function isSequenceOfNumber($input)
{
for ($i = 0; $i <= 9; $i++)
if (strcmp($input, str_pad('', strlen($input), $i)) === 0)
if ($input === str_repeat($i, 11))
return true;
return false;
}