cakephp / localized

I18n and L10n related CakePHP code
Other
213 stars 179 forks source link

Question - How should I implement the personId for my country? #117

Closed elboletaire closed 8 years ago

elboletaire commented 8 years ago

I would like to implement the personId for Spain, but I've serious doubts about it.

Here in Spain we have at least 7 different personId with different calculations each one:

You can see all the Spanish NIF types on wikipedia: https://es.wikipedia.org/wiki/N%C3%BAmero_de_identificaci%C3%B3n_fiscal

That's referring to person ids (NIF), for companies we use other letters.

The question is... should I implement all of them? If so, I guess I should create a separate method for every different calculation, am I right?

I currently have this (ugly, would refactor obviously) method for testing NIFs on my CakePHP 1.3 apps:

public function validateNif($check, $options = array())
{
    $nif_codes = 'TRWAGMYFPDXBNJZSQVHLCKE';

    $nif = strtoupper(array_pop($check));

    if (isset($options['allowEmpty']) && !$options['allowEmpty'] && empty($nif)) {
        return false;
    }

    $matches = array();

    if (preg_match('/^([0-9]+)([A-Z]{1})$/', $nif, $matches))
    {
        // DNIs
        array_shift($matches);
        list($num, $letter) = $matches;

        return ($letter == $nif_codes[$num % 23]);
    }
    elseif (preg_match('/^[XYZ]([0-9]+)([A-Z]{1})$/', $nif, $matches))
    {
        // NIEs
        array_shift($matches);
        list($num, $letter) = $matches;
        $num = strtr(substr($nif, 0, 1), 'XYZ', '012') . $num;

        return ($letter == $nif_codes[$num % 23]);
    }
    elseif (preg_match('/^[KLM]{1}/', $nif))
    {
        // NIFs especials
        // Vegeu https://es.wikipedia.org/wiki/N%C3%BAmero_de_identificaci%C3%B3n_fiscal
        $sum = (string)$this->getCifSum($nif);
        $n = 10 - substr($sum, -1);

        return ($nif[strlen($nif)-1] == chr($n + 64));
    }

    return false;
}

Note that it does not cover all the cases... and it's very huge right now, but is a good sample of how much calculations do we have to ensure a personId is valid.

elboletaire commented 8 years ago

What I mean is... should I just validate the basic NIF? Or should I consider all the types? If I should consider all of them, should I add options to the basic personId method to test one or more types?

elboletaire commented 8 years ago

Seen the participation, I close the issue and I'll do a MR when I have this implemented.