<?php
// Author: Sergi Diaz Planas
/*
Functions related to the validation of identity documents. At this moment, the only
document supported is the Spanish DNI.
*/

class IDValidation
{
    // Concatenation of all DNI control letters
    public static $dniValString = "TRWAGMYFPDXBNJZSQVHLCKE";
    
    // Check if the input string corresponds to a valid DNI number
    public static function validateDNI($string)
    {
        try
        {
            $letter = substr($string, -1);          // extract ending letter
            $digits = substr($string, -9, 8);      // extract digits

            // Check whether the DNI number is legit or not by comparing the result of dividing
            // the number by 23 and the control letter.
            $position = intval($digits) % 23;
            return ($letter == IDValidation::$dniValString[$position]);
        }
        catch (Exception $e)    // The validation will fail if the conversion from chars to integer failed
        {
            return false;
        }
    
    }  
    
    // Return a string containing only numbers and letters from the input string
    public static function cleanUpText($string)
    {
        $clr= "";
    
        for($i=0; $i<strlen($string); $i++)
        {
            // Obtain ASCII code for each character. Copy character if it's a number
            // or a capital letter.
            $ascii = ord($string[$i]); 
            if (($ascii >= 48 && $ascii <= 57) || ($ascii >= 65 && $ascii <= 90))
            {
                $clr = $clr . $string[$i];
            } 
        }
        return $clr;
    }

    // Return an array of strings containing the names to be found in input string
    public static function extractNames($string) 
    {     
        $names = "";

        for($i=0; $i<strlen($string); $i++)
        {
            // Obtain ASCII code for each character. Copy character if it's a capital letter or a line break.
            $ascii = ord($string[$i]); 
            if (($ascii >= 65 && $ascii <= 90) || $ascii == 10)
            {
                $names = $names . $string[$i];
            }
        }
        // Split the names array by breaklines.
        return explode("\n", $names);
    }
}
?>