Skip to content

Commit a9976ed

Browse files
committed
Initial release: RIF PHP Library v1.0.0
0 parents  commit a9976ed

21 files changed

Lines changed: 1749 additions & 0 deletions

.editorconfig

Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,15 @@
1+
root = true
2+
3+
[*]
4+
charset = utf-8
5+
end_of_line = lf
6+
insert_final_newline = true
7+
trim_trailing_whitespace = true
8+
indent_style = space
9+
indent_size = 4
10+
11+
[*.md]
12+
trim_trailing_whitespace = false
13+
14+
[*.{yml,yaml}]
15+
indent_size = 2

.github/workflows/tests.yml

Lines changed: 37 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,37 @@
1+
name: Tests
2+
3+
on:
4+
push:
5+
branches: [ main, develop ]
6+
pull_request:
7+
branches: [ main ]
8+
9+
jobs:
10+
test:
11+
name: PHP ${{ matrix.php-version }}
12+
runs-on: ubuntu-latest
13+
strategy:
14+
matrix:
15+
php-version: ['8.3', '8.4']
16+
17+
steps:
18+
- name: Checkout code
19+
uses: actions/checkout@v4
20+
21+
- name: Setup PHP
22+
uses: shivammathur/setup-php@v2
23+
with:
24+
php-version: ${{ matrix.php-version }}
25+
coverage: none
26+
27+
- name: Validate composer.json
28+
run: composer validate --strict
29+
30+
- name: Install dependencies
31+
run: composer install --prefer-dist --no-progress --no-interaction
32+
33+
- name: Run test suite
34+
run: composer test
35+
36+
- name: Check code style
37+
run: composer lint

.gitignore

Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,22 @@
1+
/vendor/
2+
/composer.lock
3+
/coverage/
4+
.phpunit.cache/
5+
.phpunit.result.cache
6+
.DS_Store
7+
.idea/
8+
*.log
9+
10+
# IDE
11+
.vscode/
12+
.phpintel/
13+
.idea/
14+
*.swp
15+
*.swo
16+
17+
# Sistema
18+
.DS_Store
19+
Thumbs.db
20+
21+
# Logs
22+
*.log

LICENCE

Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,21 @@
1+
MIT License
2+
3+
Copyright (c) 2024 Ernesto Chapon
4+
5+
Permission is hereby granted, free of charge, to any person obtaining a copy
6+
of this software and associated documentation files (the "Software"), to deal
7+
in the Software without restriction, including without limitation the rights
8+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9+
copies of the Software, and to permit persons to whom the Software is
10+
furnished to do so, subject to the following conditions:
11+
12+
The above copyright notice and this permission notice shall be included in all
13+
copies or substantial portions of the Software.
14+
15+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21+
SOFTWARE.

README.md

