|
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 |
|
array_walk( |
|
60
|
10 |
|
str_split($matches[2]), |
|
|
|
|
|
|
61
|
|
|
function ($value, $key) use (&$code) { |
|
62
|
|
|
if (($key + 1) % 2 === 0) { |
|
63
|
|
|
$code += $value; |
|
64
|
|
|
} else { |
|
65
|
|
|
$code += array_sum(str_split($value * 2)); |
|
66
|
|
|
} |
|
67
|
|
|
} |
|
68
|
|
|
); |
|
69
|
|
|
$controlKey = end(str_split($code)); |
|
|
|
|
|
|
70
|
|
|
if ($controlKey !== 0) { |
|
71
|
|
|
$controlKey = 10 - $controlKey; |
|
72
|
|
|
} |
|
73
|
|
|
|
|
74
|
|
|
if (is_numeric($control)) { |
|
75
|
|
|
return $controlKey === (int) $control; |
|
76
|
|
|
} |
|
77
|
|
|
|
|
78
|
|
|
return substr('JABCDEFGHI', $controlKey % 10, 1) === $control; |
|
79
|
|
|
} |
|
80
|
|
|
|
|
81
|
|
|
return false; |
|
82
|
|
|
} |
|
83
|
|
|
} |
|
84
|
|
|
|