Completed
Push — master ( 9de2ae...02afd8 )
by Ronan
06:45
created

Nif::validate()   B

Complexity

Conditions 6
Paths 6

Size

Total Lines 33
Code Lines 19

Duplication

Lines 0
Ratio 0 %

Importance

Changes 2
Bugs 1 Features 0
Metric Value
c 2
b 1
f 0
dl 0
loc 33
rs 8.439
cc 6
eloc 19
nc 6
nop 1
1
<?php
2
3
namespace IsoCodes;
4
5
/**
6
 * Class Nif.
7
 *
8
 * About Tax Identification Number (Spain's Número de Identificación Fiscal, NIF)
9
 * or Foreign Identification Number (Spain's Número de Identificación de Extranjeror, NIE):
10
 * The applicable Spanish legislation currently requires that any individual
11
 * or legal entity with economic or professional interests in Spain,
12
 * or involved in a relevant way for tax purposes,
13
 * must hold a tax identification number (in the case of legal entities)
14
 * or a foreigner identity number (for individuals).
15
 *
16
 * @source  https://github.com/alrik11es/spanish-utils
17
 *
18
 * @link    http://es.wikipedia.org/wiki/NIF
19
 * @link    http://www.investinspain.org/guidetobusiness/en/2/art_2_3.html
20
 */
21
class Nif implements IsoCodeInterface
22
{
23
    /**
24
     * NIF and DNI validation.
25
     *
26
     * @param string $nif The NIF or NIE
27
     *
28
     * @return bool
29
     */
30
    public static function validate($nif)
31
    {
32
        $nifCodes = 'TRWAGMYFPDXBNJZSQVHLCKE';
33
34
        if (9 !== strlen($nif)) {
35
            return false;
36
        }
37
        $nif = strtoupper(trim($nif));
38
39
        $sum = (string) self::getCifSum($nif);
40
        $n = 10 - substr($sum, -1);
41
42
        if (preg_match('/^[0-9]{8}[A-Z]{1}$/', $nif)) {
43
            // DNIs
44
            $num = substr($nif, 0, 8);
45
46
            return $nif[8] == $nifCodes[$num % 23];
47
        } elseif (preg_match('/^[XYZ][0-9]{7}[A-Z]{1}$/', $nif)) {
48
            // NIEs normales
49
            $tmp = substr($nif, 1, 7);
50
            $tmp = strtr(substr($nif, 0, 1), 'XYZ', '012').$tmp;
51
52
            return $nif[8] == $nifCodes[$tmp % 23];
53
        } elseif (preg_match('/^[KLM]{1}/', $nif)) {
54
            // NIFs especiales
55
            return $nif[8] == chr($n + 64);
56
        } elseif (preg_match('/^[T]{1}[A-Z0-9]{8}$/', $nif)) {
57
            // NIE extraño
58
            return true;
59
        }
60
61
        return false;
62
    }
63
64
    /**
65
     * Used to calculate the sum of the CIF, DNI and NIE.
66
     *
67
     * @param string $cif
68
     *
69
     * @codeCoverageIgnore
70
     *
71
     * @return mixed
72
     */
73
    public static function getCifSum($cif)
74
    {
75
        $sum = $cif[2] + $cif[4] + $cif[6];
76
77
        for ($i = 1; $i < 8; $i += 2) {
78
            $tmp = (string) (2 * $cif[$i]);
79
            $tmp = $tmp[0] + ((strlen($tmp) == 2) ?  $tmp[1] : 0);
80
            $sum += $tmp;
81
        }
82
83
        return $sum;
84
    }
85
}
86