|
1
|
|
|
<?php |
|
2
|
|
|
|
|
3
|
|
|
/* |
|
4
|
|
|
* This file is part of Respect/Validation. |
|
5
|
|
|
* |
|
6
|
|
|
* (c) Alexandre Gomes Gaigalas <[email protected]> |
|
7
|
|
|
* |
|
8
|
|
|
* For the full copyright and license information, please view the "LICENSE.md" |
|
9
|
|
|
* file that was distributed with this source code. |
|
10
|
|
|
*/ |
|
11
|
|
|
|
|
12
|
|
|
namespace Respect\Validation\Rules; |
|
13
|
|
|
|
|
14
|
|
|
/** |
|
15
|
|
|
* Validates Spain's fiscal identification number (NIF). |
|
16
|
|
|
* |
|
17
|
|
|
* @author Julián Gutiérrez <[email protected]> |
|
18
|
|
|
* |
|
19
|
|
|
* @see https://es.wikipedia.org/wiki/N%C3%BAmero_de_identificaci%C3%B3n_fiscal |
|
20
|
|
|
*/ |
|
21
|
|
|
class Nif extends AbstractRule |
|
22
|
|
|
{ |
|
23
|
|
|
/** |
|
24
|
|
|
* NIE key values. |
|
25
|
|
|
* |
|
26
|
|
|
* @var array |
|
27
|
|
|
*/ |
|
28
|
|
|
protected static $nieKeyValues = [ |
|
29
|
|
|
'K' => '', |
|
30
|
|
|
'L' => '', |
|
31
|
|
|
'M' => '', |
|
32
|
|
|
'X' => '0', |
|
33
|
|
|
'Y' => '1', |
|
34
|
|
|
'Z' => '2' |
|
35
|
|
|
]; |
|
36
|
|
|
|
|
37
|
|
|
/** |
|
38
|
|
|
* {@inheritdoc} |
|
39
|
|
|
*/ |
|
40
|
30 |
|
public function validate($input) |
|
41
|
|
|
{ |
|
42
|
30 |
|
if (preg_match('/^(\d{8})([A-Z])$/', $input, $matches)) { |
|
43
|
|
|
// DNI |
|
44
|
10 |
|
$code = (int) $matches[1]; |
|
45
|
10 |
|
$control = $matches[2]; |
|
46
|
|
|
|
|
47
|
10 |
|
return substr('TRWAGMYFPDXBNJZSQVHLCKE', $code % 23, 1) === $control; |
|
48
|
20 |
|
} elseif (preg_match('/^([KLMXYZ])(\d{7})([A-Z])$/', $input, $matches)) { |
|
49
|
|
|
// NIE |
|
50
|
10 |
|
$code = (int) (static::$nieKeyValues[$matches[1]] . $matches[2]); |
|
51
|
10 |
|
$control = $matches[3]; |
|
52
|
|
|
|
|
53
|
10 |
|
return substr('TRWAGMYFPDXBNJZSQVHLCKE', $code % 23, 1) === $control; |
|
54
|
10 |
|
} elseif (preg_match('/^([ABCDEFGHJNPQRSUVW])(\d{7})([0-9A-Z])$/', $input, $matches)) { |
|
55
|
|
|
// CIF |
|
56
|
10 |
|
$control = $matches[3]; |
|
57
|
|
|
|
|
58
|
10 |
|
$code = 0; |
|
59
|
10 |
|
$pos = 1; |
|
60
|
10 |
|
foreach (str_split($matches[2]) as $number) { |
|
61
|
10 |
|
if ($pos % 2 === 0) { |
|
62
|
10 |
|
$code += $number; |
|
63
|
10 |
|
} else { |
|
64
|
10 |
|
$code += array_sum(str_split($number * 2)); |
|
65
|
|
|
} |
|
66
|
|
|
|
|
67
|
10 |
|
$pos++; |
|
68
|
10 |
|
} |
|
69
|
10 |
|
$code = str_split($code); |
|
70
|
10 |
|
$key = end($code) === 0 ? 0 : 10 - end($code); |
|
71
|
|
|
|
|
72
|
10 |
|
if (is_numeric($control)) { |
|
73
|
2 |
|
return (int) $key === (int) $control; |
|
74
|
|
|
} |
|
75
|
|
|
|
|
76
|
8 |
|
return substr('JABCDEFGHI', $key % 10, 1) === $control; |
|
77
|
|
|
} |
|
78
|
|
|
|
|
79
|
|
|
return false; |
|
80
|
|
|
} |
|
81
|
|
|
} |
|
82
|
|
|
|