Lines changed: 246 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,246 @@
1+
# RIF PHP
2+
3+
[![PHP Version](https://img.shields.io/badge/php-8.3%2B-blue.svg)](https://packagist.org/packages/ernestoch/rif-php)
4+
[![Tests](https://github.com/3rn3st0/rif-php/actions/workflows/tests.yml/badge.svg)](https://github.com/3rn3st0/rif-php/actions/workflows/tests.yml)
5+
[![License](https://img.shields.io/badge/license-MIT-green.svg)](LICENSE)
6+
7+
Una librería PHP profesional para validar, formatear y generar números RIF (Registro de Información Fiscal) de Venezuela.
8+
9+
## ✨ Características
10+
11+
-**Validación completa** de números RIF según algoritmo oficial
12+
-**Cálculo del dígito verificador** con algoritmo verificados
13+
-**Soporte para todos los tipos** de RIF (V, E, J, P, G, C)
14+
-**Formateo profesional** para presentación
15+
-**Generación de RIFs válidos** para testing
16+
-**100% type-hinted** y compatible con PHP 8.3+
17+
-**Cobertura completa de tests**
18+
-**PSR-4 y estándares modernos** de PHP
19+
20+
## 📦 Instalación
21+
22+
```bash
23+
composer require ernestoch/rif-php
24+
```
25+
26+
## 🚀 Uso Rápido
27+
28+
```php
29+
<?php
30+
31+
require_once 'vendor/autoload.php';
32+
33+
use TurecoLabs\Rif\Rif;
34+
35+
// Validación simple
36+
if (Rif::isValid('V113502963')) {
37+
echo "RIF válido!";
38+
}
39+
40+
// Validación con manejo de excepciones
41+
try {
42+
$rif = Rif::create('J000029679');
43+
echo "RIF: " . $rif->getRaw();
44+
echo "Tipo: " . $rif->getType()->getDescription();
45+
echo "Número: " . $rif->getNumber();
46+
echo "Dígito verificador: " . $rif->getCheckDigit();
47+
} catch (TurecoLabs\Rif\Exceptions\RifValidationException $e) {
48+
echo "Error: " . $e->getMessage();
49+
}
50+
51+
// Validación de RIFs conocidos
52+
$knownRifs = [
53+
'V113502963', // RIF personal
54+
'G200001100', // Banco Central de Venezuela
55+
'J000029679', // Banco Provincial
56+
];
57+
58+
foreach ($knownRifs as $rifString) {
59+
if (Rif::isValid($rifString)) {
60+
echo "$rifString es válido\n";
61+
}
62+
}
63+
```
64+
65+
## 🎨 Formateadores
66+
67+
La librería incluye múltiples formateadores para diferentes contextos:
68+
69+
```php
70+
<?php
71+
72+
use TurecoLabs\Rif\Rif;
73+
use TurecoLabs\Rif\Formatters\RifFormatter;
74+
75+
$rif = Rif::create('J000029679');
76+
77+
// Diferentes formatos disponibles
78+
echo RifFormatter::standard($rif); // J-00002967-9
79+
echo RifFormatter::spaced($rif); // J 00 002 967 9
80+
echo RifFormatter::withDescription($rif); // J-00002967-9 (Persona Jurídica)
81+
echo RifFormatter::dotted($rif); // J-2.967-9
82+
echo RifFormatter::legal($rif); // R.I.F. J-00002967-9
83+
84+
// Método de conveniencia
85+
echo $rif->format('standard'); // J-00002967-9
86+
echo $rif->format('spaced'); // J 00 002 967 9
87+
```
88+
89+
### Casos de uso comunes:
90+
91+
Interfaces de usuario: spaced o dotted para mejor legibilidad
92+
93+
Bases de datos: compact o database para almacenamiento
94+
95+
Facturas electrónicas: invoice (formato SENIAT)
96+
97+
Documentos legales: legal para contratos y documentos formales
98+
99+
Mostrar información completa: withDescription para interfaces administrativas
100+
101+
## 🎲 Generador de RIFs Válidos
102+
103+
Genera RIFs válidos para testing y desarrollo:
104+
105+
```php
106+
<?php
107+
108+
use TurecoLabs\Rif\Rif;
109+
use TurecoLabs\Rif\Types\RifType;
110+
111+
// Generar un RIF aleatorio
112+
$rif = Rif::generate();
113+
echo $rif->getRaw(); // Ej: V123456789
114+
115+
// Generar un tipo específico
116+
$rif = Rif::generate(RifType::LEGAL);
117+
echo $rif->getRaw(); // Ej: J987654321
118+
119+
// Generar múltiples RIFs
120+
$rifs = Rif::generateMultiple(5);
121+
foreach ($rifs as $rif) {
122+
echo $rif->format() . "\n";
123+
}
124+
125+
// Generar RIF secuencial (útil para testing)
126+
$rif = Rif::generateSequential(42, RifType::NATURAL);
127+
echo $rif->getRaw(); // V00000042X
128+
129+
// Usar el generador directamente
130+
use TurecoLabs\Rif\Services\RifGenerator;
131+
132+
$rif = RifGenerator::generateOneOfEachType();
133+
foreach ($rif as $type => $rifInstance) {
134+
echo "{$type}: {$rifInstance->format()}\n";
135+
}
136+
```
137+
138+
### Casos de uso del generador:
139+
140+
Testing: Generar datos de prueba para tus tests unitarios
141+
142+
Desarrollo: Rellenar bases de datos de desarrollo
143+
144+
Demostraciones: Crear ejemplos para documentación o presentaciones
145+
146+
Prototipos: Probar interfaces sin necesidad de RIFs reales
147+
148+
## 🔍 Validador de Formato
149+
150+
Valida la estructura de un RIF sin verificar el dígito verificador:
151+
152+
```php
153+
<?php
154+
155+
use TurecoLabs\Rif\Rif;
156+
use TurecoLabs\Rif\Validators\FormatValidator;
157+
158+
// Validar estructura completa (pero sin dígito verificador)
159+
if (Rif::isValidFormat('J123456789')) {
160+
echo "Formato válido";
161+
}
162+
163+
// Validar usando el validador directamente
164+
if (FormatValidator::validateStructure('V113502963')) {
165+
echo "Estructura válida";
166+
}
167+
168+
// Validación parcial (prefijo y cuerpo)
169+
if (FormatValidator::validatePartial('J123456789')) {
170+
echo "Prefijo y cuerpo válidos";
171+
}
172+
173+
// Validar componentes individuales
174+
if (FormatValidator::isValidPrefix('V')) {
175+
echo "Prefijo válido";
176+
}
177+
178+
if (FormatValidator::isValidBody('12345678')) {
179+
echo "Cuerpo válido";
180+
}
181+
182+
// Extraer el tipo de RIF
183+
$type = FormatValidator::extractType('J123456789');
184+
if ($type) {
185+
echo "Tipo: " . $type->getDescription();
186+
}
187+
188+
// Obtener detalles de validación para feedback al usuario
189+
$details = Rif::validateFormat('X12A');
190+
if (!$details['is_valid']) {
191+
foreach ($details['errors'] as $error) {
192+
echo "Error: $error\n";
193+
}
194+
foreach ($details['suggestions'] as $suggestion) {
195+
echo "Sugerencia: $suggestion\n";
196+
}
197+
}
198+
```
199+
200+
### Casos de uso del validador de formato:
201+
202+
Validación en tiempo real: En formularios, validar mientras el usuario escribe
203+
204+
Feedback inmediato: Indicar errores de formato sin esperar a la validación completa
205+
206+
Limpieza de datos: Verificar datos antes de procesarlos
207+
208+
Clasificación: Identificar el tipo de RIF antes de validar completamente
209+
210+
## 🧪 Ejecución de Tests
211+
212+
```bash
213+
# Ejecutar tests
214+
composer test
215+
216+
# Análisis estático de código
217+
composer analyse
218+
219+
# Verificación de estándares de código
220+
composer lint
221+
```
222+
223+
## 📚 Documentación
224+
225+
Consulta la [documentación completa](README.md) para más ejemplos y API reference.
226+
227+
## 🤝 Contribuciones
228+
229+
Las contribuciones son bienvenidas. Por favor:
230+
231+
Fork el proyecto
232+
233+
Crea una rama para tu feature (git checkout -b feature/AmazingFeature)
234+
235+
Commit tus cambios (git commit -m 'Add some AmazingFeature')
236+
237+
Push a la rama (git push origin feature/AmazingFeature)
238+
239+
Abre un Pull Request
240+
241+
## 📄 Licencia
242+
243+
Este proyecto está licenciado bajo la Licencia MIT - ver el archivo [LICENSE](LICENSE) para detalles.
244+
245+
## 🏢 Uso en Producción
246+
Esta librería está siendo utilizada en producción y ha sido verificada con RIFs reales del sistema venezolano.

composer.json

Lines changed: 46 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,46 @@
1+
{
2+
"name": "ernestoch/rif-php",
3+
"type": "library",
4+
"description": "Librería PHP para validar, formatear y generar números RIF (Registro de Información Fiscal) de Venezuela",
5+
"keywords": ["rif", "venezuela", "validación", "fiscal", "seniat", "contribuyente"],
6+
"homepage": "https://github.com/3rn3st0/rif-php",
7+
"license": "MIT",
8+
"version": "1.0.0",
9+
"authors": [
10+
{
11+
"name": "Ernesto Chapon",
12+
"email": "ernesto@turecolabs.com",
13+
"homepage": "https://github.com/3rn3st0",
14+
"role": "Developer"
15+
}
16+
],
17+
"require": {
18+
"php": "^8.3"
19+
},
20+
"require-dev": {
21+
"phpunit/phpunit": "^10.0",
22+
"squizlabs/php_codesniffer": "^3.0"
23+
},
24+
"autoload": {
25+
"psr-4": {
26+
"TurecoLabs\\Rif\\": "src/"
27+
}
28+
},
29+
"autoload-dev": {
30+
"psr-4": {
31+
"TurecoLabs\\Rif\\Tests\\": "tests/"
32+
}
33+
},
34+
"scripts": {
35+
"test": "phpunit",
36+
"lint": "phpcs --standard=PSR12 src tests",
37+
"fix": "phpcbf --standard=PSR12 src tests"
38+
},
39+
"config": {
40+
"allow-plugins": {
41+
"dealerdirect/phpcodesniffer-composer-installer": true
42+
}
43+
},
44+
"minimum-stability": "stable",
45+
"prefer-stable": true
46+
}

0 commit comments

Comments
 (0)