Skip to content

Instantly share code, notes, and snippets.

@crecabar
Forked from ronzalo/Entity.php
Created October 4, 2017 18:18
Show Gist options
  • Save crecabar/47c0bb6c87a4e08796a733d995357636 to your computer and use it in GitHub Desktop.
Save crecabar/47c0bb6c87a4e08796a733d995357636 to your computer and use it in GitHub Desktop.
<?php
/*
*
* (c) Gonzalo Moreno C. <goncab380<at>hotmail.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Vendor\YourBundle\Entity;
use Doctrine\ORM\Mapping as ORM;
use Vendor\YourBundle\Validator\Constraints as MyAssert;
use Symfony\Component\Validator\Constraints as Assert;
/**
* Business
*
* @ORM\Table(name="table")
*/
class Entity
{
/**
* @var string
* @ORM\Column(name="rut", type="string", length=10)
* @MyAssert\Rut()
*/
private $rut;
/**
* Set rut
*
* @param string $rut
* @return Entity
*/
public function setRut($rut)
{
$this->rut = $rut;
return $this;
}
/**
* Get rut
*
* @return string
*/
public function getRut()
{
return $this->rut;
}
}
<?php
/*
*
* (c) Gonzalo Moreno C. <[email protected]>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Vendor\YourBundle\Validator\Constraints;
use Symfony\Component\Validator\Constraint;
use Symfony\Component\Validator\Exception\MissingOptionsException;
/**
* @Annotation
*/
class Rut extends Constraint
{
public $message = 'Este valor no es un RUT valido';
public function __construct($options = null)
{
parent::__construct($options);
}
}
<?php
/*
*
* (c) Gonzalo Moreno C. <[email protected]>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Vendor\YourBundle\Validator\Constraints;
use Symfony\Component\Validator\Constraint;
use Symfony\Component\Validator\ConstraintValidator;
class RutValidator extends ConstraintValidator
{
/**
* {@inheritDoc}
*/
public function validate($value, Constraint $constraint)
{
$r = strtoupper(str_replace(array(".", "-"), "", $value));
$sub_rut = substr($r, 0, strlen($r) - 1);
$sub_dv = substr($r, - 1);
$x = 2;
$s = 0;
for ($i = strlen($sub_rut) - 1; $i >= 0; $i--) {
if ($x > 7) {
$x = 2;
}
$s += $sub_rut[$i] * $x;
$x++;
}
$dv = 11 - ($s % 11);
if ($dv == 10) {
$dv = 'K';
}
if ($dv == 11) {
$dv = '0';
}
if ($dv != $sub_dv) {
$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