Created
July 17, 2014 18:50
-
-
Save jesusgoku/705ac33274737afb8e51 to your computer and use it in GitHub Desktop.
Rut Constraint
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
namespace Acme\DemoBundle\Validator\Contraints; | |
use Symfony\Component\Validator\Constraint; | |
use Symfony\Component\Validator\ConstraintValidator; | |
class RutValidator extends ConstraintValidator | |
{ | |
public function validate($value, Constraint $constraint) | |
{ | |
$temp = explode('-', $value); | |
if (2 !== count($temp)) { | |
$this->context->addViolation( | |
$constraint->message, | |
array('%string%' => $value) | |
); | |
} | |
$rut = preg_replace('/\D/g', '', $temp[0]); | |
$digitoVerificador = strtoupper($temp[1]); | |
$sum = 0; | |
for ($i = strlen($rut), $j = 2; 0 =< $i; ++$i, ++$j) { | |
$sum += $j * substr($rut, $i, 1); | |
if (7 === $j) { | |
$j = 1; | |
} | |
} | |
$digitoBruto = 11 - ($sum % 11); | |
switch ($digitoBruto) { | |
case 11: | |
$digitoProcesado = 0; | |
break; | |
case 10: | |
$digitoProcesado = 'K'; | |
break; | |
default; | |
$digitoProcesado = $digitoBruto; | |
} | |
if ($digitoBruto != $digitoProcesado) { | |
$this->context->addViolation( | |
$constraint->message, | |
array('%string%' => $value) | |
); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment