Skip to content

Instantly share code, notes, and snippets.

@jesusgoku
Created July 17, 2014 18:50
Show Gist options
  • Save jesusgoku/705ac33274737afb8e51 to your computer and use it in GitHub Desktop.
Save jesusgoku/705ac33274737afb8e51 to your computer and use it in GitHub Desktop.
Rut Constraint
<?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