Initial release
This commit is contained in:
1
.gitignore
vendored
1
.gitignore
vendored
@@ -1,3 +1,4 @@
|
||||
vendor
|
||||
composer.lock
|
||||
.idea
|
||||
.php_cs.cache
|
||||
32
.php_cs.dist
Normal file
32
.php_cs.dist
Normal file
@@ -0,0 +1,32 @@
|
||||
<?php
|
||||
|
||||
$header = <<<EOF
|
||||
This file is part of the MNC\ChileanRut library.
|
||||
|
||||
(c) Matías Navarro Carter <mnavarrocarter@gmail.com>
|
||||
For the full copyright and license information, please view the LICENSE
|
||||
file that was distributed with this source code.
|
||||
EOF;
|
||||
|
||||
return PhpCsFixer\Config::create()
|
||||
->setRules([
|
||||
'@Symfony' => true,
|
||||
'array_syntax' => ['syntax' => 'short'],
|
||||
'combine_consecutive_unsets' => true,
|
||||
'header_comment' => ['header' => $header],
|
||||
'linebreak_after_opening_tag' => true,
|
||||
'no_php4_constructor' => true,
|
||||
'no_useless_else' => true,
|
||||
'ordered_class_elements' => true,
|
||||
'ordered_imports' => true,
|
||||
'php_unit_construct' => true,
|
||||
'php_unit_strict' => true,
|
||||
'phpdoc_no_empty_return' => false,
|
||||
])
|
||||
->setUsingCache(true)
|
||||
->setRiskyAllowed(true)
|
||||
->setFinder(
|
||||
PhpCsFixer\Finder::create()
|
||||
->in(__DIR__)
|
||||
)
|
||||
;
|
||||
19
LICENSE
Normal file
19
LICENSE
Normal file
@@ -0,0 +1,19 @@
|
||||
Copyright (c) 2018 Matías Navarro Carter
|
||||
|
||||
Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
of this software and associated documentation files (the "Software"), to deal
|
||||
in the Software without restriction, including without limitation the rights
|
||||
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||
copies of the Software, and to permit persons to whom the Software is furnished
|
||||
to do so, subject to the following conditions:
|
||||
|
||||
The above copyright notice and this permission notice shall be included in all
|
||||
copies or substantial portions of the Software.
|
||||
|
||||
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
|
||||
THE SOFTWARE.
|
||||
169
README.md
169
README.md
@@ -9,7 +9,172 @@ y un *type* para `doctrine/dbal`.
|
||||
|
||||
Sólo es compatible con PHP 7.1 o superior.
|
||||
|
||||
## ¿Cómo nació y por qué esta librería?
|
||||
## Uso
|
||||
Simplemente instancia una nueva clase con un rut en cualquier formato:
|
||||
|
||||
```php
|
||||
<?php
|
||||
|
||||
use MNC\ChileanRut\Rut;
|
||||
|
||||
$rut = new Rut('23.546.565-4');
|
||||
|
||||
// Si prefieres, puedes usar el factory method
|
||||
|
||||
$rut = Rut::fromString('23546565-4');
|
||||
```
|
||||
|
||||
Por defecto, la clase Rut no se valida a sí misma, lo que puede significar que
|
||||
el objeto sea instanciado en un estado inconsistente. Si esto no te gusta, puedes pasarle
|
||||
el `SimpleRutValidator` al constructor, y el Rut será validado al momento de ser instanciado.
|
||||
|
||||
```php
|
||||
<?php
|
||||
|
||||
use MNC\ChileanRut\Rut;
|
||||
use MNC\ChileanRut\Validator\SimpleRutValidator;
|
||||
|
||||
$rut = new Rut('23.546.565-4', new SimpleRutValidator());
|
||||
|
||||
// Esto lanzará un InvalidRutException si el rut no es valido.
|
||||
```
|
||||
|
||||
### Validación Personalizada de Rut
|
||||
El `SimpleRutValidator` no es más que la implementación del validador clásico de Rut,
|
||||
el algoritmo de módulo 11. Esto verifica que un Rut es algoritmicamente correcto, pero
|
||||
no valida que es real.
|
||||
|
||||
Por ello, proveemos la interfaz `RutValidator`. Con ella, puedes crear tus propias
|
||||
reglas de validación, como llamar a un web service o consultar una base de datos
|
||||
para verificar si un Rut es real o no. Te recomiendo mirar la interfaz para
|
||||
implementarla correctamente.
|
||||
|
||||
De todas formas, aquí hay un ejemplo que va a buscar un rut a un web service.
|
||||
|
||||
```php
|
||||
<?php
|
||||
|
||||
use MNC\ChileanRut\Validator\RutValidator;
|
||||
use MNC\ChileanRut\Rut;
|
||||
use MNC\ChileanRut\Exception\InvalidRutException;
|
||||
use App\Rut\WebServiceRutChecker;
|
||||
|
||||
class MyCustomRutValidator implements RutValidator
|
||||
{
|
||||
private $rutChecker;
|
||||
|
||||
/**
|
||||
* MyCustomRutValidator constructor.
|
||||
* @param WebServiceRutChecker $rutChecker
|
||||
*/
|
||||
public function __construct(WebServiceRutChecker $rutChecker)
|
||||
{
|
||||
$this->rutChecker = $rutChecker;
|
||||
}
|
||||
|
||||
/**
|
||||
* @param Rut $rut
|
||||
*/
|
||||
public function validate(Rut $rut) : void
|
||||
{
|
||||
// Por debajo, esta clase ficticia haría una llamada a un web service preguntando
|
||||
// si el Rut existe.
|
||||
if ($this->rutChecker->doesRutExist($rut->format())) {
|
||||
return;
|
||||
}
|
||||
throw new InvalidRutException($rut, 'This rut does not exist');
|
||||
}
|
||||
}
|
||||
|
||||
```
|
||||
|
||||
> NOTA: La implementación de cualquier validador DEBE arrojar un InvalidRutException cuando
|
||||
el Rut no es válido. De lo contrario, el Rut se toma como válido.
|
||||
|
||||
### Usando múltiples validadores
|
||||
Proveemos un `ChainRutValidator` que puedes usar para validar un rut contra múltiples
|
||||
validadores. Esto permite ejecutar cadenas de validación, como ver primero si un rut es
|
||||
válido algorítmicamente antes de verificarlo contra un web service.
|
||||
|
||||
Usarlo es simple:
|
||||
|
||||
```php
|
||||
<?php
|
||||
|
||||
use MNC\ChileanRut\Rut;
|
||||
use MNC\ChileanRut\Validator\ChainRutValidator;
|
||||
use MNC\ChileanRut\Validator\SimpleRutValidator;
|
||||
use App\Rut\DatabaseRutValidator;
|
||||
|
||||
$chainValidator = new ChainRutValidator();
|
||||
$chainValidator
|
||||
->append(new SimpleRutValidator())
|
||||
->append(new DatabaseRutValidator());
|
||||
|
||||
$rut = new Rut('14.245.245-2');
|
||||
|
||||
$chainValidator->validate($rut);
|
||||
```
|
||||
|
||||
### Formateando Ruts a String
|
||||
|
||||
Una vez creado el objeto Rut, puedes formatearlo a string en el formato que tu quieras.
|
||||
Esto se hace a través del método format y cómo parámetro acepta el valor
|
||||
de una de las constantes FORMAT_ de la clase Rut.
|
||||
|
||||
```php
|
||||
<?php
|
||||
|
||||
use MNC\ChileanRut\Rut;
|
||||
|
||||
$rut = new Rut('34244223-4');
|
||||
|
||||
echo $rut->format(Rut::FORMAT_CLEAR); // Va a imprimir 342442234
|
||||
echo $rut->format(Rut::FORMAT_READABLE); // Va a imprimir 34.244.223-4
|
||||
echo $rut->format(Rut::FORMAT_HYPHENED); // Va a imprimir 34244223-4
|
||||
echo $rut->format(Rut::FORMAT_HIDDEN); // Va a imprimir 34.***.***-4
|
||||
```
|
||||
|
||||
### Utilidades
|
||||
Esta librería provee una clase llamada `CorrelativeUtils` que tiene algunas utilidades
|
||||
interesantes. Posee tres métodos:
|
||||
|
||||
```php
|
||||
<?php
|
||||
|
||||
use MNC\ChileanRut\Util\CorrelativeUtils;
|
||||
|
||||
// Este método devuelve el digito verificador de un correlativo.
|
||||
CorrelativeUtils::findVerifierDigit('34525252');
|
||||
|
||||
// Este método devuelve una instancia de Rut válida, sólo con el correlativo.
|
||||
CorrelativeUtils::createValidRutOnlyFromCorrelative('34525252');
|
||||
|
||||
// Este método devuelve instancia de Rut autogenerada algoritmicamente válida.
|
||||
CorrelativeUtils::autoGenerateValidRut();
|
||||
```
|
||||
|
||||
## Integraciones con Liberías de Terceros
|
||||
|
||||
### Doctrine DBAL
|
||||
Esta libería provee un custom type para doctrine llamado `RutType`. Puedes registrarla
|
||||
en el Dbal para usarla en tus mappings de doctrine y automáticamente mappear tu
|
||||
el valor de tu db a un objeto rut.
|
||||
|
||||
### Symfony Validator
|
||||
Además, esta libería cuenta con un validador para Symfony Validator, que te
|
||||
permite beneficiarte de las anotaciones del componente de validación de Symfony.
|
||||
Como dependencia opcional necesita una instancia de `RutValidator`. Si ninguna es proveída,
|
||||
se utiliza el `SimpleRutValidator`. Solo puedes usar el validador contra una instancia de `Rut`.
|
||||
|
||||
### Symfony Form Type
|
||||
Por último, esta libería cuenta con un Symfony Form Type que puedes añadir en tus
|
||||
formularios HTML, para que puedas autoinstanciar la clase y poner lógica de
|
||||
validación en ella sin problema, y añadirla a tus otros tipos.
|
||||
|
||||
## FAQ
|
||||
|
||||
### ¿Cómo nació y por qué esta librería?
|
||||
Esta libería nace de la necesidad de estandarizar una clase Rut común para todos mis proyectos
|
||||
PHP.
|
||||
Si bien es cierto, hay muchas liberías con implementaciones de Rut chilenos en PHP,
|
||||
@@ -22,7 +187,7 @@ solo a ser algorítmica.
|
||||
4. Están acopladas a un framework
|
||||
5. No proveen herramientas ni integraciones con librerías de terceros.
|
||||
|
||||
## ¿Por qué PHP 7.1?
|
||||
### ¿Por qué PHP 7.1?
|
||||
El fin del soporte de PHP 5.6 será a fines de 2018. PHP 7.1 es una de las últimas
|
||||
versiones estables, y me beneficio mucho de su sistema de tipado estricto en esta libería.
|
||||
|
||||
|
||||
@@ -18,7 +18,8 @@
|
||||
"phpunit/phpunit": "^7.3",
|
||||
"doctrine/dbal": "^2.5",
|
||||
"symfony/form": "^3.4|^4.0",
|
||||
"symfony/validator": "^3.4|^4.0"
|
||||
"symfony/validator": "^3.4|^4.0",
|
||||
"symfony/var-dumper": "^4.1"
|
||||
},
|
||||
"autoload": {
|
||||
"psr-4": {
|
||||
|
||||
@@ -1,14 +1,23 @@
|
||||
<?php
|
||||
|
||||
/*
|
||||
* This file is part of the MNC\ChileanRut library.
|
||||
*
|
||||
* (c) Matías Navarro Carter <mnavarrocarter@gmail.com>
|
||||
* For the full copyright and license information, please view the LICENSE
|
||||
* file that was distributed with this source code.
|
||||
*/
|
||||
|
||||
namespace MNC\ChileanRut\Bridge\Doctrine\DBAL\Types;
|
||||
|
||||
use Doctrine\DBAL\Platforms\AbstractPlatform;
|
||||
use Doctrine\DBAL\Types\ConversionException;
|
||||
use Doctrine\DBAL\Types\StringType;
|
||||
use MNC\ChileanRut\Rut\Rut;
|
||||
use MNC\ChileanRut\Rut;
|
||||
|
||||
/**
|
||||
* Class RutType
|
||||
* Class RutType.
|
||||
*
|
||||
* @author Matías Navarro Carter <mnavarro@option.cl>
|
||||
*/
|
||||
class RutType extends StringType
|
||||
@@ -26,7 +35,9 @@ class RutType extends StringType
|
||||
/**
|
||||
* @param mixed $value
|
||||
* @param AbstractPlatform $platform
|
||||
*
|
||||
* @return mixed
|
||||
*
|
||||
* @throws ConversionException
|
||||
*/
|
||||
public function convertToDatabaseValue($value, AbstractPlatform $platform)
|
||||
@@ -45,13 +56,14 @@ class RutType extends StringType
|
||||
/**
|
||||
* @param mixed $value
|
||||
* @param AbstractPlatform $platform
|
||||
*
|
||||
* @return mixed
|
||||
*/
|
||||
public function convertToPHPValue($value, AbstractPlatform $platform)
|
||||
{
|
||||
$value = parent::convertToPHPValue($value, $platform);
|
||||
|
||||
if ($value === null || $value instanceof Rut) {
|
||||
if (null === $value || $value instanceof Rut) {
|
||||
return $value;
|
||||
}
|
||||
|
||||
|
||||
@@ -1,27 +1,75 @@
|
||||
<?php
|
||||
|
||||
/*
|
||||
* This file is part of the MNC\ChileanRut library.
|
||||
*
|
||||
* (c) Matías Navarro Carter <mnavarrocarter@gmail.com>
|
||||
* For the full copyright and license information, please view the LICENSE
|
||||
* file that was distributed with this source code.
|
||||
*/
|
||||
|
||||
namespace MNC\ChileanRut\Bridge\Symfony\Form;
|
||||
|
||||
use MNC\ChileanRut\Rut\Rut;
|
||||
use MNC\ChileanRut\Rut;
|
||||
use Symfony\Component\Form\AbstractType;
|
||||
use Symfony\Component\Form\Extension\Core\Type\TextType;
|
||||
use Symfony\Component\Form\DataTransformerInterface;
|
||||
use Symfony\Component\Form\FormBuilderInterface;
|
||||
use Symfony\Component\Form\FormInterface;
|
||||
use Symfony\Component\OptionsResolver\OptionsResolver;
|
||||
|
||||
/**
|
||||
* Class RutType
|
||||
* @package MNC\ChileanRut\Bridge\Symfony\Form
|
||||
* Class RutType.
|
||||
*
|
||||
* @author Matías Navarro Carter <mnavarro@option.cl>
|
||||
*/
|
||||
class RutType extends TextType
|
||||
class RutType extends AbstractType implements DataTransformerInterface
|
||||
{
|
||||
public function buildForm(FormBuilderInterface $builder, array $options): void
|
||||
{
|
||||
$builder->addModelTransformer($this);
|
||||
}
|
||||
|
||||
/**
|
||||
* @param OptionsResolver $resolver
|
||||
*/
|
||||
public function configureOptions(OptionsResolver $resolver): void
|
||||
{
|
||||
$resolver->setDefaults([
|
||||
'compound' => false,
|
||||
'data_class' => Rut::class,
|
||||
'empty_data' => function (FormInterface $form) {
|
||||
return new Rut($form->getData());
|
||||
},
|
||||
]);
|
||||
}
|
||||
|
||||
/**
|
||||
* {@inheritdoc}
|
||||
*/
|
||||
public function getBlockPrefix(): ?string
|
||||
{
|
||||
return 'rut';
|
||||
}
|
||||
|
||||
/**
|
||||
* @param mixed $value
|
||||
*
|
||||
* @return mixed|string
|
||||
*/
|
||||
public function transform($value)
|
||||
{
|
||||
if ($value instanceof Rut) {
|
||||
return $value->format(Rut::FORMAT_READABLE);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* @param mixed $value
|
||||
*
|
||||
* @return mixed|Rut
|
||||
*/
|
||||
public function reverseTransform($value)
|
||||
{
|
||||
return new Rut((string) $value);
|
||||
}
|
||||
}
|
||||
@@ -1,5 +1,13 @@
|
||||
<?php
|
||||
|
||||
/*
|
||||
* This file is part of the MNC\ChileanRut library.
|
||||
*
|
||||
* (c) Matías Navarro Carter <mnavarrocarter@gmail.com>
|
||||
* For the full copyright and license information, please view the LICENSE
|
||||
* file that was distributed with this source code.
|
||||
*/
|
||||
|
||||
namespace MNC\ChileanRut\Bridge\Symfony\Validator;
|
||||
|
||||
use Symfony\Component\Validator\Constraint;
|
||||
|
||||
@@ -1,9 +1,17 @@
|
||||
<?php
|
||||
|
||||
/*
|
||||
* This file is part of the MNC\ChileanRut library.
|
||||
*
|
||||
* (c) Matías Navarro Carter <mnavarrocarter@gmail.com>
|
||||
* For the full copyright and license information, please view the LICENSE
|
||||
* file that was distributed with this source code.
|
||||
*/
|
||||
|
||||
namespace MNC\ChileanRut\Bridge\Symfony\Validator;
|
||||
|
||||
use MNC\ChileanRut\Exception\InvalidRutException;
|
||||
use MNC\ChileanRut\Rut\Rut;
|
||||
use MNC\ChileanRut\Rut;
|
||||
use MNC\ChileanRut\Validator\RutValidator;
|
||||
use MNC\ChileanRut\Validator\SimpleRutValidator;
|
||||
use Symfony\Component\Form\Exception\UnexpectedTypeException;
|
||||
@@ -11,8 +19,8 @@ use Symfony\Component\Validator\Constraint;
|
||||
use Symfony\Component\Validator\ConstraintValidator;
|
||||
|
||||
/**
|
||||
* Class IsValidRutValidator
|
||||
* @package MNC\ChileanRut\Bridge\Symfony\Validator
|
||||
* Class IsValidRutValidator.
|
||||
*
|
||||
* @author Matías Navarro Carter <mnavarro@option.cl>
|
||||
*/
|
||||
class IsValidRutValidator extends ConstraintValidator
|
||||
|
||||
@@ -1,12 +1,20 @@
|
||||
<?php
|
||||
|
||||
/*
|
||||
* This file is part of the MNC\ChileanRut library.
|
||||
*
|
||||
* (c) Matías Navarro Carter <mnavarrocarter@gmail.com>
|
||||
* For the full copyright and license information, please view the LICENSE
|
||||
* file that was distributed with this source code.
|
||||
*/
|
||||
|
||||
namespace MNC\ChileanRut\Exception;
|
||||
|
||||
use MNC\ChileanRut\Rut\Rut;
|
||||
use MNC\ChileanRut\Rut;
|
||||
|
||||
/**
|
||||
* Class InvalidRutException
|
||||
* @package MNC\ChileanRut\Rut
|
||||
* Class InvalidRutException.
|
||||
*
|
||||
* @author Matías Navarro Carter <mnavarro@option.cl>
|
||||
*/
|
||||
class InvalidRutException extends \LogicException
|
||||
@@ -18,11 +26,15 @@ class InvalidRutException extends \LogicException
|
||||
|
||||
/**
|
||||
* InvalidRutException constructor.
|
||||
*
|
||||
* @param Rut $rut
|
||||
* @param string|null $message
|
||||
*/
|
||||
public function __construct(Rut $rut)
|
||||
public function __construct(Rut $rut, string $message = null)
|
||||
{
|
||||
if (null === $message) {
|
||||
$message = sprintf('Rut %s is not a valid rut.', $rut->format(Rut::FORMAT_READABLE));
|
||||
}
|
||||
$this->rut = $rut;
|
||||
parent::__construct($message);
|
||||
}
|
||||
|
||||
@@ -1,11 +1,20 @@
|
||||
<?php
|
||||
|
||||
namespace MNC\ChileanRut\Rut;
|
||||
/*
|
||||
* This file is part of the MNC\ChileanRut library.
|
||||
*
|
||||
* (c) Matías Navarro Carter <mnavarrocarter@gmail.com>
|
||||
* For the full copyright and license information, please view the LICENSE
|
||||
* file that was distributed with this source code.
|
||||
*/
|
||||
|
||||
namespace MNC\ChileanRut;
|
||||
|
||||
use MNC\ChileanRut\Validator\RutValidator;
|
||||
|
||||
/**
|
||||
* Class Rut
|
||||
* Class Rut.
|
||||
*
|
||||
* @author Matías Navarro Carter <mnavarro@option.cl>
|
||||
*/
|
||||
class Rut
|
||||
@@ -13,6 +22,7 @@ class Rut
|
||||
public const FORMAT_HYPHENED = 0; // 14533535-5
|
||||
public const FORMAT_CLEAR = 1; // 145335355
|
||||
public const FORMAT_READABLE = 2; // 14.533.535-5
|
||||
public const FORMAT_HIDDEN = 3; // 17.***.***-5
|
||||
|
||||
/**
|
||||
* @var string
|
||||
@@ -25,8 +35,9 @@ class Rut
|
||||
|
||||
/**
|
||||
* Rut constructor.
|
||||
*
|
||||
* @param string $rut
|
||||
* @param RutValidator|null $validator if provided validates the Rut.
|
||||
* @param RutValidator|null $validator if provided validates the Rut
|
||||
*/
|
||||
public function __construct(string $rut, RutValidator $validator = null)
|
||||
{
|
||||
@@ -39,9 +50,18 @@ class Rut
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* @return string
|
||||
*/
|
||||
public function __toString(): string
|
||||
{
|
||||
return $this->format(self::FORMAT_READABLE);
|
||||
}
|
||||
|
||||
/**
|
||||
* @param string $correlative
|
||||
* @param string $verifierDigit
|
||||
*
|
||||
* @return Rut
|
||||
*/
|
||||
public static function fromParts(string $correlative, string $verifierDigit): Rut
|
||||
@@ -51,6 +71,7 @@ class Rut
|
||||
|
||||
/**
|
||||
* @param string $rut
|
||||
*
|
||||
* @return Rut
|
||||
*/
|
||||
public static function fromString(string $rut): Rut
|
||||
@@ -60,6 +81,7 @@ class Rut
|
||||
|
||||
/**
|
||||
* @param Rut $rut
|
||||
*
|
||||
* @return bool
|
||||
*/
|
||||
public function isEqualTo(Rut $rut): bool
|
||||
@@ -68,18 +90,10 @@ class Rut
|
||||
}
|
||||
|
||||
/**
|
||||
* @param string $value
|
||||
* @return string
|
||||
*/
|
||||
private function sanitize(string $value): string
|
||||
{
|
||||
$value = trim($value);
|
||||
$value = strtoupper($value);
|
||||
return str_replace(['.', ',', '-'], '', $value);
|
||||
}
|
||||
|
||||
/**
|
||||
* @param int $format One of the FORMAT_ constants.
|
||||
* Formats a Rut to a string.
|
||||
*
|
||||
* @param int $format one of the FORMAT_ constants
|
||||
*
|
||||
* @return string
|
||||
*/
|
||||
public function format(int $format = 0): string
|
||||
@@ -92,7 +106,10 @@ class Rut
|
||||
return $this->value.$this->dv;
|
||||
break;
|
||||
case self::FORMAT_READABLE:
|
||||
return sprintf('%s-%s', number_format($this->value, 0, '', '.'), $this->dv);
|
||||
return $this->formatReadable();
|
||||
break;
|
||||
case self::FORMAT_HIDDEN:
|
||||
return $this->formatHidden();
|
||||
break;
|
||||
default:
|
||||
throw new \InvalidArgumentException(
|
||||
@@ -106,6 +123,8 @@ class Rut
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the correlative number of the Rut.
|
||||
*
|
||||
* @return string
|
||||
*/
|
||||
public function getCorrelative(): string
|
||||
@@ -114,6 +133,8 @@ class Rut
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the verifier digit of the Rut.
|
||||
*
|
||||
* @return string
|
||||
*/
|
||||
public function getVerifierDigit(): string
|
||||
@@ -122,10 +143,36 @@ class Rut
|
||||
}
|
||||
|
||||
/**
|
||||
* Sanitizes a Rut string.
|
||||
*
|
||||
* @param string $value
|
||||
*
|
||||
* @return string
|
||||
*/
|
||||
public function __toString(): string
|
||||
private function sanitize(string $value): string
|
||||
{
|
||||
return $this->format(self::FORMAT_READABLE);
|
||||
$value = trim($value);
|
||||
$value = strtoupper($value);
|
||||
|
||||
return str_replace(['.', ',', '-'], '', $value);
|
||||
}
|
||||
|
||||
/**
|
||||
* @return string
|
||||
*/
|
||||
private function formatReadable(): string
|
||||
{
|
||||
return sprintf('%s-%s', number_format($this->value, 0, '', '.'), $this->dv);
|
||||
}
|
||||
|
||||
/**
|
||||
* @return string
|
||||
*/
|
||||
private function formatHidden(): string
|
||||
{
|
||||
$readable = $this->formatReadable();
|
||||
$exploded = explode('.', $readable);
|
||||
|
||||
return sprintf('%s.***.***-%s', $exploded[0], $this->dv);
|
||||
}
|
||||
}
|
||||
@@ -1,20 +1,29 @@
|
||||
<?php
|
||||
|
||||
/*
|
||||
* This file is part of the MNC\ChileanRut library.
|
||||
*
|
||||
* (c) Matías Navarro Carter <mnavarrocarter@gmail.com>
|
||||
* For the full copyright and license information, please view the LICENSE
|
||||
* file that was distributed with this source code.
|
||||
*/
|
||||
|
||||
namespace MNC\ChileanRut\Util;
|
||||
|
||||
use MNC\ChileanRut\Rut\Rut;
|
||||
use MNC\ChileanRut\Rut;
|
||||
|
||||
/**
|
||||
* This class provides utils for a Rut correlative.
|
||||
*
|
||||
* @author Matías Navarro Carter <mnavarro@option.cl>
|
||||
*/
|
||||
class Correlative
|
||||
class CorrelativeUtils
|
||||
{
|
||||
/**
|
||||
* Finds the verifier digit of a correlative.
|
||||
*
|
||||
* @param string $correlative
|
||||
*
|
||||
* @return string
|
||||
*/
|
||||
public static function findVerifierDigit(string $correlative): string
|
||||
@@ -22,21 +31,21 @@ class Correlative
|
||||
$x = 2;
|
||||
$s = 0;
|
||||
|
||||
for ($i = \strlen($correlative) - 1; $i >= 0; $i--) {
|
||||
for ($i = \strlen($correlative) - 1; $i >= 0; --$i) {
|
||||
if ($x > 7) {
|
||||
$x = 2;
|
||||
}
|
||||
$s += $correlative[$i] * $x;
|
||||
$x++;
|
||||
++$x;
|
||||
}
|
||||
|
||||
$dv = 11 - ($s % 11);
|
||||
|
||||
if ($dv === 10) {
|
||||
if (10 === $dv) {
|
||||
$dv = 'K';
|
||||
}
|
||||
|
||||
if ($dv === 11) {
|
||||
if (11 === $dv) {
|
||||
$dv = '0';
|
||||
}
|
||||
|
||||
@@ -47,10 +56,25 @@ class Correlative
|
||||
* Instantiates a valid Rut object just providing a correlative.
|
||||
*
|
||||
* @param string $correlative
|
||||
*
|
||||
* @return Rut
|
||||
*/
|
||||
public static function createValidRutOnlyFromCorrelative(string $correlative): Rut
|
||||
{
|
||||
return Rut::fromParts($correlative, static::findVerifierDigit($correlative));
|
||||
}
|
||||
|
||||
/**
|
||||
* Auto-generates an algorithmically valid Rut, because why not.
|
||||
*
|
||||
* @return Rut
|
||||
*
|
||||
* @throws \Exception on insufficient entropy on correlative generation
|
||||
*/
|
||||
public static function autoGenerateValidRut(): Rut
|
||||
{
|
||||
$correlative = \random_int(1000000, 40000000);
|
||||
|
||||
return static::createValidRutOnlyFromCorrelative($correlative);
|
||||
}
|
||||
}
|
||||
@@ -1,12 +1,20 @@
|
||||
<?php
|
||||
|
||||
/*
|
||||
* This file is part of the MNC\ChileanRut library.
|
||||
*
|
||||
* (c) Matías Navarro Carter <mnavarrocarter@gmail.com>
|
||||
* For the full copyright and license information, please view the LICENSE
|
||||
* file that was distributed with this source code.
|
||||
*/
|
||||
|
||||
namespace MNC\ChileanRut\Validator;
|
||||
|
||||
use MNC\ChileanRut\Exception\InvalidRutException;
|
||||
use MNC\ChileanRut\Rut\Rut;
|
||||
use MNC\ChileanRut\Rut;
|
||||
|
||||
/**
|
||||
* A ChainRutValidator
|
||||
* A ChainRutValidator.
|
||||
*
|
||||
* Use this implementation when you want to validate a Rut against multiple
|
||||
* validators. Add the validators in order by calling addValidator().
|
||||
@@ -29,18 +37,23 @@ class ChainRutValidator implements RutValidator
|
||||
}
|
||||
|
||||
/**
|
||||
* Appends a RutValidator instance to the validation chain.
|
||||
*
|
||||
* @param RutValidator $validator
|
||||
*
|
||||
* @return ChainRutValidator
|
||||
*/
|
||||
public function addValidator(RutValidator $validator): ChainRutValidator
|
||||
public function append(RutValidator $validator): ChainRutValidator
|
||||
{
|
||||
$this->validators[] = $validator;
|
||||
|
||||
return $this;
|
||||
}
|
||||
|
||||
/**
|
||||
* @param Rut $rut
|
||||
* @throws InvalidRutException on invalid Rut.
|
||||
*
|
||||
* @throws InvalidRutException on invalid Rut
|
||||
*/
|
||||
public function validate(Rut $rut): void
|
||||
{
|
||||
|
||||
@@ -1,9 +1,17 @@
|
||||
<?php
|
||||
|
||||
/*
|
||||
* This file is part of the MNC\ChileanRut library.
|
||||
*
|
||||
* (c) Matías Navarro Carter <mnavarrocarter@gmail.com>
|
||||
* For the full copyright and license information, please view the LICENSE
|
||||
* file that was distributed with this source code.
|
||||
*/
|
||||
|
||||
namespace MNC\ChileanRut\Validator;
|
||||
|
||||
use MNC\ChileanRut\Exception\InvalidRutException;
|
||||
use MNC\ChileanRut\Rut\Rut;
|
||||
use MNC\ChileanRut\Rut;
|
||||
|
||||
/**
|
||||
* This is the base contract for a Rut validator.
|
||||
@@ -15,7 +23,6 @@ use MNC\ChileanRut\Rut\Rut;
|
||||
* You could create a HTTPRutValidator that performs a request to validate that a
|
||||
* Rut exists against a Rest Api or a third party service.
|
||||
*
|
||||
* @package MNC\ChileanRut\Validator
|
||||
* @author Matías Navarro Carter <mnavarro@option.cl>
|
||||
*/
|
||||
interface RutValidator
|
||||
@@ -29,7 +36,8 @@ interface RutValidator
|
||||
* error according to their business rules.
|
||||
*
|
||||
* @param Rut $rut
|
||||
* @throws InvalidRutException on invalid Rut.
|
||||
*
|
||||
* @throws InvalidRutException on invalid Rut
|
||||
*/
|
||||
public function validate(Rut $rut): void;
|
||||
}
|
||||
@@ -1,10 +1,18 @@
|
||||
<?php
|
||||
|
||||
/*
|
||||
* This file is part of the MNC\ChileanRut library.
|
||||
*
|
||||
* (c) Matías Navarro Carter <mnavarrocarter@gmail.com>
|
||||
* For the full copyright and license information, please view the LICENSE
|
||||
* file that was distributed with this source code.
|
||||
*/
|
||||
|
||||
namespace MNC\ChileanRut\Validator;
|
||||
|
||||
use MNC\ChileanRut\Exception\InvalidRutException;
|
||||
use MNC\ChileanRut\Rut\Rut;
|
||||
use MNC\ChileanRut\Util\Correlative;
|
||||
use MNC\ChileanRut\Rut;
|
||||
use MNC\ChileanRut\Util\CorrelativeUtils;
|
||||
|
||||
/**
|
||||
* Validates the Rut using the Module 11 algorithm.
|
||||
@@ -15,10 +23,12 @@ class SimpleRutValidator implements RutValidator
|
||||
{
|
||||
/**
|
||||
* @param Rut $rut
|
||||
*
|
||||
* @throws InvalidRutException
|
||||
*/
|
||||
public function validate(Rut $rut): void
|
||||
{
|
||||
$digit = Correlative::findVerifierDigit($rut->getCorrelative());
|
||||
$digit = CorrelativeUtils::findVerifierDigit($rut->getCorrelative());
|
||||
|
||||
if ($digit !== $rut->getVerifierDigit()) {
|
||||
throw new InvalidRutException($rut);
|
||||
|
||||
41
tests/Bridge/Symfony/Form/RutTypeTest.php
Normal file
41
tests/Bridge/Symfony/Form/RutTypeTest.php
Normal file
@@ -0,0 +1,41 @@
|
||||
<?php
|
||||
|
||||
/*
|
||||
* This file is part of the MNC\ChileanRut library.
|
||||
*
|
||||
* (c) Matías Navarro Carter <mnavarrocarter@gmail.com>
|
||||
* For the full copyright and license information, please view the LICENSE
|
||||
* file that was distributed with this source code.
|
||||
*/
|
||||
|
||||
namespace MNC\ChileanRut\Tests\Bridge\Symfony\Form;
|
||||
|
||||
use MNC\ChileanRut\Bridge\Symfony\Form\RutType;
|
||||
use MNC\ChileanRut\Rut;
|
||||
use Symfony\Component\Form\Test\TypeTestCase;
|
||||
|
||||
class RutTypeTest extends TypeTestCase
|
||||
{
|
||||
public function testSubmitValidData()
|
||||
{
|
||||
$objectToCompare = new Rut('16.894.365-2');
|
||||
|
||||
// $objectToCompare will retrieve data from the form submission; pass it as the second argument
|
||||
$form = $this->factory->create(RutType::class);
|
||||
|
||||
// submit the data to the form directly
|
||||
$form->submit('16.894.365-2');
|
||||
|
||||
$this->assertTrue($form->isSynchronized());
|
||||
|
||||
$formData = $form->getData();
|
||||
|
||||
// check that $objectToCompare was modified as expected when the form was submitted
|
||||
$this->assertInstanceOf(Rut::class, $formData);
|
||||
$this->assertTrue($formData->isEqualTo($objectToCompare));
|
||||
|
||||
$view = $form->createView();
|
||||
|
||||
$this->assertSame('16.894.365-2', $view->vars['value']);
|
||||
}
|
||||
}
|
||||
@@ -1,15 +1,17 @@
|
||||
<?php
|
||||
/**
|
||||
* Created by PhpStorm.
|
||||
* User: mnavarro
|
||||
* Date: 07-08-18
|
||||
* Time: 23:45
|
||||
|
||||
/*
|
||||
* This file is part of the MNC\ChileanRut library.
|
||||
*
|
||||
* (c) Matías Navarro Carter <mnavarrocarter@gmail.com>
|
||||
* For the full copyright and license information, please view the LICENSE
|
||||
* file that was distributed with this source code.
|
||||
*/
|
||||
|
||||
namespace MNC\ChileanRut\Tests\Rut;
|
||||
|
||||
use MNC\ChileanRut\Exception\InvalidRutException;
|
||||
use MNC\ChileanRut\Rut\Rut;
|
||||
use MNC\ChileanRut\Rut;
|
||||
use MNC\ChileanRut\Validator\SimpleRutValidator;
|
||||
use PHPUnit\Framework\TestCase;
|
||||
|
||||
@@ -19,8 +21,8 @@ class RutTest extends TestCase
|
||||
{
|
||||
$rut = Rut::fromString('16.894.365-2');
|
||||
|
||||
$this->assertEquals('16894365', $rut->getCorrelative());
|
||||
$this->assertEquals('2', $rut->getVerifierDigit());
|
||||
$this->assertSame('16894365', $rut->getCorrelative());
|
||||
$this->assertSame('2', $rut->getVerifierDigit());
|
||||
}
|
||||
|
||||
public function testThatRutsInstantiatedDifferentFormatButWithEqualValueAreIndeedEqual()
|
||||
@@ -33,19 +35,25 @@ class RutTest extends TestCase
|
||||
public function testThatFormatClearWorks()
|
||||
{
|
||||
$rut = new Rut('16.894.365-2');
|
||||
$this->assertEquals('168943652', $rut->format(Rut::FORMAT_CLEAR));
|
||||
$this->assertSame('168943652', $rut->format(Rut::FORMAT_CLEAR));
|
||||
}
|
||||
|
||||
public function testThatFormatWithHyphenWorks()
|
||||
{
|
||||
$rut = new Rut('16.894.365-2');
|
||||
$this->assertEquals('16894365-2', $rut->format(Rut::FORMAT_HYPHENED));
|
||||
$this->assertSame('16894365-2', $rut->format(Rut::FORMAT_HYPHENED));
|
||||
}
|
||||
|
||||
public function testThatFormatReadableWorks()
|
||||
{
|
||||
$rut = new Rut('168943652');
|
||||
$this->assertEquals('16.894.365-2', $rut->format(Rut::FORMAT_READABLE));
|
||||
$this->assertSame('16.894.365-2', $rut->format(Rut::FORMAT_READABLE));
|
||||
}
|
||||
|
||||
public function testThatFormatHiddenWorks()
|
||||
{
|
||||
$rut = new Rut('168943652');
|
||||
$this->assertSame('16.***.***-2', $rut->format(Rut::FORMAT_HIDDEN));
|
||||
}
|
||||
|
||||
public function testThatIntegratedValidationThrowsExceptionOnInvalidRut()
|
||||
@@ -63,4 +71,12 @@ class RutTest extends TestCase
|
||||
|
||||
$this->assertInstanceOf(Rut::class, $rut);
|
||||
}
|
||||
|
||||
public function testInvalidFormatValueRaisesException()
|
||||
{
|
||||
$rut = new Rut('16.894.365-2');
|
||||
|
||||
$this->expectException(\InvalidArgumentException::class);
|
||||
$rut->format(23);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,9 +1,17 @@
|
||||
<?php
|
||||
|
||||
/*
|
||||
* This file is part of the MNC\ChileanRut library.
|
||||
*
|
||||
* (c) Matías Navarro Carter <mnavarrocarter@gmail.com>
|
||||
* For the full copyright and license information, please view the LICENSE
|
||||
* file that was distributed with this source code.
|
||||
*/
|
||||
|
||||
namespace MNC\ChileanRut\Tests\Validator;
|
||||
|
||||
use MNC\ChileanRut\Exception\InvalidRutException;
|
||||
use MNC\ChileanRut\Rut\Rut;
|
||||
use MNC\ChileanRut\Rut;
|
||||
use MNC\ChileanRut\Validator\SimpleRutValidator;
|
||||
use PHPUnit\Framework\TestCase;
|
||||
|
||||
|
||||
Reference in New Issue
Block a user