Skip to content

Instantly share code, notes, and snippets.

@agiuliano
Created April 10, 2014 09:30
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save agiuliano/10361445 to your computer and use it in GitHub Desktop.
Save agiuliano/10361445 to your computer and use it in GitHub Desktop.
<?php
/**
* ConstraintFiscalCodeValidator.php.
* @author Andrea Giuliano <giulianoand@gmail.com>
* Date: 20/07/12
* Time: 16:19
*/
namespace Dnsee\RegistrationBundle\Validator\Constraints;
use Symfony\Component\Validator\Constraint;
use Symfony\Component\Validator\ConstraintValidator;
use Dnsee\RegistrationBundle\Entity\User;
class ConstraintFiscalCodeSyntaxValidator extends ConstraintValidator
{
const REGEX_CF = '/^([A-Z]{6}[0-9LMNPQRSTUV]{2}[ABCDEHLMPRST]{1}[0-9LMNPQRSTUV]{2}[A-Za-z]{1}[0-9LMNPQRSTUV]{3}[A-Za-z]{1})$/i';
/**
* @param $user
* @param Symfony\Component\Validator\Constraint $constraint
*/
public function isValid($fiscalCode, Constraint $constraint)
{
$fiscalCode = strtoupper(str_replace(" ", "", $fiscalCode));
if ( !$this->checkSyntax($fiscalCode) ||
!$this->checkDigit($fiscalCode)
)
{
$this->context->addViolationAtSubPath('fiscal_code', $constraint->message);
}
}
protected function checkSyntax($value)
{
return preg_match(self::REGEX_CF, $value);
}
protected function checkDigit($cf)
{
$check = true;
$s = 0;
for ($i = 1; $i <= 13; $i += 2)
{
$c = $cf[$i];
if ('0' <= $c && $c <= '9')
$s += ord($c) - ord('0');
else
$s += ord($c) - ord('A');
}
for ($i = 0; $i <= 14; $i += 2)
{
$c = $cf[$i];
switch ($c)
{
case '0': $s += 1;
break;
case '1': $s += 0;
break;
case '2': $s += 5;
break;
case '3': $s += 7;
break;
case '4': $s += 9;
break;
case '5': $s += 13;
break;
case '6': $s += 15;
break;
case '7': $s += 17;
break;
case '8': $s += 19;
break;
case '9': $s += 21;
break;
case 'A': $s += 1;
break;
case 'B': $s += 0;
break;
case 'C': $s += 5;
break;
case 'D': $s += 7;
break;
case 'E': $s += 9;
break;
case 'F': $s += 13;
break;
case 'G': $s += 15;
break;
case 'H': $s += 17;
break;
case 'I': $s += 19;
break;
case 'J': $s += 21;
break;
case 'K': $s += 2;
break;
case 'L': $s += 4;
break;
case 'M': $s += 18;
break;
case 'N': $s += 20;
break;
case 'O': $s += 11;
break;
case 'P': $s += 3;
break;
case 'Q': $s += 6;
break;
case 'R': $s += 8;
break;
case 'S': $s += 12;
break;
case 'T': $s += 14;
break;
case 'U': $s += 16;
break;
case 'V': $s += 10;
break;
case 'W': $s += 22;
break;
case 'X': $s += 25;
break;
case 'Y': $s += 24;
break;
case 'Z': $s += 23;
break;
}
}
if (chr($s % 26 + ord('A')) != $cf[15])
{
$check = false;
}
return $check;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment